feat: add export_3d_cli tool (kicad-cli, format-dispatched 3D export)

New MCP tool `export_3d_cli` wrapping the kicad-cli 3D subcommands. A
`format` enum {step,glb,stl,ply,brep,xao,vrml} selects the subcommand and
the handler forwards only flags valid for that subcommand: the shared
geometry/include set for step/glb/stl/ply/brep/xao, no-optimize-step for
STEP only, and units + models-dir/models-relative for VRML. Rich CLI
sibling of the existing export_3d / export_vrml (left untouched). Reads
the saved .kicad_pcb.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Gavin Colonese
2026-06-12 10:58:01 -04:00
parent 0faef07650
commit f23f1f658a
3 changed files with 228 additions and 0 deletions

View File

@@ -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 <fmt>`).
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.