surfcad-mcp 0.3.2 → 0.3.4
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 +55 -7
- package/bin/surfcad-mcp.js +36 -3
- package/data/commands.json +4424 -129
- package/data/helpers.json +35 -11
- package/package.json +2 -2
- package/src/bridge/bridgePopup.mjs +28 -1
- package/src/bridge/localAddress.mjs +43 -5
- package/src/bridge/relayHub.mjs +31 -9
- package/src/cli.mjs +230 -0
- package/src/commandProtocol.mjs +126 -0
- package/src/errors.mjs +81 -2
- package/src/helpers.mjs +1 -1
- package/src/pairWait.mjs +34 -0
- package/src/prompt/errorHints.mjs +22 -5
- package/src/prompt/guide.mjs +4 -4
- package/src/prompt/promptSession.mjs +62 -23
- package/src/prompt/promptTools.mjs +2 -2
- package/src/relay.mjs +8 -5
- package/src/remote/config.mjs +178 -0
- package/src/remote/httpFallback.mjs +289 -0
- package/src/remote/login.mjs +258 -0
- package/src/remote/logout.mjs +67 -0
- package/src/remote/session.mjs +534 -0
- package/src/remote/tokenStore.mjs +109 -0
- package/src/server.mjs +52 -23
package/data/helpers.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"generatedFrom": "src/lib/surfcad/runtime.js HELPER_FUNCTIONS",
|
|
3
|
-
"count":
|
|
3
|
+
"count": 80,
|
|
4
4
|
"helpers": [
|
|
5
5
|
{
|
|
6
6
|
"name": "shell",
|
|
@@ -170,7 +170,7 @@
|
|
|
170
170
|
},
|
|
171
171
|
{
|
|
172
172
|
"name": "mirror",
|
|
173
|
-
"signature": "mirror(manifold, plane = 'xy', keepOriginal = true)",
|
|
173
|
+
"signature": "mirror(manifold, plane = 'xy', keepOriginal = true, opts = {})",
|
|
174
174
|
"params": [
|
|
175
175
|
{
|
|
176
176
|
"name": "manifold",
|
|
@@ -185,12 +185,17 @@
|
|
|
185
185
|
"name": "keepOriginal",
|
|
186
186
|
"text": "keepOriginal = true",
|
|
187
187
|
"default": "true"
|
|
188
|
+
},
|
|
189
|
+
{
|
|
190
|
+
"name": "opts",
|
|
191
|
+
"text": "opts = {}",
|
|
192
|
+
"default": "{}"
|
|
188
193
|
}
|
|
189
194
|
],
|
|
190
|
-
"description": "
|
|
191
|
-
"doc": "Mirrors a manifold across a plane.\n\n\n\n**Parameters:**\n- `manifold` - The manifold to mirror\n- `plane` -
|
|
195
|
+
"description": "mirror(manifold, plane, keepOriginal, { bodies }) — reflect one body, or the whole solid. plane is 'xy', 'xz', or 'yz' (through the origin) or { center, normal } (a workplane or a planar face). { normal, originOffset } is the same plane. keepOriginal unions the copy with that ...",
|
|
196
|
+
"doc": "Mirrors a manifold across a plane. A named body is mirrored on its own; every other body stays. With no `bodies`, the whole solid is mirrored (older scripts).\n\n\n\n**Parameters:**\n- `manifold` - The manifold to mirror\n- `plane` - `'xy'`, `'xz'`, or `'yz'` (through the origin), or `{ center, normal }` for a workplane or a planar face. `{ normal, originOffset }` is the same plane.\n- `keepOriginal` - If true, unions the copy with the original (default: true). A third argument that is an object is `opts`, and the copy is kept.\n- `opts.bodies` - One body, `{ at }` its centroid, the same point `move()` uses. Overlap throws instead of dropping the original.\n\n---",
|
|
192
197
|
"examples": [
|
|
193
|
-
"//
|
|
198
|
+
"// Symmetric part across the YZ plane through the origin\nconst half = Manifold.cube([20, 10, 10]);\nconst full = mirror(half, 'yz', true);\nreturn full;\n\n// One body across a workplane, keeping the original\npart = mirror(part, { center: [30, 0, 0], normal: [1, 0, 0] }, true, { bodies: [{ at: [20, 0, 0] }] });"
|
|
194
199
|
]
|
|
195
200
|
},
|
|
196
201
|
{
|
|
@@ -1381,7 +1386,7 @@
|
|
|
1381
1386
|
}
|
|
1382
1387
|
],
|
|
1383
1388
|
"description": "filletEdges(part, edges, radius, opts) — circular fillet of radius r on a SET of straight convex edges. edges = objects from convexEdges() (required: they carry the mesh indices this helper needs; edges from OTHER selections can still be filleted if the edge object has {a, b, ...",
|
|
1384
|
-
"doc": "Circular fillet of radius `r` on a **set** of straight convex edges\n(Manifold has no native fillet; this is a geometric construction).\n`edges` must come from `convexEdges()` (it needs the per-edge vertex\nindices to recover the in-face directions — and the in-face geometry, not\njust the normals, is what makes non-90° corners work). `radius` is a\nnumber (same `r` for all edges) or a `number[]` parallel to `edges`\n(per-edge radii). `opts` (optional): `{ sphericalCorners: true }`\n(see below).\n\n\n\n**How it works (per edge).** In the cross-section perpendicular to the\nedge, the two faces meet at interior angle θ. The fillet arc of radius `r`\nis tangent to both faces at distance `t = r/tan(θ/2)` from the corner,\ncentered on the interior angle bisector at `r/sin(θ/2)`. The removed\ncross-section is the sliver `r·t − ½·r²·(π−θ)` (= `r²(1−π/4)` at 90°).\nThe cutter is exactly `parallelepiped(t·f0, t·f1, edge) − cylinder(r)` —\nboth are exact primitives, so the result is geometrically exact for any\nθ. The in-face boundary directions `f0`/`f1` come from the adjacent\ntriangles' third vertices (robust to Manifold's `faceID` grouping, which\ncan merge faces from different planes into one). All cutters for the set\nare unioned and subtracted once, so shared-corner interactions resolve\nthrough the boolean — matching analytic inclusion-exclusion for adjacent\nedges (two cutters at a corner, three at a box corner).\n\n**Closed circular rims (v2, 2026-09-08).** A curved surface (a cylinder\nwall, a hole wall) meeting a planar face tessellates as a LOOP of many\nshort straight mesh edges — e.g. a Ø12 hole rim at 48 segments has\n~0.78mm segments. In v1 this loop was filleted PER SEGMENT, and any\nsegment failing the size guard below was silently skipped — for a real\nfillet radius (r=1 on that Ø12 rim, t=1 > 0.45·0.78mm) EVERY segment\nfailed, so the whole rim's fillet silently vanished with no error. v2\ndetects a maximal chain of input edges that (a) share consecutive mesh\nvertices, (b) turn ≤30° at each shared vertex (a genuine polygon corner\nturns 60-180°; a tessellated circle turns 360/segs°, well under 30° for\nany segs≥12), and (c) keep the same interior angle θ (within 3°) and the\nsame radius. If that chain closes into a loop AND fits an exact circle\n(3-point circumcircle, verified against every other vertex in the run),\nthe WHOLE rim is filleted as one exact revolved cutter — the same 2D\ncorner-sliver cross-section swept a full 360° around the rim's own axis\n— instead of per-segment boxes, so the old per-segment size guard does\nnot apply to it at all. `convexEdges(part)` (unfiltered, or filtered only\nby position/orientation — do NOT filter out short segments) is the\ncorrect input; a \"filter out the tiny seam edges\" workaround is no longer\nnecessary or correct for a genuine curved rim. If a chain doesn't close,\nor doesn't fit a clean circle (mixed/non-circular topology), filletEdges\nfalls back to the v1 per-edge construction for every edge in that chain,\nincluding the size guard below — so isolated straight edges and\nnon-circular chains behave exactly as before.\n\n**Constraints (v1 per-edge path — still the fallback for singleton edges\nand non-circular chains).**\n- **Planar faces only** — each adjacent face must be planar at the edge\n (checked: all same-face neighbor triangles coplanar within 1e-3). A\n fillet touching a curved face **throws** for a SINGLETON edge. (A\n successfully-fit closed circular run skips this check entirely — the\n circle fit plus per-vertex on-circle verification is a strictly more\n specific validity proof for \"this chain is one smooth curved feature\"\n than the singleton check, which was never designed to look past one\n edge.)\n- **Convex edges only** — concave corners (rounding = adding material)\n throw. `convexEdges()` already filters these out; passing them directly\n also throws via the ball probe. (Applies to every edge, run or not.)\n- **Size guard** — for a SINGLETON edge (or an edge in a chain that didn't\n qualify as a closed circular run), `r` must satisfy `t < 0.45·L` where\n `L` is the edge length; individual edges that FAIL this guard are\n **skipped** when other edges still produce cutters. If **every** requested\n edge is skipped / rejected, `filletEdges` **throws** (no silent unchanged\n part). Closed-circular-run members are exempt — their per-segment `L` is a\n tessellation artifact, not a signal that the feature is too small.\n- **Arc tessellation** — a SINGLETON edge's fillet arc is an inscribed\n 384-gon: the result volume sits at most `L·(π−(n/2)·sin(2π/n))·r²` BELOW\n the circle-exact value per edge. A closed run's revolve resolution is\n tied to the rim's own mesh segment count exactly (verified necessary\n for a numerically clean boolean: Manifold's boolean difference between\n the original n-segment part and a cutter revolved at a DIFFERENT\n segment count — even a clean integer multiple of n — silently removes\n LESS than the cutter's own volume), with a separately-tunable, finer\n resolution for the small fillet arc itself.\n- **Known gaps** — an OPEN curved run (a fillet on a less-than-360° arc)\n does not get the closed-run treatment and can still lose short segments\n to the size guard; not exercised by any part in the current corpus\n (every curved surface here comes from a full-revolution primitive). A\n closed-run cutter throws (rather than silently clipping) if `r` is so\n large the fillet would revolve through the rim's own axis.\n\n**Spherical corner caps** (`opts.sphericalCorners: true`). Three fillets\nmeeting at a box corner converge to a sharp cusp point — the plain\nresult is a valid but pointy corner. With this option the cusp
|
|
1389
|
+
"doc": "Circular fillet of radius `r` on a **set** of straight convex edges\n(Manifold has no native fillet; this is a geometric construction).\n`edges` must come from `convexEdges()` (it needs the per-edge vertex\nindices to recover the in-face directions — and the in-face geometry, not\njust the normals, is what makes non-90° corners work). `radius` is a\nnumber (same `r` for all edges) or a `number[]` parallel to `edges`\n(per-edge radii). `opts` (optional): `{ sphericalCorners: true }`\n(see below).\n\n\n\n**How it works (per edge).** In the cross-section perpendicular to the\nedge, the two faces meet at interior angle θ. The fillet arc of radius `r`\nis tangent to both faces at distance `t = r/tan(θ/2)` from the corner,\ncentered on the interior angle bisector at `r/sin(θ/2)`. The removed\ncross-section is the sliver `r·t − ½·r²·(π−θ)` (= `r²(1−π/4)` at 90°).\nThe cutter is exactly `parallelepiped(t·f0, t·f1, edge) − cylinder(r)` —\nboth are exact primitives, so the result is geometrically exact for any\nθ. The in-face boundary directions `f0`/`f1` come from the adjacent\ntriangles' third vertices (robust to Manifold's `faceID` grouping, which\ncan merge faces from different planes into one). All cutters for the set\nare unioned and subtracted once, so shared-corner interactions resolve\nthrough the boolean — matching analytic inclusion-exclusion for adjacent\nedges (two cutters at a corner, three at a box corner).\n\n**Closed circular rims (v2, 2026-09-08).** A curved surface (a cylinder\nwall, a hole wall) meeting a planar face tessellates as a LOOP of many\nshort straight mesh edges — e.g. a Ø12 hole rim at 48 segments has\n~0.78mm segments. In v1 this loop was filleted PER SEGMENT, and any\nsegment failing the size guard below was silently skipped — for a real\nfillet radius (r=1 on that Ø12 rim, t=1 > 0.45·0.78mm) EVERY segment\nfailed, so the whole rim's fillet silently vanished with no error. v2\ndetects a maximal chain of input edges that (a) share consecutive mesh\nvertices, (b) turn ≤30° at each shared vertex (a genuine polygon corner\nturns 60-180°; a tessellated circle turns 360/segs°, well under 30° for\nany segs≥12), and (c) keep the same interior angle θ (within 3°) and the\nsame radius. If that chain closes into a loop AND fits an exact circle\n(3-point circumcircle, verified against every other vertex in the run),\nthe WHOLE rim is filleted as one exact revolved cutter — the same 2D\ncorner-sliver cross-section swept a full 360° around the rim's own axis\n— instead of per-segment boxes, so the old per-segment size guard does\nnot apply to it at all. `convexEdges(part)` (unfiltered, or filtered only\nby position/orientation — do NOT filter out short segments) is the\ncorrect input; a \"filter out the tiny seam edges\" workaround is no longer\nnecessary or correct for a genuine curved rim. If a chain doesn't close,\nor doesn't fit a clean circle (mixed/non-circular topology), filletEdges\nfalls back to the v1 per-edge construction for every edge in that chain,\nincluding the size guard below — so isolated straight edges and\nnon-circular chains behave exactly as before.\n\n**Constraints (v1 per-edge path — still the fallback for singleton edges\nand non-circular chains).**\n- **Planar faces only** — each adjacent face must be planar at the edge\n (checked: all same-face neighbor triangles coplanar within 1e-3). A\n fillet touching a curved face **throws** for a SINGLETON edge. (A\n successfully-fit closed circular run skips this check entirely — the\n circle fit plus per-vertex on-circle verification is a strictly more\n specific validity proof for \"this chain is one smooth curved feature\"\n than the singleton check, which was never designed to look past one\n edge.)\n- **Convex edges only** — concave corners (rounding = adding material)\n throw. `convexEdges()` already filters these out; passing them directly\n also throws via the ball probe. (Applies to every edge, run or not.)\n- **Size guard** — for a SINGLETON edge (or an edge in a chain that didn't\n qualify as a closed circular run), `r` must satisfy `t < 0.45·L` where\n `L` is the edge length; individual edges that FAIL this guard are\n **skipped** when other edges still produce cutters. If **every** requested\n edge is skipped / rejected, `filletEdges` **throws** (no silent unchanged\n part). Closed-circular-run members are exempt — their per-segment `L` is a\n tessellation artifact, not a signal that the feature is too small.\n- **Arc tessellation** — a SINGLETON edge's fillet arc is an inscribed\n 384-gon: the result volume sits at most `L·(π−(n/2)·sin(2π/n))·r²` BELOW\n the circle-exact value per edge. A closed run's revolve resolution is\n tied to the rim's own mesh segment count exactly (verified necessary\n for a numerically clean boolean: Manifold's boolean difference between\n the original n-segment part and a cutter revolved at a DIFFERENT\n segment count — even a clean integer multiple of n — silently removes\n LESS than the cutter's own volume), with a separately-tunable, finer\n resolution for the small fillet arc itself.\n- **Known gaps** — an OPEN curved run (a fillet on a less-than-360° arc)\n does not get the closed-run treatment and can still lose short segments\n to the size guard; not exercised by any part in the current corpus\n (every curved surface here comes from a full-revolution primitive). A\n closed-run cutter throws (rather than silently clipping) if `r` is so\n large the fillet would revolve through the rim's own axis.\n\n**Spherical corner caps** (`opts.sphericalCorners: true`). Three fillets\nmeeting at a box corner converge to a sharp cusp point — the plain\nresult is a valid but pointy corner. With this option the cusp is\nreplaced by the sphere of radius `r` centered on the trihedral incenter\n(equidistant `r` from all three faces and lying ON all three fillet\ncylinder axes): a spherical corner patch that is tangent to each\nfillet sail along a circle (C1 junction) and to each face at one point —\ni.e. the true CAD r/r/r rounded corner. An exact right-angle corner is\nbuilt as meshes (each edge cutter stops at the junction plane and one\npocket solid holds the sphere octant) that share their ring vertices, so\nnothing is cut between tangent surfaces: on a 40×30×20 box each sail is\none face, each corner is one face (`<block>.corner[k]`, see\n[architecture.md](architecture.md) → Face graph walls), and the result\nhas no needle triangles. v1 scope: applies only at vertices where exactly\nTHREE filleted edges meet at ~90° with EQUAL radii; other corners keep\nthe cusp, and non-triple corners are unaffected (the option is a no-op\non an edge set whose corners have fewer than three fillets). A corner a\nfraction of a degree off square keeps the older ball cut.\n\n**Verified** against analytic volumes: single edge, 4 top edges, all 12\nbox edges (pair + triple corner overlaps), an obtuse wedge (90°/116°/153°\ncorners), and mixed per-edge radii — see `cadgen-workspace/reports/c6-report.md`.\n\n---\n\n\n---\n\n## Cross-section substrate (Slice 21)\n\nReusable **plane + 2D profile** value for later edge→sweep path,\nfillet-via-sweep, then extrude/revolve/loft siblings. This slice ships the\nsubstrate only — those followers are **not** started here.\n\nPlane comes from `workplaneFromFace` (primary mobile path: selected planar\nface). Profile is a light 2D shape in plane UV. The returned value is a plain\nobject (no class inheritance):",
|
|
1385
1390
|
"examples": [
|
|
1386
1391
|
"// round all 12 box corners at r=3\npart = filletEdges(part, convexEdges(part), 3);\n\n// fillet only the 4 vertical corners, mixed radii per edge\nconst vert = convexEdges(part).filter(e => Math.abs(e.tangent[2]) > 0.99);\npart = filletEdges(part, vert, [3, 3, 5, 5]);\n\n// fully-rounded box corners: r=5 fillets + spherical corner patches\npart = filletEdges(part, convexEdges(part), 5, { sphericalCorners: true });",
|
|
1387
1392
|
"{\n kind: 'crossSection',\n plane: { center, normal, x, y }, // workplaneFromFace frame\n profile: { type: 'circle'|'rectangle'|'polygon', ... },\n contours: [ [[u,v], ...] ], // ready for makeExtrude / sweep later\n}"
|
|
@@ -1598,7 +1603,7 @@
|
|
|
1598
1603
|
}
|
|
1599
1604
|
],
|
|
1600
1605
|
"description": "makeSweepPath(edges, opts?) → reusable ordered sweep path / wire. edges: feature / convexEdges-style {a,b,va,vb,...} (selection or query). ",
|
|
1601
|
-
"doc": "**Parameters:**\n- `edges` — array of feature edges `{ a, b, va, vb, length?, key? }` (from\n `convexEdges` / Edge pick selection)\n- `opts.reverse` — optional; reverse polyline direction\n\n**Returns:** `{ kind:'sweepPath', closed, points, length, edgeCount }`\n\n**Loud failures (script):** empty / unusable edges;
|
|
1606
|
+
"doc": "**Parameters:**\n- `edges` — array of feature edges `{ a, b, va, vb, length?, key? }` (from\n `convexEdges` / Edge pick selection)\n- `opts.reverse` — optional; reverse polyline direction\n\n**Returns:** `{ kind:'sweepPath', closed, points, length, edgeCount }`\n\n**Edge sets.** The edges need not form one chain. Every connected chain or\nloop is a component; a vertex where three or more edges meet (a box corner)\nsplits its component into chains that end there. One component is returned\nas the plain path. Several come back as the longest component (so\n`sweep` / `sweepPoints` keep a usable path) with `components` listing every\nchain, `edgeCount` and `setLength` over the whole set, and `junctions`. The\nbox's twelve edges are twelve chains and eight junctions; four vertical\nedges plus the top rim are eight chains and four junctions.\n`filletAlongPath` fillets every component. Nothing is dropped: an earlier\nversion kept the largest piece of a broken loop and filleted that.\n\n**Loud failures (script):** empty / unusable edges; walk failure.\n\n**UI:** FEAT rail → **Path** → param popup (Body, Reverse). Uses current Edge\nselection + Tangent chip. Viewport preview shows order/direction (green→magenta\ngradient polyline, chevron arrows, start/end markers) — distinct from the\norange #20 selection halo. Auto-Run unchanged.\n\n**Non-goals (Slice 22):** fillet-via-sweep shipped in Slice 23; extrude/revolve/loft\nstill wait for Product brief; Profile API changes; full sketcher; C6 soft counters.\n\n\n---\n\n## Fillet via swept cross-section (Slice 23)\n\nUnlock fillets on **compound / curved-adjacent** edges (cases where C6\n`filletEdges` throws `curved-face fillet not supported`, e.g. post-fillet seams\nor when you prefer Path-driven construction) by sweeping a cutter along\n`makeSweepPath` and boolean-subtracting.",
|
|
1602
1607
|
"examples": [
|
|
1603
1608
|
"let part = Manifold.cube([40, 30, 20], true);\nconst top = facesByNormal(part, [0, 0, 1])[0];\nconst fr = workplaneFromFace(part, top);\n// Script path: pass convexEdges (or a filtered subset) — UI emits mid-matched selection.\nconst rim = convexEdges(part); // or selected edges from Edge pick + Tangent\nconst path = makeSweepPath(rim); // { kind:'sweepPath', closed, points, length, edgeCount }\n// Later: sweepPoints(profile, path.points, { closed: path.closed })\nreturn part;"
|
|
1604
1609
|
]
|
|
@@ -1626,7 +1631,7 @@
|
|
|
1626
1631
|
}
|
|
1627
1632
|
],
|
|
1628
1633
|
"description": "filletAlongPath(part, path, radius, opts?) Sweep a dihedral fillet (or equal-leg chamfer) along path → boolean subtract. ",
|
|
1629
|
-
"doc": "**Parameters:**\n- `part` — manifold body\n- `path` — `makeSweepPath` result, `{ points, closed }`, or `points[]` (+ `opts.closed`)\n- `radius` — fillet radius, or chamfer leg length (> 0)\n- `opts.profile` — `'fillet'` (default) or `'chamfer'`\n- `opts.segments` — arc segments for the fillet profile (default 12)\n- `opts.initialNormal` — optional. When set, keeps the legacy 90° wedge and a single start-frame RMF. Leave unset for the dihedral cutter.\n- `opts.arcSamples` / `opts.extrudeSegments` — legacy RMF sweep quality only\n\n**Path / cutter:** open chains sweep the wedge along a **linear polyline** of the\nedge wire (not Catmull-Rom — spline bulge left purple scraps). Closed paths that\nfit a circle use a **revolved meridian wedge** (C6-style, phase-locked to the\ntessellation). **Fillet-on-fillet / path on a prior blend:** keep the full wire,\nincluding tessellated micro rim arcs — do **not** skip those segments (skipping\nleft a gap instead of wrapping the prior fillet). The quarter-circle / chamfer\ncutter origin is pushed into a rear exterior bumper `(−e,−e)` plus thickness-`e`\nstrips so the boolean consumes coincident sliver sheets **without growing the\nrequested blend** (realized first-quadrant extent stays at `r`). Mixed-radius /\ntighter follow-on sweeps use a deeper rear pad than the original 4%·r sliver.\nDisconnected cutter scraps are dropped via `decompose` when present.\nLoud-fail if the kept solid is still scrap-sheet dirty.\n\n**Dihedral cutter:** each path segment is probed from the two adjacent triangles\n(in-face rays from the third vertices — not face normals, not faceID groups).\n`N` lies in one face, `B = T×N` points toward the other, and the profile is built\nfor that interior angle θ: fillet setback `t = r/tan(θ/2)`, removed area\n`r·t − ½·r²·(π−θ)` (at 90° this is `r²(1−π/4)`); chamfer area `½·c²·sin θ`\n(at 90° this is `½·c²`). Segments whose θ stays within 3° share one profile and\nare swept with those per-segment frames. A smooth segment that is not a convex\nedge keeps the neighboring frame, so a compound chain can still sweep. A closed run that fits a circle is\nrevolved. `opts.initialNormal` is the only path that still uses a 90° wedge and\none start-frame RMF. The exterior bumper still keeps cutter legs off the faces;\nat 90° it matches the old `(−e,−e)` pad.",
|
|
1634
|
+
"doc": "**Parameters:**\n- `part` — manifold body\n- `path` — `makeSweepPath` result, `{ points, closed }`, or `points[]` (+ `opts.closed`).\n A `makeSweepPath` result with `components` (an edge set: disjoint edges,\n several loops, a pick with junctions) fillets every component: each builds\n its cutter against the untouched solid, with its own frames, then one\n n-way subtract and the set-level guards (removed volume against the summed\n expectation, scrap components, degenerate triangles). Chains meeting at a\n vertex are cut from the same solid, so the shared vertex is still there\n when the second chain is probed. A vertex where exactly three convex\n chains end at right angles gets the spherical corner patch (one face,\n `<block>.corner[k]`), built as a mesh on the chains' own end rings; any\n other junction keeps the cusp. `filletAlongPath(part,\n makeSweepPath(convexEdges(part)), r)` on a box is the fully rounded box.\n- `radius` — fillet radius, or chamfer leg length (> 0)\n- `opts.profile` — `'fillet'` (default) or `'chamfer'`\n- `opts.segments` — arc segments for the fillet profile (default 12)\n- `opts.initialNormal` — optional. When set, keeps the legacy 90° wedge and a single start-frame RMF. Leave unset for the dihedral cutter.\n- `opts.arcSamples` / `opts.extrudeSegments` — legacy RMF sweep quality only\n\n**Path / cutter:** open chains sweep the wedge along a **linear polyline** of the\nedge wire (not Catmull-Rom — spline bulge left purple scraps). Closed paths that\nfit a circle use a **revolved meridian wedge** (C6-style, phase-locked to the\ntessellation). **Fillet-on-fillet / path on a prior blend:** keep the full wire,\nincluding tessellated micro rim arcs — do **not** skip those segments (skipping\nleft a gap instead of wrapping the prior fillet). The quarter-circle / chamfer\ncutter origin is pushed into a rear exterior bumper `(−e,−e)` plus thickness-`e`\nstrips so the boolean consumes coincident sliver sheets **without growing the\nrequested blend** (realized first-quadrant extent stays at `r`). Mixed-radius /\ntighter follow-on sweeps use a deeper rear pad than the original 4%·r sliver.\nDisconnected cutter scraps are dropped via `decompose` when present.\nLoud-fail if the kept solid is still scrap-sheet dirty.\n\n**Dihedral cutter:** each path segment is probed from the two adjacent triangles\n(in-face rays from the third vertices — not face normals, not faceID groups).\n`N` lies in one face, `B = T×N` points toward the other, and the profile is built\nfor that interior angle θ: fillet setback `t = r/tan(θ/2)`, removed area\n`r·t − ½·r²·(π−θ)` (at 90° this is `r²(1−π/4)`); chamfer area `½·c²·sin θ`\n(at 90° this is `½·c²`). Segments whose θ stays within 3° share one profile and\nare swept with those per-segment frames. A smooth segment that is not a convex\nedge keeps the neighboring frame, so a compound chain can still sweep. A closed run that fits a circle is\nrevolved. `opts.initialNormal` is the only path that still uses a 90° wedge and\none start-frame RMF. The exterior bumper still keeps cutter legs off the faces;\nat 90° it matches the old `(−e,−e)` pad.",
|
|
1630
1635
|
"examples": [
|
|
1631
1636
|
"let part = Manifold.cube([40, 30, 20], true);\n// Planar–planar (unchanged):\nconst e = convexEdges(part).filter(/* … */);\npart = filletEdges(part, e, 3, { sphericalCorners: true });\n\n// Sweep fillet (curved-adjacent / closed rim / post-fillet seam):\nconst rim = /* Edge pick + Tangent → selection, or convexEdges subset */;\nconst path = makeSweepPath(rim); // { kind:'sweepPath', closed, points, length, edgeCount }\npart = filletAlongPath(part, path, 2); // dihedral fillet\n// part = filletAlongPath(part, path, 2, { profile: 'chamfer' }); // equal-leg chamfer\nreturn part;"
|
|
1632
1637
|
]
|
|
@@ -1645,7 +1650,7 @@
|
|
|
1645
1650
|
}
|
|
1646
1651
|
],
|
|
1647
1652
|
"description": "edge(part, id) → mesh segments of one boundary edge. id is the integer shown as e{id} in Fillet mode. ",
|
|
1648
|
-
"doc": "Fillet-mode labels and Accept use these instead of tessellation keys like\n`\"1268-1269\"`.\n\n\n\n**How ids are assigned (current mesh only):**\n- A **face id** is the minimum Manifold `faceID` in a coplanar connected group\n (normals within 0.1°, plane offset within 1e-3). Shown as `fN`.\n- A **boundary edge id** groups triangle segments that share one unordered face\n pair and connect through vertices. One CAD edge that was tessellated collinearly\n is one id (`eN`). A curved rim, where each facet is its own face, stays many ids.\n- Ids are sorted by `(min face, max face, midpoint)` so a fresh cube is stable.\n- `edge(part, id)` and `edgesBetween(part, faceA, faceB)` return\n `{ key, a, b, va, vb, mid, length }` segments for `makeSweepPath`.\n `edgesBetween` throws when that pair has more than one boundary — use `edge`.\n\n**Rematch limits:** ids are not a CAD feature tree. Manifold `faceID` is\nprovenance and can merge or split after a boolean, and two disconnected regions\ncan share one minimum faceID. `edge` / `edgesBetween` throw `re-pick edges`\nwhen the id or pair is missing. Re-running a script from scratch is stable only\nwhile the solid *before* the fillet is deterministic. After geometry changes,\nre-pick in Fillet mode (the labels update) rather than editing a stale id.\n\n**Loud failures (script):** bad/empty path; radius ≤ 0;
|
|
1653
|
+
"doc": "Fillet-mode labels and Accept use these instead of tessellation keys like\n`\"1268-1269\"`.\n\n\n\n**How ids are assigned (current mesh only):**\n- A **face id** is the minimum Manifold `faceID` in a coplanar connected group\n (normals within 0.1°, plane offset within 1e-3). Shown as `fN`.\n- A **boundary edge id** groups triangle segments that share one unordered face\n pair and connect through vertices. One CAD edge that was tessellated collinearly\n is one id (`eN`). A curved rim, where each facet is its own face, stays many ids.\n- Ids are sorted by `(min face, max face, midpoint)` so a fresh cube is stable.\n- `edge(part, id)` and `edgesBetween(part, faceA, faceB)` return\n `{ key, a, b, va, vb, mid, length }` segments for `makeSweepPath`.\n `edgesBetween` throws when that pair has more than one boundary — use `edge`.\n\n**Rematch limits:** ids are not a CAD feature tree. Manifold `faceID` is\nprovenance and can merge or split after a boolean, and two disconnected regions\ncan share one minimum faceID. `edge` / `edgesBetween` throw `re-pick edges`\nwhen the id or pair is missing. Re-running a script from scratch is stable only\nwhile the solid *before* the fillet is deterministic. After geometry changes,\nre-pick in Fillet mode (the labels update) rather than editing a stale id.\n\n**Loud failures (script):** bad/empty path; radius ≤ 0; cannot orient\ncutter; sweep/boolean failure; ~0 volume removed (wrong orientation); near-no-op vs\nexpected wedge volume; empty result. Never silent wrong solid.\n\n**Soft-fail (UI):** empty / disconnected / branched edge selection — same messages\nas Path; no broken JS inserted.",
|
|
1649
1654
|
"examples": [
|
|
1650
1655
|
"let part = Manifold.cube([40, 30, 20], true);\nconst cat = boundaryEdges(part); // [{ id, faceA, faceB, mid, length }, ...]\nconst one = cat[0];\nconst selEdges = edgesBetween(part, one.faceA, one.faceB);\n// partial chain: [id, id].flatMap((id) => edge(part, id))\nconst path = makeSweepPath(selEdges);\npart = filletAlongPath(part, path, 2);\nreturn part;"
|
|
1651
1656
|
]
|
|
@@ -1668,7 +1673,7 @@
|
|
|
1668
1673
|
}
|
|
1669
1674
|
],
|
|
1670
1675
|
"description": "edgesBetween(part, faceA, faceB) → segments of the only boundary between those face ids. ",
|
|
1671
|
-
"doc": "Fillet-mode labels and Accept use these instead of tessellation keys like\n`\"1268-1269\"`.\n\n\n\n**How ids are assigned (current mesh only):**\n- A **face id** is the minimum Manifold `faceID` in a coplanar connected group\n (normals within 0.1°, plane offset within 1e-3). Shown as `fN`.\n- A **boundary edge id** groups triangle segments that share one unordered face\n pair and connect through vertices. One CAD edge that was tessellated collinearly\n is one id (`eN`). A curved rim, where each facet is its own face, stays many ids.\n- Ids are sorted by `(min face, max face, midpoint)` so a fresh cube is stable.\n- `edge(part, id)` and `edgesBetween(part, faceA, faceB)` return\n `{ key, a, b, va, vb, mid, length }` segments for `makeSweepPath`.\n `edgesBetween` throws when that pair has more than one boundary — use `edge`.\n\n**Rematch limits:** ids are not a CAD feature tree. Manifold `faceID` is\nprovenance and can merge or split after a boolean, and two disconnected regions\ncan share one minimum faceID. `edge` / `edgesBetween` throw `re-pick edges`\nwhen the id or pair is missing. Re-running a script from scratch is stable only\nwhile the solid *before* the fillet is deterministic. After geometry changes,\nre-pick in Fillet mode (the labels update) rather than editing a stale id.\n\n**Loud failures (script):** bad/empty path; radius ≤ 0;
|
|
1676
|
+
"doc": "Fillet-mode labels and Accept use these instead of tessellation keys like\n`\"1268-1269\"`.\n\n\n\n**How ids are assigned (current mesh only):**\n- A **face id** is the minimum Manifold `faceID` in a coplanar connected group\n (normals within 0.1°, plane offset within 1e-3). Shown as `fN`.\n- A **boundary edge id** groups triangle segments that share one unordered face\n pair and connect through vertices. One CAD edge that was tessellated collinearly\n is one id (`eN`). A curved rim, where each facet is its own face, stays many ids.\n- Ids are sorted by `(min face, max face, midpoint)` so a fresh cube is stable.\n- `edge(part, id)` and `edgesBetween(part, faceA, faceB)` return\n `{ key, a, b, va, vb, mid, length }` segments for `makeSweepPath`.\n `edgesBetween` throws when that pair has more than one boundary — use `edge`.\n\n**Rematch limits:** ids are not a CAD feature tree. Manifold `faceID` is\nprovenance and can merge or split after a boolean, and two disconnected regions\ncan share one minimum faceID. `edge` / `edgesBetween` throw `re-pick edges`\nwhen the id or pair is missing. Re-running a script from scratch is stable only\nwhile the solid *before* the fillet is deterministic. After geometry changes,\nre-pick in Fillet mode (the labels update) rather than editing a stale id.\n\n**Loud failures (script):** bad/empty path; radius ≤ 0; cannot orient\ncutter; sweep/boolean failure; ~0 volume removed (wrong orientation); near-no-op vs\nexpected wedge volume; empty result. Never silent wrong solid.\n\n**Soft-fail (UI):** empty / disconnected / branched edge selection — same messages\nas Path; no broken JS inserted.",
|
|
1672
1677
|
"examples": [
|
|
1673
1678
|
"let part = Manifold.cube([40, 30, 20], true);\nconst cat = boundaryEdges(part); // [{ id, faceA, faceB, mid, length }, ...]\nconst one = cat[0];\nconst selEdges = edgesBetween(part, one.faceA, one.faceB);\n// partial chain: [id, id].flatMap((id) => edge(part, id))\nconst path = makeSweepPath(selEdges);\npart = filletAlongPath(part, path, 2);\nreturn part;"
|
|
1674
1679
|
]
|
|
@@ -1683,7 +1688,7 @@
|
|
|
1683
1688
|
}
|
|
1684
1689
|
],
|
|
1685
1690
|
"description": "boundaryEdges(part) → catalog { id, faceA, faceB, mid, length } for the current mesh. ",
|
|
1686
|
-
"doc": "Fillet-mode labels and Accept use these instead of tessellation keys like\n`\"1268-1269\"`.\n\n\n\n**How ids are assigned (current mesh only):**\n- A **face id** is the minimum Manifold `faceID` in a coplanar connected group\n (normals within 0.1°, plane offset within 1e-3). Shown as `fN`.\n- A **boundary edge id** groups triangle segments that share one unordered face\n pair and connect through vertices. One CAD edge that was tessellated collinearly\n is one id (`eN`). A curved rim, where each facet is its own face, stays many ids.\n- Ids are sorted by `(min face, max face, midpoint)` so a fresh cube is stable.\n- `edge(part, id)` and `edgesBetween(part, faceA, faceB)` return\n `{ key, a, b, va, vb, mid, length }` segments for `makeSweepPath`.\n `edgesBetween` throws when that pair has more than one boundary — use `edge`.\n\n**Rematch limits:** ids are not a CAD feature tree. Manifold `faceID` is\nprovenance and can merge or split after a boolean, and two disconnected regions\ncan share one minimum faceID. `edge` / `edgesBetween` throw `re-pick edges`\nwhen the id or pair is missing. Re-running a script from scratch is stable only\nwhile the solid *before* the fillet is deterministic. After geometry changes,\nre-pick in Fillet mode (the labels update) rather than editing a stale id.\n\n**Loud failures (script):** bad/empty path; radius ≤ 0;
|
|
1691
|
+
"doc": "Fillet-mode labels and Accept use these instead of tessellation keys like\n`\"1268-1269\"`.\n\n\n\n**How ids are assigned (current mesh only):**\n- A **face id** is the minimum Manifold `faceID` in a coplanar connected group\n (normals within 0.1°, plane offset within 1e-3). Shown as `fN`.\n- A **boundary edge id** groups triangle segments that share one unordered face\n pair and connect through vertices. One CAD edge that was tessellated collinearly\n is one id (`eN`). A curved rim, where each facet is its own face, stays many ids.\n- Ids are sorted by `(min face, max face, midpoint)` so a fresh cube is stable.\n- `edge(part, id)` and `edgesBetween(part, faceA, faceB)` return\n `{ key, a, b, va, vb, mid, length }` segments for `makeSweepPath`.\n `edgesBetween` throws when that pair has more than one boundary — use `edge`.\n\n**Rematch limits:** ids are not a CAD feature tree. Manifold `faceID` is\nprovenance and can merge or split after a boolean, and two disconnected regions\ncan share one minimum faceID. `edge` / `edgesBetween` throw `re-pick edges`\nwhen the id or pair is missing. Re-running a script from scratch is stable only\nwhile the solid *before* the fillet is deterministic. After geometry changes,\nre-pick in Fillet mode (the labels update) rather than editing a stale id.\n\n**Loud failures (script):** bad/empty path; radius ≤ 0; cannot orient\ncutter; sweep/boolean failure; ~0 volume removed (wrong orientation); near-no-op vs\nexpected wedge volume; empty result. Never silent wrong solid.\n\n**Soft-fail (UI):** empty / disconnected / branched edge selection — same messages\nas Path; no broken JS inserted.",
|
|
1687
1692
|
"examples": [
|
|
1688
1693
|
"let part = Manifold.cube([40, 30, 20], true);\nconst cat = boundaryEdges(part); // [{ id, faceA, faceB, mid, length }, ...]\nconst one = cat[0];\nconst selEdges = edgesBetween(part, one.faceA, one.faceB);\n// partial chain: [id, id].flatMap((id) => edge(part, id))\nconst path = makeSweepPath(selEdges);\npart = filletAlongPath(part, path, 2);\nreturn part;"
|
|
1689
1694
|
]
|
|
@@ -1746,6 +1751,25 @@
|
|
|
1746
1751
|
"faceNames(part); // ['base.bottom', 'base.top', 'boss.side', …]\nconst top = facesNamed(part, 'base.top')[0];\nconst wp = workplaneFromFace(part, top);\npart = hole(part, wp, 10, 0, 4, 6);\nfacesNamed(part, 'plate.top'); // every piece: plate.top[0], plate.top[1]\nfacesNamed(part, 'boss.wall[*]'); // glob\nsurfaceOf(top); // { kind: 'plane', origin, normal }\npart = chamferEdges(part, edgesOf(part, 'boss.top'), 2); // the edges around that face only\nconst e = edgesOf(part, 'plate.top'); e.skipped; // concave edges left out, counted"
|
|
1747
1752
|
]
|
|
1748
1753
|
},
|
|
1754
|
+
{
|
|
1755
|
+
"name": "edgesNamed",
|
|
1756
|
+
"signature": "edgesNamed(part, ...names)",
|
|
1757
|
+
"params": [
|
|
1758
|
+
{
|
|
1759
|
+
"name": "part",
|
|
1760
|
+
"text": "part"
|
|
1761
|
+
},
|
|
1762
|
+
{
|
|
1763
|
+
"name": "names",
|
|
1764
|
+
"text": "...names"
|
|
1765
|
+
}
|
|
1766
|
+
],
|
|
1767
|
+
"description": "edgesNamed(part, ...names) → the mesh segments of the edges between two named faces, for makeSweepPath / filletAlongPath. ",
|
|
1768
|
+
"doc": "The one edge reference a script should hold. An edge is the pair of stamped faces it lies between, so the name survives every edit that keeps those faces, where `edge(part, 17)` renumbers after any earlier change and a literal `va/vb` wire breaks as soon as the geometry moves.\n\n\n\n- Face order inside a name does not matter (`a~b` is `b~a`). Names come from `faceNames(part)`, `list_feature_edges`, or the Fillet card.\n- A bare pair returns every chain between those faces. `[k]` picks one chain and throws when the pair no longer has that many chains (the pieces changed): re-pick, or use the bare name. `*` globs either side.\n- Returns the same segment rows `edge()` returns (`a`, `b`, `va`, `vb`, `length`, `mid`, plus `n0` / `n1` and `name`), so `makeSweepPath` and `filletAlongPath` are unchanged. `result.names` lists the chains it matched.\n- Throws, listing the edges that exist, when a name matches nothing. It never substitutes a nearby edge.\n- Every face has a name: helper roles (`cube1.top`), fillet and chamfer surfaces (`fillet1.round`, `chamfer2.bevel`, and the spherical corner balls of `filletEdges(..., { sphericalCorners: true })` as `fillet1.corner[k]`; the block id Accept mints, positional like `fillet-16` only on an older block with no `id=`, one piece per contiguous strip), uploads by coplanar group (`import@1.f3`), and freehand `Manifold.*` runs by their block (`snippet2.f7`, else `script.f7`).\n- `filletAlongPath` also refuses a path whose knots are not on an edge of the solid (a stale literal wire), instead of sweeping a cutter through air.",
|
|
1769
|
+
"examples": [
|
|
1770
|
+
"const e1 = edgesNamed(part, 'plate.top~boss.side'); // every chain between those faces\nconst e2 = edgesNamed(part, 'plate.top~boss.side[1]'); // one chain of a pair that meets twice\nconst e3 = edgesNamed(part, 'cube1.top~cube1.front', 'cube1.top~cube1.right'); // several edges, one list\nconst e4 = edgesNamed(part, 'boss.top~boss.wall[*]'); // glob: the rim of a hex boss\npart = filletAlongPath(part, makeSweepPath(e1), 2);\npart = filletAlongPath(part, makeSweepPath(edgesNamed(part, 'plate.top~fillet-2.round')), 1, { profile: 'chamfer' });"
|
|
1771
|
+
]
|
|
1772
|
+
},
|
|
1749
1773
|
{
|
|
1750
1774
|
"name": "surfaceOf",
|
|
1751
1775
|
"signature": "surfaceOf(face)",
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "surfcad-mcp",
|
|
3
|
-
"version": "0.3.
|
|
4
|
-
"description": "SurfCAD agent bridge MCP server (stdio) — pairs to a browser tab via the local WebSocket relay",
|
|
3
|
+
"version": "0.3.4",
|
|
4
|
+
"description": "SurfCAD agent bridge MCP server (stdio) — pairs to a browser tab via the local WebSocket relay, or a saved remote login",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"author": "artur0x0",
|
|
7
7
|
"homepage": "https://github.com/artur0x0/surfcad/tree/main/packages/surfcad-mcp",
|
|
@@ -32,6 +32,33 @@ export const BRIDGE_NONCE_RE = /^[A-Za-z0-9_-]{22,128}$/;
|
|
|
32
32
|
const LOCAL_HOSTNAMES = new Set(['localhost', '127.0.0.1', '[::1]', '::1']);
|
|
33
33
|
const PROD_SURFCAD_HOSTS = new Set(['surfcad.com', 'www.surfcad.com']);
|
|
34
34
|
|
|
35
|
+
/**
|
|
36
|
+
* Same loopback rule as the relay allowlist, without `node:net`.
|
|
37
|
+
* Four decimal octets only. A hostname is never prefix-matched.
|
|
38
|
+
* @param {string} hostname
|
|
39
|
+
*/
|
|
40
|
+
function isLiteralLoopbackHost(hostname) {
|
|
41
|
+
if (LOCAL_HOSTNAMES.has(hostname)) return true;
|
|
42
|
+
const host = hostname.startsWith('[') && hostname.endsWith(']')
|
|
43
|
+
? hostname.slice(1, -1)
|
|
44
|
+
: hostname;
|
|
45
|
+
if (LOCAL_HOSTNAMES.has(host)) return true;
|
|
46
|
+
const parts = host.split('.');
|
|
47
|
+
if (parts.length === 4 && parts.every((part) => /^(0|[1-9]\d{0,2})$/.test(part) && Number(part) <= 255)) {
|
|
48
|
+
return Number(parts[0]) === 127;
|
|
49
|
+
}
|
|
50
|
+
const lower = host.toLowerCase();
|
|
51
|
+
if (lower === '::1') return true;
|
|
52
|
+
if (lower.startsWith('::ffff:')) {
|
|
53
|
+
const v4 = lower.slice('::ffff:'.length);
|
|
54
|
+
const mapped = v4.split('.');
|
|
55
|
+
return mapped.length === 4
|
|
56
|
+
&& mapped.every((part) => /^(0|[1-9]\d{0,2})$/.test(part) && Number(part) <= 255)
|
|
57
|
+
&& Number(mapped[0]) === 127;
|
|
58
|
+
}
|
|
59
|
+
return false;
|
|
60
|
+
}
|
|
61
|
+
|
|
35
62
|
/**
|
|
36
63
|
* Same rule as the relay's `isAllowedHttpOrigin`, but an opener must always
|
|
37
64
|
* present an origin, and it must be a bare origin (no path, query or `null`).
|
|
@@ -52,7 +79,7 @@ export function isAllowedOpenerOrigin(origin, extraOrigins = []) {
|
|
|
52
79
|
if (extra === origin) return true;
|
|
53
80
|
}
|
|
54
81
|
if (url.protocol !== 'http:' && url.protocol !== 'https:') return false;
|
|
55
|
-
if (
|
|
82
|
+
if (isLiteralLoopbackHost(url.hostname)) return true;
|
|
56
83
|
return PROD_SURFCAD_HOSTS.has(url.hostname);
|
|
57
84
|
}
|
|
58
85
|
|
|
@@ -1,5 +1,10 @@
|
|
|
1
|
+
import { isIP } from 'node:net';
|
|
2
|
+
|
|
1
3
|
/**
|
|
2
4
|
* Localhost binding and browser Origin allowlist for the M1 agent-bridge relay.
|
|
5
|
+
*
|
|
6
|
+
* Hostnames are exact matches only. A string that merely starts with `127.`
|
|
7
|
+
* is not loopback: `127.evil.com` is a DNS name.
|
|
3
8
|
*/
|
|
4
9
|
|
|
5
10
|
const LOCAL_HOSTNAMES = new Set(['localhost', '127.0.0.1', '[::1]', '::1']);
|
|
@@ -7,15 +12,46 @@ const LOCAL_HOSTNAMES = new Set(['localhost', '127.0.0.1', '[::1]', '::1']);
|
|
|
7
12
|
const PROD_SURFCAD_HOSTS = new Set(['surfcad.com', 'www.surfcad.com']);
|
|
8
13
|
|
|
9
14
|
/**
|
|
10
|
-
*
|
|
15
|
+
* Drop one pair of URL brackets so `net.isIP` can see the address.
|
|
16
|
+
* @param {string} host
|
|
17
|
+
*/
|
|
18
|
+
function unbracket(host) {
|
|
19
|
+
if (host.startsWith('[') && host.endsWith(']') && host.indexOf(']') === host.length - 1) {
|
|
20
|
+
return host.slice(1, -1);
|
|
21
|
+
}
|
|
22
|
+
return host;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* A literal IP in 127.0.0.0/8, `::1`, or an IPv4-mapped form of those.
|
|
27
|
+
* `net.isIP` has already accepted `host`. Never call this with a hostname.
|
|
28
|
+
* @param {string} host
|
|
11
29
|
*/
|
|
30
|
+
function isLiteralLoopbackIp(host) {
|
|
31
|
+
const kind = isIP(host);
|
|
32
|
+
if (kind === 4) {
|
|
33
|
+
const dot = host.indexOf('.');
|
|
34
|
+
return dot > 0 && Number(host.slice(0, dot)) === 127;
|
|
35
|
+
}
|
|
36
|
+
if (kind === 6) {
|
|
37
|
+
const lower = host.toLowerCase();
|
|
38
|
+
if (lower === '::1') return true;
|
|
39
|
+
if (lower.startsWith('::ffff:')) {
|
|
40
|
+
const v4 = lower.slice('::ffff:'.length);
|
|
41
|
+
return isIP(v4) === 4 && isLiteralLoopbackIp(v4);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return false;
|
|
45
|
+
}
|
|
46
|
+
|
|
12
47
|
export function isLoopbackAddress(address) {
|
|
13
48
|
if (!address || typeof address !== 'string') return false;
|
|
14
49
|
const trimmed = address.trim();
|
|
15
50
|
if (LOCAL_HOSTNAMES.has(trimmed)) return true;
|
|
16
|
-
|
|
17
|
-
if (trimmed
|
|
18
|
-
return false;
|
|
51
|
+
const host = unbracket(trimmed);
|
|
52
|
+
if (host !== trimmed && LOCAL_HOSTNAMES.has(host)) return true;
|
|
53
|
+
if (!isIP(host)) return false;
|
|
54
|
+
return isLiteralLoopbackIp(host);
|
|
19
55
|
}
|
|
20
56
|
|
|
21
57
|
/**
|
|
@@ -44,7 +80,9 @@ export function isAllowedHttpOrigin(origin) {
|
|
|
44
80
|
try {
|
|
45
81
|
const url = new URL(origin);
|
|
46
82
|
if (url.protocol !== 'http:' && url.protocol !== 'https:') return false;
|
|
47
|
-
if (LOCAL_HOSTNAMES.has(url.hostname)
|
|
83
|
+
if (LOCAL_HOSTNAMES.has(url.hostname)) return true;
|
|
84
|
+
const literal = unbracket(url.hostname);
|
|
85
|
+
if (isIP(literal) && isLoopbackAddress(literal)) return true;
|
|
48
86
|
if (PROD_SURFCAD_HOSTS.has(url.hostname)) return true;
|
|
49
87
|
return false;
|
|
50
88
|
} catch {
|
package/src/bridge/relayHub.mjs
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
* Canonical implementation shared by surfcad-mcp and the SurfCAD dev server.
|
|
4
4
|
*/
|
|
5
5
|
|
|
6
|
+
import { AGENT_PROTOCOL_VERSION, commandRequest, commandResponse, readCommandResponse } from '../commandProtocol.mjs';
|
|
6
7
|
import { PAIR_MSG } from '../relayMessages.mjs';
|
|
7
8
|
import { isAllowedHttpOrigin, isLoopbackAddress } from './localAddress.mjs';
|
|
8
9
|
|
|
@@ -426,15 +427,27 @@ export function createAgentBridgeRelayHub(opts = {}) {
|
|
|
426
427
|
refuse(socket, 'not_paired', 'Pair before sending bridge commands');
|
|
427
428
|
return;
|
|
428
429
|
}
|
|
430
|
+
if (msg.v != null && msg.v !== AGENT_PROTOCOL_VERSION) {
|
|
431
|
+
sendJson(socket, commandResponse({
|
|
432
|
+
id: msg.id,
|
|
433
|
+
ok: false,
|
|
434
|
+
error: { code: 'bad_call', message: `Unsupported protocol version: ${msg.v}` },
|
|
435
|
+
}));
|
|
436
|
+
return;
|
|
437
|
+
}
|
|
429
438
|
if (typeof msg.id !== 'string' && typeof msg.id !== 'number') {
|
|
430
|
-
sendJson(socket, {
|
|
439
|
+
sendJson(socket, commandResponse({
|
|
440
|
+
id: msg.id,
|
|
441
|
+
ok: false,
|
|
442
|
+
error: { code: 'bad_call', message: 'call requires id' },
|
|
443
|
+
}));
|
|
431
444
|
return;
|
|
432
445
|
}
|
|
433
|
-
sendJson(tab.socket, {
|
|
446
|
+
sendJson(tab.socket, commandRequest({
|
|
434
447
|
id: msg.id,
|
|
435
448
|
command: msg.command,
|
|
436
449
|
args: msg.args == null ? {} : msg.args,
|
|
437
|
-
});
|
|
450
|
+
}));
|
|
438
451
|
return;
|
|
439
452
|
}
|
|
440
453
|
|
|
@@ -443,12 +456,21 @@ export function createAgentBridgeRelayHub(opts = {}) {
|
|
|
443
456
|
refuse(socket, 'not_paired', 'No paired peer for response');
|
|
444
457
|
return;
|
|
445
458
|
}
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
459
|
+
if (msg.v != null && msg.v !== AGENT_PROTOCOL_VERSION) {
|
|
460
|
+
sendJson(tab.pairedPeer, commandResponse({
|
|
461
|
+
id: msg.id,
|
|
462
|
+
ok: false,
|
|
463
|
+
error: { code: 'bad_call', message: `Unsupported protocol version: ${msg.v}` },
|
|
464
|
+
}));
|
|
465
|
+
return;
|
|
466
|
+
}
|
|
467
|
+
const response = readCommandResponse(msg);
|
|
468
|
+
sendJson(tab.pairedPeer, commandResponse({
|
|
469
|
+
id: response?.id ?? msg.id,
|
|
470
|
+
ok: response?.ok === true,
|
|
471
|
+
result: response?.ok === true ? response.result : undefined,
|
|
472
|
+
error: response?.ok === true ? undefined : response?.error,
|
|
473
|
+
}));
|
|
452
474
|
return;
|
|
453
475
|
}
|
|
454
476
|
|
package/src/cli.mjs
ADDED
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `surfcad-mcp` argv. login / logout / status exit. Anything else starts
|
|
3
|
+
* the stdio server. The token is never written to stdout or stderr.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { hostname } from 'node:os';
|
|
7
|
+
import { resolveAgentName, resolveServerUrl, selectRelayMode } from './remote/config.mjs';
|
|
8
|
+
import { loginDevice, loginWithCode } from './remote/login.mjs';
|
|
9
|
+
import { logoutDevice } from './remote/logout.mjs';
|
|
10
|
+
import { formatLoginStatus, readSavedLogin } from './remote/tokenStore.mjs';
|
|
11
|
+
|
|
12
|
+
const HELP = `surfcad-mcp
|
|
13
|
+
|
|
14
|
+
npx surfcad-mcp
|
|
15
|
+
MCP server on stdio. The local relay is the default.
|
|
16
|
+
npx surfcad-mcp login [--name NAME] [--server URL]
|
|
17
|
+
Device-code login at the SurfCAD agent server. Prints the code and
|
|
18
|
+
the approval URL. The token is saved on this machine and is not printed.
|
|
19
|
+
npx surfcad-mcp login --code CODE [--name NAME] [--server URL]
|
|
20
|
+
Redeem a join code shown by SurfCAD on Safari, iOS, or a phone.
|
|
21
|
+
The token is saved on this machine and is not printed.
|
|
22
|
+
npx surfcad-mcp logout
|
|
23
|
+
Revokes this machine's token on the server, then deletes the saved
|
|
24
|
+
file. If the server cannot be reached, the file is still deleted.
|
|
25
|
+
npx surfcad-mcp status
|
|
26
|
+
|
|
27
|
+
--remote Use the server relay. Requires a saved login.
|
|
28
|
+
--local Use the local relay even when a login is saved.
|
|
29
|
+
--server URL Dev or staging origin (or set SURFCAD_AGENT_SERVER).
|
|
30
|
+
Cleartext http is only allowed for localhost, 127.0.0.1, and ::1.
|
|
31
|
+
--code CODE Join code from the SurfCAD Connect Agent screen (ABCD-EFGH).
|
|
32
|
+
--name NAME Agent name for the approval page. Otherwise the MCP client
|
|
33
|
+
name is used when the server starts, or SURFCAD_AGENT_NAME.
|
|
34
|
+
|
|
35
|
+
A saved login selects the server relay. These keep the local relay:
|
|
36
|
+
--local, SURFCAD_MCP_TRANSPORT=local, SURFCAD_AGENT_BRIDGE_WS_URL,
|
|
37
|
+
SURFCAD_AGENT_BRIDGE_WS_PORT, or a non-empty SURFCAD_PAIRING_CODE.
|
|
38
|
+
--remote and SURFCAD_MCP_TRANSPORT=remote win over those.
|
|
39
|
+
`;
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* @param {string[]} argv
|
|
43
|
+
*/
|
|
44
|
+
export function parseArgs(argv) {
|
|
45
|
+
/** @type {'serve' | 'login' | 'logout' | 'status' | 'help'} */
|
|
46
|
+
let command = 'serve';
|
|
47
|
+
let name = '';
|
|
48
|
+
let server = '';
|
|
49
|
+
let code = '';
|
|
50
|
+
let remote = false;
|
|
51
|
+
let local = false;
|
|
52
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
53
|
+
const arg = argv[i];
|
|
54
|
+
if (arg === 'login' || arg === 'logout' || arg === 'status') {
|
|
55
|
+
if (command !== 'serve') {
|
|
56
|
+
throw Object.assign(new Error('Pass one command: login, logout, or status.'), { code: 'bad_args' });
|
|
57
|
+
}
|
|
58
|
+
command = arg;
|
|
59
|
+
continue;
|
|
60
|
+
}
|
|
61
|
+
if (arg === '--help' || arg === '-h' || arg === 'help') {
|
|
62
|
+
command = 'help';
|
|
63
|
+
continue;
|
|
64
|
+
}
|
|
65
|
+
if (arg === '--remote') {
|
|
66
|
+
remote = true;
|
|
67
|
+
continue;
|
|
68
|
+
}
|
|
69
|
+
if (arg === '--local') {
|
|
70
|
+
local = true;
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
73
|
+
if (arg === '--name' || arg.startsWith('--name=')) {
|
|
74
|
+
const value = arg === '--name' ? argv[++i] : arg.slice('--name='.length);
|
|
75
|
+
if (!value || value.startsWith('--')) {
|
|
76
|
+
throw Object.assign(new Error('--name needs a value.'), { code: 'bad_args' });
|
|
77
|
+
}
|
|
78
|
+
name = value;
|
|
79
|
+
continue;
|
|
80
|
+
}
|
|
81
|
+
if (arg === '--code' || arg.startsWith('--code=')) {
|
|
82
|
+
const value = arg === '--code' ? argv[++i] : arg.slice('--code='.length);
|
|
83
|
+
if (!value || value.startsWith('--')) {
|
|
84
|
+
throw Object.assign(new Error('--code needs a value.'), { code: 'bad_args' });
|
|
85
|
+
}
|
|
86
|
+
code = value;
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
if (arg === '--server' || arg.startsWith('--server=')) {
|
|
90
|
+
const value = arg === '--server' ? argv[++i] : arg.slice('--server='.length);
|
|
91
|
+
if (!value || value.startsWith('--')) {
|
|
92
|
+
throw Object.assign(new Error('--server needs a value.'), { code: 'bad_args' });
|
|
93
|
+
}
|
|
94
|
+
server = value;
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
throw Object.assign(new Error(`Unknown argument: ${arg}`), { code: 'bad_args' });
|
|
98
|
+
}
|
|
99
|
+
return { command, name, server, code, remote, local };
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* @param {NodeJS.ProcessEnv} env
|
|
104
|
+
* @param {{ remote: boolean, local: boolean }} flags
|
|
105
|
+
*/
|
|
106
|
+
function flagsFromEnv(env, flags) {
|
|
107
|
+
let { remote, local } = flags;
|
|
108
|
+
if (!remote && !local) {
|
|
109
|
+
const transport = typeof env.SURFCAD_MCP_TRANSPORT === 'string'
|
|
110
|
+
? env.SURFCAD_MCP_TRANSPORT.trim().toLowerCase()
|
|
111
|
+
: '';
|
|
112
|
+
if (transport === 'remote') remote = true;
|
|
113
|
+
else if (transport === 'local') local = true;
|
|
114
|
+
}
|
|
115
|
+
return { remote, local };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* @param {string[]} argv
|
|
120
|
+
* @param {{
|
|
121
|
+
* env?: NodeJS.ProcessEnv,
|
|
122
|
+
* fetch?: typeof fetch,
|
|
123
|
+
* io?: { stdout: (text: string) => void, stderr: (text: string) => void },
|
|
124
|
+
* machine?: string,
|
|
125
|
+
* }} [options]
|
|
126
|
+
* @returns {Promise<{ action: 'exit', code: number } | { action: 'serve', mode: 'local' | 'remote', server: string, name: string }>}
|
|
127
|
+
*/
|
|
128
|
+
export async function runCli(argv, options = {}) {
|
|
129
|
+
const env = options.env || process.env;
|
|
130
|
+
const io = options.io || {
|
|
131
|
+
stdout: (text) => { process.stdout.write(text); },
|
|
132
|
+
stderr: (text) => { process.stderr.write(text); },
|
|
133
|
+
};
|
|
134
|
+
/** @type {ReturnType<typeof parseArgs>} */
|
|
135
|
+
let parsed;
|
|
136
|
+
try {
|
|
137
|
+
parsed = parseArgs(argv);
|
|
138
|
+
} catch (err) {
|
|
139
|
+
io.stderr(`${err?.message || 'Bad arguments'}\n${HELP}`);
|
|
140
|
+
return { action: 'exit', code: 1 };
|
|
141
|
+
}
|
|
142
|
+
if (parsed.command === 'help') {
|
|
143
|
+
io.stdout(HELP);
|
|
144
|
+
return { action: 'exit', code: 0 };
|
|
145
|
+
}
|
|
146
|
+
if (parsed.command === 'login' || parsed.command === 'logout' || parsed.command === 'status') {
|
|
147
|
+
if (parsed.remote || parsed.local) {
|
|
148
|
+
io.stderr(`login, logout, and status do not take --remote or --local.\n${HELP}`);
|
|
149
|
+
return { action: 'exit', code: 1 };
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
try {
|
|
153
|
+
if (parsed.command === 'login') {
|
|
154
|
+
const serverUrl = resolveServerUrl({ flag: parsed.server, env });
|
|
155
|
+
const name = resolveAgentName({ name: parsed.name, env });
|
|
156
|
+
if (parsed.code) {
|
|
157
|
+
await loginWithCode({
|
|
158
|
+
serverUrl,
|
|
159
|
+
code: parsed.code,
|
|
160
|
+
name,
|
|
161
|
+
machine: options.machine || hostname(),
|
|
162
|
+
env,
|
|
163
|
+
fetch: options.fetch,
|
|
164
|
+
});
|
|
165
|
+
io.stdout('Logged in. The token is saved on this machine and is not printed.\n');
|
|
166
|
+
return { action: 'exit', code: 0 };
|
|
167
|
+
}
|
|
168
|
+
await loginDevice({
|
|
169
|
+
serverUrl,
|
|
170
|
+
name,
|
|
171
|
+
machine: options.machine || hostname(),
|
|
172
|
+
env,
|
|
173
|
+
fetch: options.fetch,
|
|
174
|
+
onCode: ({ userCode, approvalUrl }) => {
|
|
175
|
+
io.stdout(`Code: ${userCode}\nApprove at: ${approvalUrl}\nWaiting for approval…\n`);
|
|
176
|
+
},
|
|
177
|
+
});
|
|
178
|
+
io.stdout('Logged in. The token is saved on this machine and is not printed.\n');
|
|
179
|
+
return { action: 'exit', code: 0 };
|
|
180
|
+
}
|
|
181
|
+
if (parsed.command === 'logout') {
|
|
182
|
+
const result = await logoutDevice({ env, fetch: options.fetch });
|
|
183
|
+
if (result.hadLogin && !result.confirmed) {
|
|
184
|
+
io.stdout('Logged out on this machine. SurfCAD did not confirm the revoke, so that login may stay valid until it expires.\n');
|
|
185
|
+
} else {
|
|
186
|
+
io.stdout('Logged out.\n');
|
|
187
|
+
}
|
|
188
|
+
return { action: 'exit', code: 0 };
|
|
189
|
+
}
|
|
190
|
+
if (parsed.command === 'status') {
|
|
191
|
+
const saved = await readSavedLogin(env);
|
|
192
|
+
const serverUrl = resolveServerUrl({ flag: parsed.server, env, saved });
|
|
193
|
+
io.stdout(formatLoginStatus(saved, serverUrl));
|
|
194
|
+
return { action: 'exit', code: 0 };
|
|
195
|
+
}
|
|
196
|
+
} catch (err) {
|
|
197
|
+
const usage = err?.code === 'bad_args' || err?.code === 'bad_server' ? HELP : '';
|
|
198
|
+
io.stderr(`${err?.message || 'Login failed'}\n${usage}`);
|
|
199
|
+
return { action: 'exit', code: 1 };
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
const flags = flagsFromEnv(env, parsed);
|
|
203
|
+
let saved = null;
|
|
204
|
+
try {
|
|
205
|
+
saved = await readSavedLogin(env);
|
|
206
|
+
} catch (err) {
|
|
207
|
+
io.stderr(`${err?.message || 'Saved login could not be read.'}\n`);
|
|
208
|
+
return { action: 'exit', code: 1 };
|
|
209
|
+
}
|
|
210
|
+
const selected = selectRelayMode({
|
|
211
|
+
remote: flags.remote,
|
|
212
|
+
local: flags.local,
|
|
213
|
+
loggedIn: Boolean(saved?.token),
|
|
214
|
+
env,
|
|
215
|
+
});
|
|
216
|
+
if (!selected.ok) {
|
|
217
|
+
io.stderr(`${selected.error}\n`);
|
|
218
|
+
return { action: 'exit', code: 1 };
|
|
219
|
+
}
|
|
220
|
+
if (selected.mode === 'remote' && !saved?.token) {
|
|
221
|
+
io.stderr('No saved login. Run npx surfcad-mcp login.\n');
|
|
222
|
+
return { action: 'exit', code: 1 };
|
|
223
|
+
}
|
|
224
|
+
return {
|
|
225
|
+
action: 'serve',
|
|
226
|
+
mode: selected.mode,
|
|
227
|
+
server: parsed.server,
|
|
228
|
+
name: parsed.name,
|
|
229
|
+
};
|
|
230
|
+
}
|