From d9efbe5bb27f000da109448a1ac309d5bbf48ab4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Asbj=C3=B8rn=20R=C3=B8rvik?= <11362831+asbis@users.noreply.github.com> Date: Tue, 13 Oct 2026 21:05:57 +0200 Subject: [PATCH] fix(mcp-server): stop validate_syntax flagging built-in and finder methods validate_syntax warned "unknown method(s)" on code that renders fine, because it only knew a hand-curated list of Replicad methods: - Calls on ECMAScript built-ins (`Math.cos`, `Number.isFinite`) are now resolved against the real built-in, so `Math.cso(` is still flagged. - EdgeFinder/FaceFinder/CornerFinder filters (`e.inDirection("Y")` in a fillet callback) join the list. A test reads the bundled replicad typings and fails if a new filter is missing. - Array, String and Number instance methods (`pts.map`, `parts.push`, `n.toFixed`, `Object.keys(o).map`) are accepted when the prototype has them as functions, so the check can't drift. Typos like `.extrdue(`, `Math.cso(` and `pts.pussh(` are still reported. The cost: a Replicad typo that is also an array or string method goes unflagged. Of the 92 built-in names, the realistic one is `.filter(` or `.fill(` for `.fillet(`, and that still fails at runtime with "not a function". Extension, mcp-server and plugin manifest move to 1.30.1. Co-Authored-By: Claude Opus 5.5 --- .claude-plugin/marketplace.json | 2 +- packages/extension/package.json | 2 +- packages/mcp-server/package.json | 2 +- packages/mcp-server/src/tools.test.ts | 153 ++++++++++++++++++++++++++ packages/mcp-server/src/tools.ts | 51 ++++++++- 5 files changed, 203 insertions(+), 7 deletions(-) diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index b7ede95..4a81869 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -12,7 +12,7 @@ { "name": "shapeitup", "description": "CAD scripting toolkit: create/modify .shape.ts files, validate geometry, check collisions, export STEP/STL/3MF via Replicad + OpenCascade. Runs headless; live 3D preview available if the ShapeItUp VS Code extension is installed.", - "version": "1.30.0", + "version": "1.30.1", "author": { "name": "Asbjorn Rorvik", "email": "rorvik.asbjorn@gmail.com" diff --git a/packages/extension/package.json b/packages/extension/package.json index e461817..120dc23 100644 --- a/packages/extension/package.json +++ b/packages/extension/package.json @@ -2,7 +2,7 @@ "name": "shapeitup-vscode", "displayName": "ShapeItUp", "description": "Scripted CAD for VS Code — write TypeScript, see 3D, export STEP/STL/3MF (Bambu Studio & OrcaSlicer ready). AI-powered with Claude Code MCP integration.", - "version": "1.30.0", + "version": "1.30.1", "publisher": "shapeitup", "license": "MIT", "icon": "icon.png", diff --git a/packages/mcp-server/package.json b/packages/mcp-server/package.json index 99caf9f..6c32f85 100644 --- a/packages/mcp-server/package.json +++ b/packages/mcp-server/package.json @@ -1,6 +1,6 @@ { "name": "@shapeitup/mcp-server", - "version": "1.30.0", + "version": "1.30.1", "description": "ShapeItUp MCP server — scripted CAD tools (Replicad/OpenCascade) for Claude Code, Cursor, Claude Desktop, and other MCP clients.", "type": "module", "bin": { diff --git a/packages/mcp-server/src/tools.test.ts b/packages/mcp-server/src/tools.test.ts index d9e1149..f2d4c15 100644 --- a/packages/mcp-server/src/tools.test.ts +++ b/packages/mcp-server/src/tools.test.ts @@ -1,6 +1,8 @@ import { describe, it, expect } from "vitest"; import { validateSyntaxPure, detectPathDoubling, detectPathDoublingInfo, extractSignatures, safeHandler, computePartsLine, computeEffectiveMeshQuality, formatCollisionPairs, formatSweepCollisions, formatLastScreenshotLine, registerTools, getVersionTag, getViewerStatus, formatViewerBlock, partExtendsBelowBed, formatStatusText, workspaceMismatchWarning, type CollisionEntry, type SweepCollisionEntry } from "./tools.js"; import type { EngineStatus } from "./engine.js"; +import { readFileSync } from "node:fs"; +import { fileURLToPath } from "node:url"; // --------------------------------------------------------------------------- // Bug #6 — validate_syntax must trust .method() calls whose receiver was @@ -98,6 +100,157 @@ describe("validateSyntaxPure — stdlib whitelisting", () => { }); }); +// --------------------------------------------------------------------------- +// validate_syntax reported "unknown method(s)" for valid code that renders +// fine: built-in globals (`Math.cos`) and finder callbacks +// (`(e) => e.inDirection("Y")`). Real typos must still be flagged. +// --------------------------------------------------------------------------- + +describe("validateSyntaxPure — built-in globals and finder methods", () => { + it("does not warn on Math.cos / Math.sin", () => { + const code = [ + `import { makeCylinder } from "replicad";`, + `export default function main() {`, + ` const angle = Math.PI / 6;`, + ` const x = 20 * Math.cos(angle);`, + ` const y = 20 * Math.sin(angle);`, + ` return makeCylinder(5, 10).translate([x, y, 0]);`, + `}`, + ].join("\n"); + const { text, isError } = validateSyntaxPure(code); + expect(isError).toBe(false); + expect(text).not.toMatch(/unknown method/i); + }); + + it("does not warn on an EdgeFinder callback (fillet + inDirection)", () => { + const code = [ + `import { makeBox } from "replicad";`, + `export default function main() {`, + ` const shape = makeBox([0, 0, 0], [40, 30, 20]);`, + ` return shape.fillet(2, (e) => e.inDirection("Y"));`, + `}`, + ].join("\n"); + const { text, isError } = validateSyntaxPure(code); + expect(isError).toBe(false); + expect(text).not.toMatch(/unknown method/i); + }); + + it("does not warn on a FaceFinder callback (shell + inPlane)", () => { + const code = [ + `import { makeBox } from "replicad";`, + `export default function main() {`, + ` const shape = makeBox([0, 0, 0], [40, 30, 60]);`, + ` return shape.shell(2, (f) => f.inPlane("XY", 60));`, + `}`, + ].join("\n"); + const { text, isError } = validateSyntaxPure(code); + expect(isError).toBe(false); + expect(text).not.toMatch(/unknown method/i); + }); + + it("accepts every public Finder method declared in the bundled replicad typings", () => { + // Drift guard: if replicad adds a filter, this fails until the + // whitelist in validateSyntaxPure learns it. + const dts = readFileSync( + fileURLToPath(new URL("../../extension/typings/replicad/index.d.ts", import.meta.url)), + "utf-8", + ); + const methods = new Set(); + const classPattern = /declare (?:abstract )?class (?:Finder|Finder3d|EdgeFinder|FaceFinder|CornerFinder)\b[^{]*\{([\s\S]*?)\n\}/g; + for (const [, body] of dts.matchAll(classPattern)) { + for (const [, name] of body.matchAll(/^ {4}(?:abstract )?(\w+)(?:<[^>]*>)?\(/gm)) { + if (name !== "constructor") methods.add(name); + } + } + expect(methods).toContain("inDirection"); + expect(methods).toContain("ofSurfaceType"); + expect(methods).toContain("containsPoint"); + const code = [ + `export default function main(shape) {`, + ...[...methods].map((m) => ` shape.fillet(1, (f) => f.${m}());`), + `}`, + ].join("\n"); + expect(validateSyntaxPure(code).text).not.toMatch(/unknown method/i); + }); + + it("still flags typos on Replicad shapes and on built-ins", () => { + const code = [ + `import { drawRectangle } from "replicad";`, + `export default function main() {`, + ` const r = 10 * Math.cso(0.5);`, + ` return drawRectangle(r, 20).sketchOnPlane("XY").extrdue(5);`, + `}`, + ].join("\n"); + const { text, isError } = validateSyntaxPure(code); + expect(isError).toBe(false); + expect(text).toMatch(/unknown method/i); + expect(text).toContain(".extrdue()"); + expect(text).toContain(".cso()"); + expect(text).not.toContain(".sketchOnPlane()"); + }); +}); + +// --------------------------------------------------------------------------- +// Ordinary array/string/number instance methods (`pts.map`, `parts.push`, +// `n.toFixed`) were reported as "unknown method(s)". Typos — on Replicad +// shapes, on built-ins, and on arrays themselves — must still be flagged. +// --------------------------------------------------------------------------- + +describe("validateSyntaxPure — array, string and number instance methods", () => { + it("does not warn on map / push / forEach / Object.keys(o).map / toFixed", () => { + const code = [ + `import { makeCylinder } from "replicad";`, + `export default function main() {`, + ` const o = { a: 1, b: 2 };`, + ` const n = 12.345;`, + ` const holes = [[0, 0], [10, 0]];`, + ` const pts = holes.map((p) => [p[0] * 2, p[1]]);`, + ` const parts = [];`, + ` holes.forEach((h, i) => parts.push({ shape: makeCylinder(2, 5).translate([h[0], h[1], 0]), name: "h" + i }));`, + ` const label = Object.keys(o).map((k) => k.toUpperCase()).join("-") + n.toFixed(2);`, + ` return parts;`, + `}`, + ].join("\n"); + const { text, isError } = validateSyntaxPure(code); + expect(isError).toBe(false); + expect(text).not.toMatch(/unknown method/i); + }); + + it("does not warn on chained array and string methods after a call", () => { + const code = [ + `export default function main({ count }) {`, + ` const names = Array.from({ length: count }, (_, i) => i)`, + ` .filter((i) => i % 2 === 0)`, + ` .map((i) => String(i).padStart(3, "0"))`, + ` .reduce((acc, s) => acc.concat(s.split("")), []);`, + ` return names.slice(0, 2).includes("0");`, + `}`, + ].join("\n"); + const { text, isError } = validateSyntaxPure(code); + expect(isError).toBe(false); + expect(text).not.toMatch(/unknown method/i); + }); + + it("still flags Replicad, built-in and array-method typos next to them", () => { + const code = [ + `import { drawRectangle } from "replicad";`, + `export default function main() {`, + ` const sizes = [10, 20];`, + ` const scaled = sizes.map((s) => s * Math.cso(0.5));`, + ` scaled.pussh(5);`, + ` return drawRectangle(scaled[0], 20).sketchOnPlane("XY").extrdue(5);`, + `}`, + ].join("\n"); + const { text, isError } = validateSyntaxPure(code); + expect(isError).toBe(false); + expect(text).toMatch(/unknown method/i); + expect(text).toContain(".extrdue()"); + expect(text).toContain(".cso()"); + expect(text).toContain(".pussh()"); + expect(text).not.toContain(".map()"); + }); +}); + // --------------------------------------------------------------------------- // Pitfall detector — hand-rolled boolean loops // Covers all four new patterns plus regression-guards for the existing diff --git a/packages/mcp-server/src/tools.ts b/packages/mcp-server/src/tools.ts index fc4873a..9626b25 100644 --- a/packages/mcp-server/src/tools.ts +++ b/packages/mcp-server/src/tools.ts @@ -1780,7 +1780,10 @@ export function computeEffectiveMeshQuality( * 2. Unknown `.method()` calls — compared against a hand-curated Replicad * whitelist. Method calls whose receiver was imported from "shapeitup" * are trusted unconditionally (so stdlib additions don't need to be - * mirrored here). Warnings only; isError stays false. + * mirrored here); calls on ECMAScript built-ins (`Math.cos`) are + * checked against the built-in itself, and Array/String/Number instance + * methods (`pts.map`) are accepted by name. Warnings only; isError stays + * false. * 3. Seven well-known CAD pitfalls (sketch mischain, missing sketchOnPlane, * unclosed pen, non-uniform scale, oversized fillet, booleans in loop, * and the AST-based variable-assigned `extrude` variant). Warnings only. @@ -1810,8 +1813,43 @@ export function validateSyntaxPure(code: string): { text: string; isError: boole "close", "hLine", "vLine", "lineTo", "line", "sagittaArcTo", "tangentArcTo", "threePointsArcTo", "cubicBezierCurveTo", "smoothSplineTo", "closeWithMirror", "done", "localGC", "exportSTEP", + // EdgeFinder / FaceFinder / CornerFinder filters, plus the Finder and + // Finder3d bases they inherit from (packages/extension/typings/replicad). + // These mostly show up inside finder callbacks — `.fillet(2, (e) => + // e.inDirection("Y"))` — where the receiver is just the callback param. + "inDirection", "ofLength", "ofCurveType", "parallelTo", "inPlane", "ofSurfaceType", + "when", "inList", "atAngleWith", "atDistance", "containsPoint", "withinDistance", + "inBox", "inShape", "atPoint", "ofAngle", + "and", "not", "either", "find", "clone", "delete", "shouldKeep", ]); + // ECMAScript built-ins callable as `Global.method(` — Math.cos, + // Number.isFinite, JSON.stringify. Calls rooted here are resolved against + // the real built-in instead of the Replicad whitelist, so `Math.cso(` is + // still flagged. Deliberately not `globalThis` wholesale: Node globals + // like `process` don't exist in the worker the script runs in. + const builtinGlobals = new Set([ + "Math", "Number", "Object", "Array", "JSON", "String", "Boolean", "Date", + "Symbol", "BigInt", "Reflect", "Promise", "Map", "Set", "Intl", "console", + ]); + const isBuiltinMethod = (segments: string[], methodName: string): boolean => { + let target: any = (globalThis as any)[segments[0]]; + for (const seg of segments.slice(1)) target = target?.[seg]; + return target != null && typeof target[methodName] === "function"; + }; + + // Instance methods of arrays, strings and numbers — `pts.map(`, + // `parts.push(`, `n.toFixed(`, and `Object.keys(o).map(` via the chain + // pass. The receiver is usually a local, so there is no type to resolve + // against; accept the name if one of these prototypes has it. Cost: a + // Replicad typo that IS such a name goes unflagged — realistically only + // `.filter(`/`.fill(` for `.fillet(`, which still fails at runtime with + // "not a function". + const builtinPrototypes: any[] = [Array.prototype, String.prototype, Number.prototype]; + const isKnownMethod = (methodName: string): boolean => + knownMethods.has(methodName) || + builtinPrototypes.some((proto) => typeof proto[methodName] === "function"); + // Bug #6: trust .method() calls whose receiver was imported from the // shapeitup stdlib. Otherwise every stdlib helper (bearings.body, // holes.through, patterns.grid, etc.) shows up as "unknown method" — @@ -1858,7 +1896,8 @@ export function validateSyntaxPure(code: string): { text: string; isError: boole let match: RegExpExecArray | null; while ((match = receiverCallPattern.exec(code)) !== null) { const [, receiverChain, methodName] = match; - const rootIdent = receiverChain.split(/\s*\.\s*/)[0]; + const segments = receiverChain.split(/\s*\.\s*/); + const rootIdent = segments[0]; if (stdlibIdents.has(rootIdent)) { // Remember that this method name was seen on a stdlib receiver // somewhere — even if the SAME name later appears as a chain @@ -1868,7 +1907,11 @@ export function validateSyntaxPure(code: string): { text: string; isError: boole skippedByReceiver.add(methodName); continue; } - if (!knownMethods.has(methodName)) unknownMethods.add(methodName); + if (builtinGlobals.has(rootIdent)) { + if (!isBuiltinMethod(segments, methodName)) unknownMethods.add(methodName); + continue; + } + if (!isKnownMethod(methodName)) unknownMethods.add(methodName); } // Chain-continuation pass: picks up `foo().bar()` — where `bar`'s // receiver is a call expression, not a plain identifier, so the @@ -1879,7 +1922,7 @@ export function validateSyntaxPure(code: string): { text: string; isError: boole while ((match = chainCallPattern.exec(code)) !== null) { const methodName = match[1]; if (skippedByReceiver.has(methodName)) continue; - if (!knownMethods.has(methodName)) unknownMethods.add(methodName); + if (!isKnownMethod(methodName)) unknownMethods.add(methodName); } // --- Semantic checks (pitfall linter) -----------------------------