diff --git a/python/kicad_interface.py b/python/kicad_interface.py index 9fd4f24..e1ef9be 100644 --- a/python/kicad_interface.py +++ b/python/kicad_interface.py @@ -598,6 +598,7 @@ class KiCADInterface: "export_pcb_svg": self._handle_export_pcb_svg, "export_pcb_dxf": self._handle_export_pcb_dxf, "export_gerber_single": self._handle_export_gerber_single, + "export_3d_cli": self._handle_export_3d_cli, "generate_netlist": self._handle_generate_netlist, "sync_schematic_to_board": self._handle_sync_schematic_to_board, "list_schematic_libraries": self._handle_list_schematic_libraries, @@ -5456,6 +5457,132 @@ class KiCADInterface: logger.error(f"Error exporting single Gerber: {e}") return {"success": False, "message": str(e)} + def _handle_export_3d_cli(self, params: Dict[str, Any]) -> Dict[str, Any]: + """Export a 3D model of the PCB via kicad-cli (`pcb export `). + + Rich CLI sibling of export_3d / export_vrml. The ``format`` param selects + the subcommand (step, glb, stl, ply, brep, xao, vrml) and only flags valid + for that subcommand are forwarded. STEP/glb/stl/ply/brep/xao share the + geometry/include flag set; vrml uses units + models-dir instead. Reads the + saved .kicad_pcb. + """ + import subprocess + + logger.info("Exporting 3D model via kicad-cli") + try: + board_path = params.get("boardPath") or self._current_board_path() + output_path = params.get("outputPath") + fmt = params.get("format") + + if not board_path: + return { + "success": False, + "message": "boardPath is required (no current board could be resolved)", + } + if not os.path.exists(board_path): + return {"success": False, "message": f"Board not found: {board_path}"} + if not output_path: + return {"success": False, "message": "outputPath is required"} + valid_formats = ("step", "glb", "stl", "ply", "brep", "xao", "vrml") + if fmt not in valid_formats: + return { + "success": False, + "message": f"format must be one of {valid_formats}", + } + + kicad_cli = self._find_kicad_cli_static() + if not kicad_cli: + return {"success": False, "message": "kicad-cli not found in PATH"} + + output_path = os.path.abspath(os.path.expanduser(output_path)) + parent = os.path.dirname(output_path) + if parent: + os.makedirs(parent, exist_ok=True) + + cmd = [kicad_cli, "pcb", "export", fmt, "--output", output_path] + + for kv in params.get("defineVar", []) or []: + cmd += ["--define-var", kv] + + # Flags common to ALL 3D subcommands + common_flags = { + "force": "--force", + "noUnspecified": "--no-unspecified", + "noDnp": "--no-dnp", + } + # Flags shared by step/glb/stl/ply/brep/xao (NOT vrml) + mesh_flags = { + "gridOrigin": "--grid-origin", + "drillOrigin": "--drill-origin", + "substModels": "--subst-models", + "boardOnly": "--board-only", + "cutViasInBody": "--cut-vias-in-body", + "noBoardBody": "--no-board-body", + "noComponents": "--no-components", + "includeTracks": "--include-tracks", + "includePads": "--include-pads", + "includeZones": "--include-zones", + "includeInnerCopper": "--include-inner-copper", + "includeSilkscreen": "--include-silkscreen", + "includeSoldermask": "--include-soldermask", + "fuseShapes": "--fuse-shapes", + "fillAllVias": "--fill-all-vias", + } + # STEP-only flag + step_flags = { + "noOptimizeStep": "--no-optimize-step", + } + + flag_map = dict(common_flags) + if fmt != "vrml": + flag_map.update(mesh_flags) + if fmt == "step": + flag_map.update(step_flags) + for key, flag in flag_map.items(): + if params.get(key): + cmd.append(flag) + + # Valued flags common to all: user-origin + if params.get("userOrigin") is not None and params.get("userOrigin") != "": + cmd += ["--user-origin", str(params["userOrigin"])] + # Component filter + net filter + min distance: mesh subcommands only + if fmt != "vrml": + if params.get("componentFilter") is not None and params["componentFilter"] != "": + cmd += ["--component-filter", str(params["componentFilter"])] + if params.get("netFilter") is not None and params["netFilter"] != "": + cmd += ["--net-filter", str(params["netFilter"])] + if params.get("minDistance") is not None and params["minDistance"] != "": + cmd += ["--min-distance", str(params["minDistance"])] + # VRML-only valued flags + if fmt == "vrml": + if params.get("units") is not None and params["units"] != "": + cmd += ["--units", str(params["units"])] + if params.get("modelsDir") is not None and params["modelsDir"] != "": + cmd += ["--models-dir", str(params["modelsDir"])] + if params.get("modelsRelative"): + cmd.append("--models-relative") + + cmd.append(board_path) + + logger.info(f"Running: {' '.join(cmd)}") + result = subprocess.run(cmd, capture_output=True, text=True, timeout=300) + + if result.returncode != 0: + return { + "success": False, + "message": f"kicad-cli failed (exit {result.returncode}): " + f"{result.stderr.strip()}", + } + return {"success": True, "outputPath": output_path} + + except FileNotFoundError: + return {"success": False, "message": "kicad-cli not found in PATH"} + except subprocess.TimeoutExpired: + return {"success": False, "message": "kicad-cli timed out after 300 seconds"} + except Exception as e: + logger.error(f"Error exporting 3D model: {e}") + return {"success": False, "message": str(e)} + def _handle_generate_netlist(self, params: Dict[str, Any]) -> Dict[str, Any]: """Generate netlist from schematic and return structured JSON. diff --git a/src/tools/export.ts b/src/tools/export.ts index acc0d4f..afa242a 100644 --- a/src/tools/export.ts +++ b/src/tools/export.ts @@ -933,5 +933,105 @@ export function registerExportTools(server: McpServer, callKicadScript: CommandF }, ); + // ------------------------------------------------------ + // Export 3D Model Tool (kicad-cli, format dispatch + full flag union) + // ------------------------------------------------------ + server.tool( + "export_3d_cli", + "Export a 3D model of the PCB via kicad-cli. The `format` param selects the subcommand (step, glb, stl, ply, brep, xao, vrml); only flags valid for that subcommand are forwarded. STEP/glb/stl/ply/brep/xao share the geometry/include flag set (no-board-body, include-tracks/pads/zones/inner-copper/silkscreen/soldermask, fuse-shapes, fill-all-vias, component/net filters, min-distance, etc.; no-optimize-step is STEP-only); vrml uses units + models-dir/models-relative instead. Rich CLI sibling of export_3d and export_vrml. Reads the last SAVED state of the .kicad_pcb.", + { + outputPath: z.string().describe("Output 3D model file path"), + format: z + .enum(["step", "glb", "stl", "ply", "brep", "xao", "vrml"]) + .describe("3D output format (selects the kicad-cli subcommand)"), + boardPath: z.string().optional().describe("Path to the .kicad_pcb (default: current board)"), + defineVar: z + .array(z.string()) + .optional() + .describe("Project variable overrides as 'KEY=VALUE' strings"), + // common to all formats + force: z.boolean().optional().describe("Overwrite output file"), + noUnspecified: z + .boolean() + .optional() + .describe("Exclude 3D models for components with 'Unspecified' footprint type"), + noDnp: z + .boolean() + .optional() + .describe("Exclude 3D models for components with 'Do not populate' attribute"), + userOrigin: z + .string() + .optional() + .describe("User-specified output origin e.g. '1x1in', '25.4x25.4mm' (default unit mm)"), + // mesh subcommands only (step/glb/stl/ply/brep/xao) + gridOrigin: z.boolean().optional().describe("Use Grid Origin for output origin"), + drillOrigin: z.boolean().optional().describe("Use Drill Origin for output origin"), + substModels: z + .boolean() + .optional() + .describe("Substitute STEP/IGS models in place of VRML models"), + boardOnly: z.boolean().optional().describe("Only generate a board with no components"), + cutViasInBody: z + .boolean() + .optional() + .describe("Cut via holes in board body even if conductor layers not exported"), + noBoardBody: z.boolean().optional().describe("Exclude board body"), + noComponents: z.boolean().optional().describe("Exclude 3D models for components"), + componentFilter: z + .string() + .optional() + .describe("Only include component models matching this refdes list (comma, wildcards)"), + includeTracks: z.boolean().optional().describe("Export tracks and vias"), + includePads: z.boolean().optional().describe("Export pads"), + includeZones: z.boolean().optional().describe("Export zones"), + includeInnerCopper: z.boolean().optional().describe("Export elements on inner copper layers"), + includeSilkscreen: z + .boolean() + .optional() + .describe("Export silkscreen graphics as flat faces"), + includeSoldermask: z.boolean().optional().describe("Export soldermask layers as flat faces"), + fuseShapes: z.boolean().optional().describe("Fuse overlapping geometry together"), + fillAllVias: z.boolean().optional().describe("Don't cut via holes in conductor layers"), + minDistance: z + .string() + .optional() + .describe("Min distance between points to treat as separate (default '0.01mm')"), + netFilter: z + .string() + .optional() + .describe("Only include copper items belonging to nets matching this wildcard"), + // STEP only + noOptimizeStep: z + .boolean() + .optional() + .describe("Do not optimize STEP file (enables writing parametric curves; STEP only)"), + // VRML only + units: z + .enum(["mm", "m", "in", "tenths"]) + .optional() + .describe("Output units (VRML only; default in)"), + modelsDir: z + .string() + .optional() + .describe("Folder to store 3D models in (VRML only; empty = embed in main file)"), + modelsRelative: z + .boolean() + .optional() + .describe("Use relative model paths with modelsDir (VRML only)"), + }, + async (args) => { + logger.debug(`Exporting 3D model (${args.format}) to: ${args.outputPath}`); + const result = await callKicadScript("export_3d_cli", args); + return { + content: [ + { + type: "text", + text: JSON.stringify(result), + }, + ], + }; + }, + ); + logger.info("Export tools registered"); } diff --git a/src/tools/registry.ts b/src/tools/registry.ts index 557d7c1..8441b22 100644 --- a/src/tools/registry.ts +++ b/src/tools/registry.ts @@ -69,6 +69,7 @@ export const toolCategories: ToolCategory[] = [ "export_pcb_svg", "export_pcb_dxf", "export_gerber_single", + "export_3d_cli", "export_pdf", "export_svg", "export_3d",