surfcad-mcp 0.2.4 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -3
- package/data/commands.json +11252 -4296
- package/data/helpers.json +1765 -0
- package/package.json +1 -1
- package/src/helpers.mjs +209 -0
- package/src/prompt/buildGuidance.mjs +21 -0
- package/src/prompt/errorHints.mjs +288 -0
- package/src/prompt/guide.mjs +285 -0
- package/src/prompt/promptSession.mjs +94 -11
- package/src/prompt/promptTools.mjs +31 -3
- package/src/relay.mjs +9 -3
- package/src/server.mjs +107 -19
|
@@ -0,0 +1,285 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `guide` tool: agent know-how delivered by the MCP server itself, so a
|
|
3
|
+
* fresh agent does not learn the dialect by inserting scratch features.
|
|
4
|
+
*
|
|
5
|
+
* The initialize `instructions` stay a short quick-start (under 2 KB, hosts
|
|
6
|
+
* truncate long ones) and point here. The long text lives in the topics
|
|
7
|
+
* below. `start` carries the build guidance verbatim (BUILD_GUIDANCE is the
|
|
8
|
+
* one copy, shared with the app side and pinned by a freshness test).
|
|
9
|
+
*
|
|
10
|
+
* Every statement here describes the current tool contract; the catalog
|
|
11
|
+
* (data/commands.json) and docs/agent/SKILL.md are the sources. Keep each
|
|
12
|
+
* topic under 1,500 words.
|
|
13
|
+
*/
|
|
14
|
+
import { BUILD_GUIDANCE } from './buildGuidance.mjs';
|
|
15
|
+
import { PROMPT_SERVER_INSTRUCTIONS } from './promptTools.mjs';
|
|
16
|
+
import {
|
|
17
|
+
ERROR_TOPIC_CODES,
|
|
18
|
+
ERROR_TOPIC_PREFIX,
|
|
19
|
+
errorTopic,
|
|
20
|
+
errorTopicName,
|
|
21
|
+
EXTRA_ERROR_TOPICS,
|
|
22
|
+
withErrorHint,
|
|
23
|
+
} from './errorHints.mjs';
|
|
24
|
+
import { loadPackageVersion } from '../packageVersion.mjs';
|
|
25
|
+
import { DIALECT_SUMMARY, renderDialectTopic } from '../helpers.mjs';
|
|
26
|
+
|
|
27
|
+
export const GUIDE_TOOL_NAME = 'guide';
|
|
28
|
+
|
|
29
|
+
/** Instructions are truncated by some hosts past a few KB; the test pins this. */
|
|
30
|
+
export const INSTRUCTIONS_MAX_BYTES = 2048;
|
|
31
|
+
|
|
32
|
+
const START = `${BUILD_GUIDANCE}
|
|
33
|
+
|
|
34
|
+
Quick start, three calls after pair:
|
|
35
|
+
1. create_part { name: "Hub" } then insert_tube { outerRadius: 20, innerRadius: 14, height: 40 }. The part is active when create_part returns; its result carries the opaque partId. Numbers are mm.
|
|
36
|
+
2. list_faces { filter: { kind: "planar", normalWithin: { n: [0, 0, 1], deg: 5 } } } → select_faces { keys: [<that row's key>] } → insert_tap_drill_hole { use_selection: true, size: "M5", u: 0, v: 0 } (or insert_hole). The pick is consumed by this one insert.
|
|
37
|
+
3. paint_open {} → paint_set_color { color: "#2f6fdb" } → paint_part {} (or paint_faces { keys }) → paint_confirm {}.
|
|
38
|
+
Then select_clear {} → camera_set { view: "iso" } → screenshot { save_to: true } and show the user.
|
|
39
|
+
|
|
40
|
+
Reading results: every model-changing tool answers { ok, errors, status } with return "status" by default over MCP (no script echo; get_script reads it, get_script { range: { fromFeature, toFeature } } reads one span). status.runState is not_run_yet | ok | failed; errors rows are feature_failed with the viewport's text and a detail reason.
|
|
41
|
+
Ids are opaque surf ids from parts, list_assemblies, create_part, create_assembly; never a path or a display name.
|
|
42
|
+
Topics: guide { topic: "dialect" | "features" | "selection" | "paint" | "limits" | "camera" | "assembly" }; list_helpers { names } documents any script helper.`;
|
|
43
|
+
|
|
44
|
+
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:
|
|
45
|
+
|
|
46
|
+
// --- cube begin id=cube1 ---
|
|
47
|
+
part = Manifold.cube([40, 40, 20], true);
|
|
48
|
+
// --- cube end id=cube1 ---
|
|
49
|
+
|
|
50
|
+
The kind sits between "--- " and " begin"; the optional id=<name> follows it. The strip lists blocks in script order and feature_tree returns them as { id, kind, label, chipLabel, index }; a block without id= is still found and addressed by index. Contour, fillet and chamfer blocks use mode markers (contour-mode extrude / revolve / loft / sweep, fillet-mode, chamfer-mode); a saved contour is its own statement that owns its plane:
|
|
51
|
+
|
|
52
|
+
const c1 = makeCrossSection({ center, normal, x, y }, solveContour({ ... })); // @contour id=c1
|
|
53
|
+
|
|
54
|
+
That trailing marker is the contour id (c1, c2, ...). Extrude, Revolve, Loft and Sweep blocks name the contours they use. A freehand script that keeps this marker style keeps per-feature undo, delete and rollback; a set_script without markers is one feature.
|
|
55
|
+
|
|
56
|
+
What the markers buy you:
|
|
57
|
+
- 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.
|
|
58
|
+
- delete_feature { id | index } removes the block and runs the part; one undo restores it. 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.
|
|
59
|
+
- rollback_to { id | index } moves the rollback bar and re-evaluates up to there without editing the script; rollback_to { clear: true } removes it.
|
|
60
|
+
- 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.
|
|
61
|
+
- get_script { range: { fromFeature: "cube1", toFeature: "fillet2" } } reads one span of blocks.
|
|
62
|
+
|
|
63
|
+
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.
|
|
64
|
+
|
|
65
|
+
Sketch sessions. sketch_begin → sketch_add { tool, ... } / pick_points { kind, keys } → sketch_commit saves a contour; sketch_cancel leaves. In-contour entities are p0, e0, a0, ...; a saved contour is @contour id=c1 in the script.`;
|
|
66
|
+
|
|
67
|
+
const SELECTION = `Selection. Faces and edges are addressed by keys that survive a rerun of the same script and are invalid after a remesh.
|
|
68
|
+
|
|
69
|
+
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). 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.
|
|
70
|
+
|
|
71
|
+
Edges. list_feature_edges gives grouped ids e0, e1, ... (a whole edge chain, the stable choice); list_edges gives raw mesh edges. Both take filter { between: [faceKeyA, faceKeyB], minLength, maxLength, bbox } and page.
|
|
72
|
+
|
|
73
|
+
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 }.
|
|
74
|
+
|
|
75
|
+
use_selection is single use. Every successful rebuild (each insert_*, set_script, undo) clears the picks because they index the mesh that was replaced. Pick, insert once with use_selection: true, then pick again before the next one. With nothing selected that insert answers no_selection and writes nothing (never the default face). Every insert_* / invoke_helper result carries usedSelection: true | false. Omit use_selection to take the helper default: the +Z top face for holes, every convex edge for fillet and chamfer.
|
|
76
|
+
|
|
77
|
+
Fillet and chamfer from a face pick. insert_fillet_edges { use_selection: true, radius } and insert_chamfer_edges { use_selection: true, chamfer } with a face selected take the convex edges whose adjacent face normal is within about 18 degrees of the picked face normal, over the whole body, so on a large part that set can be big and slow (see guide limits). For a precise set, pick grouped edges (list_feature_edges, select_edges { keys: ["e3", "e4"] }) and insert with use_selection: true, or run the card: pick_begin → pick_next → pick_done.
|
|
78
|
+
|
|
79
|
+
Bodies. insert_move { dx, dy, dz } must name its body: body_index or at (a centroid) from list_bodies {}, face_id or face (key) from list_faces, or use_selection: true with a face selected; nothing named is no_body.`;
|
|
80
|
+
|
|
81
|
+
const PAINT = `Paint. Colours live on the assembly document (a colors map keyed by the part's surf id), so they persist across reloads and are written by the next git_save; the same part can carry different colours in two assemblies.
|
|
82
|
+
|
|
83
|
+
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.
|
|
84
|
+
|
|
85
|
+
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.
|
|
86
|
+
|
|
87
|
+
Paint writes the working copy only; nothing reaches the vault until git_save.`;
|
|
88
|
+
|
|
89
|
+
const LIMITS = `Limits and budgets.
|
|
90
|
+
|
|
91
|
+
Each kernel job has 30 seconds. A run past that budget is treated like a crash: the geometry worker is killed and replaced, the mutate result carries crash { reason: "timeout" }, and errors has one geometry_worker_crashed row with workerRestarted: true. Out of memory and wasm aborts report the same way with reason out_of_memory or wasm_abort. Other parts keep building. Do not ask for a reload and do not retry the same script: simplify the part, lower segment counts, split the body, or pick a smaller edge set, then run again.
|
|
92
|
+
|
|
93
|
+
What is expensive: filletEdges / chamferEdges over many edges (a face pick on a large body selects every aligned convex edge; pick grouped edges instead), fillets on swept or lofted bodies, high segment counts on tubes, spheres and revolves, boolean chains over dozens of bodies, list_faces on a detailed part (filter and page it), list_commands without a group.
|
|
94
|
+
|
|
95
|
+
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.
|
|
96
|
+
|
|
97
|
+
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.
|
|
98
|
+
|
|
99
|
+
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.`;
|
|
100
|
+
|
|
101
|
+
const CAMERA = `Camera and screenshots.
|
|
102
|
+
|
|
103
|
+
Named views place the camera on one side of the target and look back at it, Z up: iso (camera at +X +Y +Z), front (camera on -Y, looking +Y, so you see the -Y face), back (camera on +Y), right (camera on +X, looking -X, so you see the +X face), left (camera on -X), top (camera on +Z, looking down, -Y up on screen), bottom (camera on -Z), normal_to_sketch (square to the open sketch plane). For a model whose length runs along X, "right" is therefore an end view, not a side elevation; use an explicit pose for that: camera_set { position: [cx, cy - d, cz], target: [cx, cy, cz] } looks along +Y with X across the screen (up defaults to [0, 0, 1] and the view never rolls; fov is optional).
|
|
104
|
+
|
|
105
|
+
A named view frames the whole assembly as placed, or the highlighted part alone while one is selected (set_active_part or select_parts highlights it; select_clear returns to the assembly), so no camera_fit is needed after it. camera_fit {} frames the model.
|
|
106
|
+
|
|
107
|
+
Before a screenshot for the user: select_clear {} so highlights and pick rings do not paint the frame, then camera_set, then screenshot { save_to: true } (or a path), which writes the PNG on the MCP host and returns { path, size } instead of base64; max_width or scale downscale, format jpeg with quality shrinks further. An open feature card's view offset is not applied to the capture. Take one after each build stage, and before asking the user to judge proportions.`;
|
|
108
|
+
|
|
109
|
+
const ASSEMBLY = `Assemblies, placement and joints.
|
|
110
|
+
|
|
111
|
+
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 and every part row with runState and crash, so a failed part that is not active is visible without switching.
|
|
112
|
+
|
|
113
|
+
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; 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).
|
|
114
|
+
|
|
115
|
+
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.
|
|
116
|
+
|
|
117
|
+
Instances. insert_part { part_id, instance: true, position? } adds another placement of a part already in the open assembly: a new row with its own id, name ("Roller (2)"), pose and visibility that shares the definition's script, run and undo history, so set_script on any one rebuilds all of them from one run. parts lists such rows with instanceOf (the definition id). Joints, part_set_transform, set_part_visible and paint act on the one row; set_script, list_faces, export and FEA act on the shared definition. delete_part on an instance keeps the script while another row still places it; the last row to go takes the script with it. Use instances for repeated hardware (rollers, bolts) instead of copies, and position or a joint to place each one.
|
|
118
|
+
|
|
119
|
+
Placement. part_get_transform { part_id } / part_set_transform { part_id, position?, rotation? } set a rigid placement: translation in mm, rotation as intrinsic XYZ Euler degrees; one assembly undo step. Use it for final positions after the part is built. A placed part's features, previews and picks are in its own frame; list_faces centers are world coordinates.
|
|
120
|
+
|
|
121
|
+
Joints. 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" }. Distance is mm, angle is degrees. Joints are the right tool when two parts must stay related; part_set_transform when one part just needs to sit somewhere.
|
|
122
|
+
|
|
123
|
+
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; insert_pattern_points { points: [{ at, axis }, ...], up } on the fastener part places one instance per hole; insert_array3_d and insert_polar_array cover grids and bolt circles.
|
|
124
|
+
|
|
125
|
+
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.`;
|
|
126
|
+
|
|
127
|
+
/** Topic name → one-line summary and the text. Order is the listing order. */
|
|
128
|
+
export const GUIDE_TOPICS = Object.freeze({
|
|
129
|
+
start: { summary: 'How to build in SurfCAD (block, build, polish, place), a three-call example, how to read results', text: START },
|
|
130
|
+
dialect: { summary: DIALECT_SUMMARY, text: renderDialectTopic() },
|
|
131
|
+
features: { summary: 'Marker blocks, feature ids, edit / delete / rollback / undo, script snippets, sketches', text: FEATURES },
|
|
132
|
+
selection: { summary: 'Face and edge keys, list_faces filters, single-use picks, no_selection, fillet edge sets', text: SELECTION },
|
|
133
|
+
paint: { summary: 'paint_open → paint_set_color → paint_part / paint_faces → paint_confirm; colours persist with the assembly', text: PAINT },
|
|
134
|
+
limits: { summary: 'The 30 s kernel budget, what is slow, worker restarts and stale status, result sizes, pairing errors', text: LIMITS },
|
|
135
|
+
camera: { summary: 'Which side each named view looks from, explicit poses, select_clear before a screenshot, screenshot to file', text: CAMERA },
|
|
136
|
+
assembly: { summary: 'Documents, create_part placement, insert by reference, part instances, part_set_transform vs joints, hardware, git_save', text: ASSEMBLY },
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
/** The core topics, in listing order (the error topics are listed on one line after them). */
|
|
140
|
+
export const GUIDE_TOPIC_NAMES = Object.freeze(Object.keys(GUIDE_TOPICS));
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* errors.<code> topics, rendered from the hint table (errorHints.mjs) so a
|
|
144
|
+
* payload's hint and its topic come from one row. sweep_path has no code of
|
|
145
|
+
* its own (the bridge says insert_failed) and is listed with them.
|
|
146
|
+
*/
|
|
147
|
+
export const ERROR_GUIDE_TOPICS = Object.freeze(Object.fromEntries([
|
|
148
|
+
...ERROR_TOPIC_CODES.map((code) => [errorTopicName(code), errorTopic(code)]),
|
|
149
|
+
...Object.entries(EXTRA_ERROR_TOPICS).map(([name, topic]) => [errorTopicName(name), topic]),
|
|
150
|
+
]));
|
|
151
|
+
|
|
152
|
+
export const ERROR_GUIDE_TOPIC_NAMES = Object.freeze(Object.keys(ERROR_GUIDE_TOPICS));
|
|
153
|
+
|
|
154
|
+
/** Every topic the guide tool and the resources serve: core first, then errors.<code>. */
|
|
155
|
+
export const ALL_GUIDE_TOPICS = Object.freeze({ ...GUIDE_TOPICS, ...ERROR_GUIDE_TOPICS });
|
|
156
|
+
export const ALL_GUIDE_TOPIC_NAMES = Object.freeze(Object.keys(ALL_GUIDE_TOPICS));
|
|
157
|
+
|
|
158
|
+
/** MCP resource URI of a topic: the same text as guide { topic }. */
|
|
159
|
+
export const GUIDE_RESOURCE_SCHEME = 'surfcad://guide/';
|
|
160
|
+
|
|
161
|
+
/** @param {string} topic */
|
|
162
|
+
export function guideResourceUri(topic) {
|
|
163
|
+
return `${GUIDE_RESOURCE_SCHEME}${topic}`;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** The topic a guide resource URI names, or null. */
|
|
167
|
+
export function topicFromResourceUri(uri) {
|
|
168
|
+
if (typeof uri !== 'string' || !uri.startsWith(GUIDE_RESOURCE_SCHEME)) return null;
|
|
169
|
+
const topic = uri.slice(GUIDE_RESOURCE_SCHEME.length);
|
|
170
|
+
return Object.prototype.hasOwnProperty.call(ALL_GUIDE_TOPICS, topic) ? topic : null;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* resources/list rows: one per topic, versioned with the package so a host
|
|
175
|
+
* that pins or caches them can tell a newer server's text apart.
|
|
176
|
+
* @param {string} [version]
|
|
177
|
+
*/
|
|
178
|
+
export function guideResourceList(version = loadPackageVersion()) {
|
|
179
|
+
return ALL_GUIDE_TOPIC_NAMES.map((topic) => ({
|
|
180
|
+
uri: guideResourceUri(topic),
|
|
181
|
+
name: topic,
|
|
182
|
+
title: topic.startsWith(ERROR_TOPIC_PREFIX) ? `SurfCAD error: ${topic.slice(ERROR_TOPIC_PREFIX.length)}` : `SurfCAD guide: ${topic}`,
|
|
183
|
+
description: ALL_GUIDE_TOPICS[topic].summary,
|
|
184
|
+
mimeType: 'text/plain',
|
|
185
|
+
_meta: { version },
|
|
186
|
+
}));
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* resources/read contents for one topic URI, or null for a URI this server
|
|
191
|
+
* does not serve.
|
|
192
|
+
* @param {string} uri
|
|
193
|
+
* @param {string} [version]
|
|
194
|
+
*/
|
|
195
|
+
export function guideResourceContents(uri, version = loadPackageVersion()) {
|
|
196
|
+
const topic = topicFromResourceUri(uri);
|
|
197
|
+
if (!topic) return null;
|
|
198
|
+
return {
|
|
199
|
+
contents: [{
|
|
200
|
+
uri: guideResourceUri(topic),
|
|
201
|
+
mimeType: 'text/plain',
|
|
202
|
+
text: ALL_GUIDE_TOPICS[topic].text,
|
|
203
|
+
_meta: { version },
|
|
204
|
+
}],
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* The initialize `instructions`: the webhook line first (clients and
|
|
210
|
+
* goldens pin it), then a quick-start that fits under INSTRUCTIONS_MAX_BYTES
|
|
211
|
+
* and points at `guide start` for the rest.
|
|
212
|
+
*/
|
|
213
|
+
export const SERVER_INSTRUCTIONS = [
|
|
214
|
+
PROMPT_SERVER_INSTRUCTIONS,
|
|
215
|
+
'',
|
|
216
|
+
`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).`,
|
|
217
|
+
'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, 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: patterns, insert_move, part_set_transform or joints.',
|
|
218
|
+
'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).',
|
|
219
|
+
'Verify: select_clear → camera_set { view } → screenshot { save_to: true }. right puts the camera on +X, front on -Y, top on +Z.',
|
|
220
|
+
'Save only when the user asks: git_save { message } answers consent_pending until the user clicks Allow; retry the same call.',
|
|
221
|
+
'Keep results small: tools default to return: "status" (no script echo; get_script reads it), list_faces { filter, page }, list_commands { group }.',
|
|
222
|
+
].join('\n');
|
|
223
|
+
|
|
224
|
+
export function guideToolDefinition() {
|
|
225
|
+
return {
|
|
226
|
+
name: GUIDE_TOOL_NAME,
|
|
227
|
+
description: `SurfCAD agent guide, plain text. guide { topic } returns one topic; guide {} lists them. Read "start" before the first model call. Topics: ${GUIDE_TOPIC_NAMES.map((n) => `${n} (${GUIDE_TOPICS[n].summary})`).join('; ')}. Error recoveries: errors.<code> for the code an error payload carries (its see field names the topic), e.g. ${ERROR_GUIDE_TOPIC_NAMES.slice(0, 3).join(', ')}. The same texts are the ${GUIDE_RESOURCE_SCHEME}<topic> resources.`,
|
|
228
|
+
inputSchema: {
|
|
229
|
+
type: 'object',
|
|
230
|
+
additionalProperties: false,
|
|
231
|
+
properties: {
|
|
232
|
+
topic: {
|
|
233
|
+
type: 'string',
|
|
234
|
+
enum: [...ALL_GUIDE_TOPIC_NAMES],
|
|
235
|
+
description: 'Which topic to read. Omit to list the topics with one line each.',
|
|
236
|
+
},
|
|
237
|
+
},
|
|
238
|
+
},
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
function topicList() {
|
|
243
|
+
return [
|
|
244
|
+
`SurfCAD guide topics (guide { topic }; also resources ${GUIDE_RESOURCE_SCHEME}<topic>, surfcad-mcp ${loadPackageVersion()}):`,
|
|
245
|
+
...GUIDE_TOPIC_NAMES.map((n) => `- ${n}: ${GUIDE_TOPICS[n].summary}`),
|
|
246
|
+
`- error recoveries, one per code an error payload names in see: ${ERROR_GUIDE_TOPIC_NAMES.join(', ')}`,
|
|
247
|
+
].join('\n');
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/** Second content item of a topic answer: where the same text lives as a resource. */
|
|
251
|
+
function resourcePointer(topic) {
|
|
252
|
+
return `Resource: ${guideResourceUri(topic)} (surfcad-mcp ${loadPackageVersion()}).`;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* @param {Record<string, unknown>} args
|
|
257
|
+
* @returns {{ content: Array<{ type: 'text', text: string }>, isError: boolean }}
|
|
258
|
+
*/
|
|
259
|
+
export function callGuideTool(args) {
|
|
260
|
+
const topic = args && typeof args.topic === 'string' ? args.topic.trim() : '';
|
|
261
|
+
if (!topic) {
|
|
262
|
+
return { content: [{ type: 'text', text: topicList() }], isError: false };
|
|
263
|
+
}
|
|
264
|
+
const entry = ALL_GUIDE_TOPICS[topic];
|
|
265
|
+
if (!entry) {
|
|
266
|
+
return {
|
|
267
|
+
content: [{
|
|
268
|
+
type: 'text',
|
|
269
|
+
text: JSON.stringify(withErrorHint({
|
|
270
|
+
code: 'unknown_topic',
|
|
271
|
+
message: `Unknown guide topic: ${topic}. Topics: ${GUIDE_TOPIC_NAMES.join(', ')}; error topics: ${ERROR_GUIDE_TOPIC_NAMES.join(', ')}.`,
|
|
272
|
+
topics: ALL_GUIDE_TOPIC_NAMES,
|
|
273
|
+
})),
|
|
274
|
+
}],
|
|
275
|
+
isError: true,
|
|
276
|
+
};
|
|
277
|
+
}
|
|
278
|
+
return {
|
|
279
|
+
content: [
|
|
280
|
+
{ type: 'text', text: entry.text },
|
|
281
|
+
{ type: 'text', text: resourcePointer(topic) },
|
|
282
|
+
],
|
|
283
|
+
isError: false,
|
|
284
|
+
};
|
|
285
|
+
}
|
|
@@ -141,6 +141,8 @@ export function createPromptSession(options) {
|
|
|
141
141
|
/** @type {string | null} Bearer token. Process memory only. Never log or return it. */
|
|
142
142
|
let webhookBearer = null;
|
|
143
143
|
let working = false;
|
|
144
|
+
/** @type {'idle' | 'typing' | 'working'} What the tab shows: the pane open with dots, or the spinner. */
|
|
145
|
+
let agentState = 'idle';
|
|
144
146
|
let promptEpoch = 0;
|
|
145
147
|
let workedEpoch = 0;
|
|
146
148
|
let lastAcceptedAt = -Infinity;
|
|
@@ -150,6 +152,15 @@ export function createPromptSession(options) {
|
|
|
150
152
|
let idleTimer = null;
|
|
151
153
|
let chain = Promise.resolve();
|
|
152
154
|
let life = 0;
|
|
155
|
+
/** read_messages { wait_ms } long-poll: resolved when the queue gains an item. */
|
|
156
|
+
/** @type {Array<() => void>} */
|
|
157
|
+
let waiters = [];
|
|
158
|
+
function wakeReaders() {
|
|
159
|
+
if (!waiters.length) return;
|
|
160
|
+
const list = waiters;
|
|
161
|
+
waiters = [];
|
|
162
|
+
for (const resolve of list) resolve();
|
|
163
|
+
}
|
|
153
164
|
|
|
154
165
|
function emit(payload) {
|
|
155
166
|
try {
|
|
@@ -174,24 +185,39 @@ export function createPromptSession(options) {
|
|
|
174
185
|
}
|
|
175
186
|
|
|
176
187
|
/**
|
|
177
|
-
*
|
|
188
|
+
* Send the agent state to the tab. `working` stays on the message for tabs
|
|
189
|
+
* that predate `state`: true for typing and working, false for idle.
|
|
190
|
+
* @param {'idle' | 'typing' | 'working'} state
|
|
178
191
|
* @param {string | null | undefined} id
|
|
179
192
|
* @param {boolean} force
|
|
193
|
+
* @param {string} [label]
|
|
180
194
|
*/
|
|
181
|
-
function
|
|
182
|
-
|
|
195
|
+
function emitState(state, id, force, label) {
|
|
196
|
+
const next = state !== 'idle';
|
|
197
|
+
if (!force && agentState === state) {
|
|
183
198
|
if (next) armIdle();
|
|
184
199
|
return true;
|
|
185
200
|
}
|
|
186
201
|
working = next;
|
|
187
|
-
|
|
202
|
+
agentState = state;
|
|
203
|
+
const msg = { type: PAIR_MSG.AGENT_STATUS, v: 1, working: next, state };
|
|
188
204
|
if (typeof id === 'string' && id) msg.id = id;
|
|
205
|
+
if (typeof label === 'string' && label) msg.label = label.slice(0, 120);
|
|
189
206
|
const sent = emit(msg);
|
|
190
207
|
if (next) armIdle();
|
|
191
208
|
else clearIdle();
|
|
192
209
|
return sent;
|
|
193
210
|
}
|
|
194
211
|
|
|
212
|
+
/**
|
|
213
|
+
* @param {boolean} next
|
|
214
|
+
* @param {string | null | undefined} id
|
|
215
|
+
* @param {boolean} force
|
|
216
|
+
*/
|
|
217
|
+
function emitStatus(next, id, force) {
|
|
218
|
+
return emitState(next ? 'working' : 'idle', id, force);
|
|
219
|
+
}
|
|
220
|
+
|
|
195
221
|
function ack(id, delivery, error) {
|
|
196
222
|
const msg = { type: PAIR_MSG.AGENT_PROMPT_ACK, id, delivery };
|
|
197
223
|
if (error) msg.error = error;
|
|
@@ -278,9 +304,37 @@ export function createPromptSession(options) {
|
|
|
278
304
|
dropped.push(queue.splice(idx, 1)[0]);
|
|
279
305
|
}
|
|
280
306
|
queue.push({ kind: 'prompt', ...prompt });
|
|
307
|
+
wakeReaders();
|
|
281
308
|
return dropped;
|
|
282
309
|
}
|
|
283
310
|
|
|
311
|
+
/**
|
|
312
|
+
* Long-poll for `read_messages { wait_ms }`: resolves true as soon as the
|
|
313
|
+
* queue has an item (a prompt or a cancel notice), false after `ms` with the
|
|
314
|
+
* queue still empty. Never holds a timer past the wait.
|
|
315
|
+
* @param {number} ms
|
|
316
|
+
* @returns {Promise<boolean>}
|
|
317
|
+
*/
|
|
318
|
+
function waitForMessage(ms) {
|
|
319
|
+
if (queue.length > 0) return Promise.resolve(true);
|
|
320
|
+
const wait = Math.max(0, Number(ms) || 0);
|
|
321
|
+
if (wait === 0) return Promise.resolve(false);
|
|
322
|
+
return new Promise((resolve) => {
|
|
323
|
+
let done = false;
|
|
324
|
+
let timer = null;
|
|
325
|
+
const settle = (value) => {
|
|
326
|
+
if (done) return;
|
|
327
|
+
done = true;
|
|
328
|
+
clearTimer(timer);
|
|
329
|
+
waiters = waiters.filter((w) => w !== wake);
|
|
330
|
+
resolve(value);
|
|
331
|
+
};
|
|
332
|
+
const wake = () => settle(true);
|
|
333
|
+
waiters.push(wake);
|
|
334
|
+
timer = setTimer(() => settle(false), wait);
|
|
335
|
+
});
|
|
336
|
+
}
|
|
337
|
+
|
|
284
338
|
/**
|
|
285
339
|
* @param {string} id
|
|
286
340
|
* @param {number} epoch
|
|
@@ -293,6 +347,7 @@ export function createPromptSession(options) {
|
|
|
293
347
|
}
|
|
294
348
|
if (epoch !== life) return;
|
|
295
349
|
queue.push({ kind: 'cancel', id });
|
|
350
|
+
wakeReaders();
|
|
296
351
|
}
|
|
297
352
|
|
|
298
353
|
/**
|
|
@@ -493,17 +548,31 @@ export function createPromptSession(options) {
|
|
|
493
548
|
queue = queue.filter((item) => item.kind === 'cancel' || item.id !== inReplyTo);
|
|
494
549
|
states.set(inReplyTo, 'replied');
|
|
495
550
|
emitStatus(false, inReplyTo, true);
|
|
496
|
-
} else
|
|
551
|
+
} else {
|
|
552
|
+
// A streamed reply means the agent is writing: the tab reopens the chat.
|
|
553
|
+
workedEpoch = promptEpoch;
|
|
554
|
+
emitState('typing', inReplyTo, false);
|
|
555
|
+
}
|
|
497
556
|
return { id: inReplyTo, final: isFinal };
|
|
498
557
|
}
|
|
499
558
|
|
|
500
559
|
/**
|
|
501
|
-
*
|
|
560
|
+
* `state` (typing | working | idle) or the legacy `working` boolean; one is
|
|
561
|
+
* required. `label` is optional text for the tab.
|
|
562
|
+
* @param {{ working?: unknown, state?: unknown, label?: unknown, id?: unknown }} args
|
|
502
563
|
*/
|
|
503
564
|
function setStatus(args) {
|
|
504
|
-
|
|
505
|
-
|
|
565
|
+
const hasState = typeof args?.state === 'string';
|
|
566
|
+
if (hasState && !['typing', 'working', 'idle'].includes(args.state)) {
|
|
567
|
+
throw Object.assign(new Error('state must be typing, working, or idle'), { code: 'bad_args' });
|
|
568
|
+
}
|
|
569
|
+
if (!hasState && typeof args?.working !== 'boolean') {
|
|
570
|
+
throw Object.assign(new Error('state (typing | working | idle) or working (boolean) is required'), { code: 'bad_args' });
|
|
506
571
|
}
|
|
572
|
+
if (args.label != null && (typeof args.label !== 'string' || args.label.length > 120)) {
|
|
573
|
+
throw Object.assign(new Error('label must be a string of at most 120 characters'), { code: 'bad_args' });
|
|
574
|
+
}
|
|
575
|
+
const state = hasState ? args.state : (args.working ? 'working' : 'idle');
|
|
507
576
|
let id;
|
|
508
577
|
if (args.id != null) {
|
|
509
578
|
if (typeof args.id !== 'string' || !args.id || args.id.length > 80) {
|
|
@@ -516,16 +585,28 @@ export function createPromptSession(options) {
|
|
|
516
585
|
return { ok: false, error: 'cancelled' };
|
|
517
586
|
}
|
|
518
587
|
workedEpoch = promptEpoch;
|
|
519
|
-
const sent =
|
|
588
|
+
const sent = emitState(state, id || lastId, true, typeof args.label === 'string' ? args.label : undefined);
|
|
520
589
|
if (!sent) throw Object.assign(new Error('Not paired'), { code: 'not_paired' });
|
|
521
|
-
return { working:
|
|
590
|
+
return { working: state !== 'idle', state };
|
|
522
591
|
}
|
|
523
592
|
|
|
524
|
-
|
|
593
|
+
/**
|
|
594
|
+
* A tool call after a prompt. A call that changes the model (`mutates`)
|
|
595
|
+
* switches the tab to working on its own, even when the agent never set
|
|
596
|
+
* a state; a read-only call only keeps the current state alive.
|
|
597
|
+
* @param {{ mutates?: boolean }} [info]
|
|
598
|
+
*/
|
|
599
|
+
function noteToolCall(info = {}) {
|
|
525
600
|
if (lastId && states.get(lastId) === 'cancelled') {
|
|
526
601
|
if (working) emitStatus(false, lastId, true);
|
|
527
602
|
return;
|
|
528
603
|
}
|
|
604
|
+
const mutates = info?.mutates === true;
|
|
605
|
+
if (mutates && agentState !== 'working') {
|
|
606
|
+
workedEpoch = promptEpoch;
|
|
607
|
+
emitState('working', lastId, false);
|
|
608
|
+
return;
|
|
609
|
+
}
|
|
529
610
|
if (promptEpoch > workedEpoch) {
|
|
530
611
|
workedEpoch = promptEpoch;
|
|
531
612
|
if (!working) emitStatus(true, lastId, false);
|
|
@@ -580,6 +661,7 @@ export function createPromptSession(options) {
|
|
|
580
661
|
webhook = null;
|
|
581
662
|
webhookBearer = null;
|
|
582
663
|
working = false;
|
|
664
|
+
agentState = 'idle';
|
|
583
665
|
promptEpoch = 0;
|
|
584
666
|
workedEpoch = 0;
|
|
585
667
|
lastAcceptedAt = -Infinity;
|
|
@@ -591,6 +673,7 @@ export function createPromptSession(options) {
|
|
|
591
673
|
acceptPrompt,
|
|
592
674
|
cancel,
|
|
593
675
|
readMessages,
|
|
676
|
+
waitForMessage,
|
|
594
677
|
reply,
|
|
595
678
|
setStatus,
|
|
596
679
|
noteToolCall,
|
|
@@ -8,6 +8,9 @@ import { BEARER_MAX, USER_CONTENT_NOTICE } from './promptSession.mjs';
|
|
|
8
8
|
const USER_CONTENT = `${USER_CONTENT_NOTICE} Agent writes still go through the existing write-grant and consent flow. Nothing reaches git without an explicit Save or git_save.`;
|
|
9
9
|
|
|
10
10
|
/** Short line for the MCP initialize `instructions` field. */
|
|
11
|
+
/** read_messages { wait_ms } cap: long enough to skip idle polls, short enough for a host tool timeout. */
|
|
12
|
+
export const READ_MESSAGES_MAX_WAIT_MS = 25_000;
|
|
13
|
+
|
|
11
14
|
export const PROMPT_SERVER_INSTRUCTIONS = 'call register_webhook { url, bearer? } if you can receive https webhooks, otherwise poll read_messages.';
|
|
12
15
|
|
|
13
16
|
/** Exact wording the agent should relay when asking the user for a webhook. */
|
|
@@ -84,6 +87,12 @@ export function promptToolDefinitions() {
|
|
|
84
87
|
maximum: 50,
|
|
85
88
|
description: 'How many queued prompts to take, oldest first. Omit to take the whole queue (at most 50).',
|
|
86
89
|
},
|
|
90
|
+
wait_ms: {
|
|
91
|
+
type: 'integer',
|
|
92
|
+
minimum: 0,
|
|
93
|
+
maximum: READ_MESSAGES_MAX_WAIT_MS,
|
|
94
|
+
description: `Long-poll: when the queue is empty, wait up to this many milliseconds (at most ${READ_MESSAGES_MAX_WAIT_MS}) for a prompt or cancel to arrive before answering, instead of returning an empty list at once. Cuts idle polling between steps; omit or 0 to return immediately.`,
|
|
95
|
+
},
|
|
87
96
|
},
|
|
88
97
|
},
|
|
89
98
|
},
|
|
@@ -112,13 +121,25 @@ export function promptToolDefinitions() {
|
|
|
112
121
|
},
|
|
113
122
|
{
|
|
114
123
|
name: 'set_status',
|
|
115
|
-
description: 'Tell the SurfCAD tab
|
|
124
|
+
description: 'Tell the SurfCAD tab what you are doing with the user\'s prompt: state typing (writing an answer: the chat stays open with typing dots), working (changing the model: the chat collapses and the field shows a spinner), or idle. You do not have to call it for working: the first model-changing tool call after a prompt sets working, a streamed reply_to_user (final false) sets typing, and a final reply or 120 seconds without activity sets idle. Set typing before a long answer so the user reads the chat instead of watching the viewport. Without id it targets the latest prompt. A cancelled id returns { ok: false, error: cancelled }.',
|
|
116
125
|
inputSchema: {
|
|
117
126
|
type: 'object',
|
|
118
127
|
additionalProperties: false,
|
|
119
|
-
required: ['working'],
|
|
120
128
|
properties: {
|
|
121
|
-
|
|
129
|
+
state: {
|
|
130
|
+
type: 'string',
|
|
131
|
+
enum: ['typing', 'working', 'idle'],
|
|
132
|
+
description: 'typing: you are writing an answer (the tab keeps the chat open with typing dots). working: you are changing the model (the tab collapses the chat and shows a spinner). idle: done. Set typing before a long answer; model-changing tool calls set working on their own; a final reply_to_user sets idle.',
|
|
133
|
+
},
|
|
134
|
+
label: {
|
|
135
|
+
type: 'string',
|
|
136
|
+
maxLength: 120,
|
|
137
|
+
description: 'Optional short text for the tab, for example what you are working on.',
|
|
138
|
+
},
|
|
139
|
+
working: {
|
|
140
|
+
type: 'boolean',
|
|
141
|
+
description: 'Legacy form of state: true is working, false is idle. Use state.',
|
|
142
|
+
},
|
|
122
143
|
id: {
|
|
123
144
|
type: 'string',
|
|
124
145
|
description: 'Optional prompt id this status refers to.',
|
|
@@ -143,6 +164,13 @@ export async function callPromptTool(prompts, name, args) {
|
|
|
143
164
|
return { content: [{ type: 'text', text: JSON.stringify(prompts.unregisterWebhook(), null, 2) }] };
|
|
144
165
|
}
|
|
145
166
|
if (name === 'read_messages') {
|
|
167
|
+
if (args.wait_ms != null) {
|
|
168
|
+
const wait = Number(args.wait_ms);
|
|
169
|
+
if (!Number.isInteger(wait) || wait < 0 || wait > READ_MESSAGES_MAX_WAIT_MS) {
|
|
170
|
+
throw Object.assign(new Error(`wait_ms must be an integer from 0 to ${READ_MESSAGES_MAX_WAIT_MS}`), { code: 'bad_args' });
|
|
171
|
+
}
|
|
172
|
+
if (wait > 0 && typeof prompts.waitForMessage === 'function') await prompts.waitForMessage(wait);
|
|
173
|
+
}
|
|
146
174
|
const { messages, images } = prompts.readMessages(args.max);
|
|
147
175
|
if (messages.length === 0) {
|
|
148
176
|
return {
|
package/src/relay.mjs
CHANGED
|
@@ -143,12 +143,14 @@ export class RelaySession {
|
|
|
143
143
|
}
|
|
144
144
|
|
|
145
145
|
/**
|
|
146
|
-
*
|
|
146
|
+
* A tool call after a prompt arrives. A model-changing call (`mutates`)
|
|
147
|
+
* marks the agent working; a read-only call keeps the state alive.
|
|
147
148
|
* Best-effort: a dead socket does not fail the tool call.
|
|
149
|
+
* @param {{ mutates?: boolean }} [info]
|
|
148
150
|
*/
|
|
149
|
-
noteAgentToolCall() {
|
|
151
|
+
noteAgentToolCall(info = {}) {
|
|
150
152
|
try {
|
|
151
|
-
this.#prompts.noteToolCall();
|
|
153
|
+
this.#prompts.noteToolCall(info);
|
|
152
154
|
} catch {
|
|
153
155
|
/* status is advisory */
|
|
154
156
|
}
|
|
@@ -273,9 +275,13 @@ export class RelaySession {
|
|
|
273
275
|
const error = msg.error && typeof msg.error === 'object'
|
|
274
276
|
? msg.error
|
|
275
277
|
: { code: 'bridge_error', message: 'Command refused' };
|
|
278
|
+
// hint and retryable ride along when the tab sent them (the server
|
|
279
|
+
// fills in a hint from its own table when it did not).
|
|
276
280
|
waiter.reject(Object.assign(new Error(error.message || error.code || 'Bridge call failed'), {
|
|
277
281
|
code: error.code,
|
|
278
282
|
details: error.details,
|
|
283
|
+
...(typeof error.hint === 'string' && error.hint ? { hint: error.hint } : {}),
|
|
284
|
+
...(typeof error.retryable === 'boolean' ? { retryable: error.retryable } : {}),
|
|
279
285
|
}));
|
|
280
286
|
return;
|
|
281
287
|
}
|