feat: add export_pcb_dxf tool (kicad-cli, full layer-plot DXF)

New MCP tool `export_pcb_dxf` wrapping `kicad-cli pcb export dxf`: exposes
the full layer-plot surface (layer/common-layer lists, refdes/value
exclusion, soldermask subtraction, use-contours, use-drill-origin,
border+title, output-units, the four DNP fab-layer modes, drill-shape, and
the single/multi output modes). 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:57:09 -04:00
parent 494c2e1ffb
commit ce6cff1b39
3 changed files with 177 additions and 0 deletions

View File

@@ -596,6 +596,7 @@ class KiCADInterface:
"export_pos": self._handle_export_pos,
"export_pcb_pdf": self._handle_export_pcb_pdf,
"export_pcb_svg": self._handle_export_pcb_svg,
"export_pcb_dxf": self._handle_export_pcb_dxf,
"generate_netlist": self._handle_generate_netlist,
"sync_schematic_to_board": self._handle_sync_schematic_to_board,
"list_schematic_libraries": self._handle_list_schematic_libraries,
@@ -5250,6 +5251,109 @@ class KiCADInterface:
logger.error(f"Error exporting PCB SVG: {e}")
return {"success": False, "message": str(e)}
def _handle_export_pcb_dxf(self, params: Dict[str, Any]) -> Dict[str, Any]:
"""Plot the PCB to DXF via kicad-cli (`pcb export dxf`).
Exposes the full layer-plot option set: layer lists, refdes/value
exclusion, soldermask subtraction, contours, drill origin, border+title,
output units, DNP fab-layer modes, drill-shape, and single/multi output
modes. Reads the saved .kicad_pcb.
"""
import subprocess
logger.info("Exporting PCB DXF via kicad-cli")
try:
board_path = params.get("boardPath") or self._current_board_path()
output_path = params.get("outputPath")
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"}
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", "dxf", "--output", output_path]
layers = params.get("layers")
if layers:
cmd += ["--layers", ",".join(layers) if isinstance(layers, list) else str(layers)]
common_layers = params.get("commonLayers")
if common_layers:
cmd += [
"--common-layers",
(
",".join(common_layers)
if isinstance(common_layers, list)
else str(common_layers)
),
]
if params.get("drawingSheet"):
cmd += ["--drawing-sheet", params["drawingSheet"]]
for kv in params.get("defineVar", []) or []:
cmd += ["--define-var", kv]
value_map = {
"outputUnits": "--output-units",
"drillShapeOpt": "--drill-shape-opt",
}
for key, flag in value_map.items():
val = params.get(key)
if val is not None and val != "":
cmd += [flag, str(val)]
flag_map = {
"excludeRefdes": "--exclude-refdes",
"excludeValue": "--exclude-value",
"sketchPadsOnFabLayers": "--sketch-pads-on-fab-layers",
"hideDnpFootprintsOnFabLayers": "--hide-DNP-footprints-on-fab-layers",
"sketchDnpFootprintsOnFabLayers": "--sketch-DNP-footprints-on-fab-layers",
"crossoutDnpFootprintsOnFabLayers": "--crossout-DNP-footprints-on-fab-layers",
"subtractSoldermask": "--subtract-soldermask",
"useContours": "--use-contours",
"useDrillOrigin": "--use-drill-origin",
"includeBorderTitle": "--include-border-title",
"modeSingle": "--mode-single",
"modeMulti": "--mode-multi",
}
for key, flag in flag_map.items():
if params.get(key):
cmd.append(flag)
cmd.append(board_path)
logger.info(f"Running: {' '.join(cmd)}")
result = subprocess.run(cmd, capture_output=True, text=True, timeout=180)
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 180 seconds"}
except Exception as e:
logger.error(f"Error exporting PCB DXF: {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.