feat: add export_gerbers tool (kicad-cli, full Plot option set)

New MCP tool `export_gerbers` wrapping `kicad-cli pcb export gerbers`,
exposing the complete Plot-dialog option surface that the existing
SWIG-based export_gerber lacks: layer + common-layer lists, X2 on/off,
netlist attributes, soldermask subtraction, aperture macros, the three
DNP fab-layer modes, refdes/value exclusion, border+title, drill-file
origin, coordinate precision (5/6), Protel vs KiCad extensions, and
--board-plot-params to reuse the board's stored plot settings.

Implemented as a self-contained interface handler (_handle_export_gerbers)
that resolves the board path (param or current board) and shells out to
kicad-cli, mirroring the _handle_export_netlist pattern — no dependence
on a live SWIG board, since the KiCad IPC API exposes no plot/export
endpoints. Reads the saved .kicad_pcb on disk.

Wiring: dispatch map + src/tools/export.ts registration + export
category in registry.ts.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Gavin Colonese
2026-06-12 10:53:19 -04:00
parent 2fb54802b6
commit 82e5de7aa9
3 changed files with 177 additions and 2 deletions

View File

@@ -325,9 +325,9 @@ try:
from commands.project import ProjectCommands
from commands.routing import RoutingCommands
from commands.schematic import SchematicManager
from commands.schematic_hierarchy import SchematicHierarchyCommands
from commands.schematic_field_layout import SchematicFieldLayoutCommands
from commands.schematic_batch import SchematicBatchCommands
from commands.schematic_field_layout import SchematicFieldLayoutCommands
from commands.schematic_hierarchy import SchematicHierarchyCommands
from commands.symbol_creator import SymbolCreator
from commands.symbol_pins import SymbolPinCommands
@@ -587,6 +587,7 @@ class KiCADInterface:
"get_net_at_point": self._handle_get_net_at_point,
"run_erc": self._handle_run_erc,
"export_netlist": self._handle_export_netlist,
"export_gerbers": self._handle_export_gerbers,
"generate_netlist": self._handle_generate_netlist,
"sync_schematic_to_board": self._handle_sync_schematic_to_board,
"list_schematic_libraries": self._handle_list_schematic_libraries,
@@ -4496,6 +4497,109 @@ class KiCADInterface:
logger.error(f"Error exporting netlist: {e}")
return {"success": False, "message": str(e)}
def _handle_export_gerbers(self, params: Dict[str, Any]) -> Dict[str, Any]:
"""Plot multiple Gerbers for a PCB via kicad-cli (`pcb export gerbers`).
Exposes the full Plot-dialog option set. Reads the board from disk, so it
reflects the last *saved* state of the .kicad_pcb. Pass ``boardPath`` to
target a specific file; otherwise the current board path is used.
"""
import subprocess
logger.info("Exporting Gerbers via kicad-cli")
try:
board_path = params.get("boardPath") or self._current_board_path()
output_dir = params.get("outputDir")
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_dir:
return {"success": False, "message": "outputDir is required"}
kicad_cli = self._find_kicad_cli_static()
if not kicad_cli:
return {"success": False, "message": "kicad-cli not found in PATH"}
output_dir = os.path.abspath(os.path.expanduser(output_dir))
os.makedirs(output_dir, exist_ok=True)
cmd = [kicad_cli, "pcb", "export", "gerbers", "--output", output_dir]
# Layer selection (accept list or comma string)
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]
# Boolean flags (omit to leave at kicad-cli default)
flag_map = {
"excludeRefdes": "--exclude-refdes",
"excludeValue": "--exclude-value",
"includeBorderTitle": "--include-border-title",
"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",
"noX2": "--no-x2",
"noNetlist": "--no-netlist",
"subtractSoldermask": "--subtract-soldermask",
"disableApertureMacros": "--disable-aperture-macros",
"useDrillFileOrigin": "--use-drill-file-origin",
"noProtelExt": "--no-protel-ext",
"boardPlotParams": "--board-plot-params",
}
for key, flag in flag_map.items():
if params.get(key):
cmd.append(flag)
precision = params.get("precision")
if precision is not None:
cmd += ["--precision", str(precision)]
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()}",
}
files = sorted(
f for f in os.listdir(output_dir) if os.path.isfile(os.path.join(output_dir, f))
)
return {"success": True, "outputDir": output_dir, "files": files}
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 Gerbers: {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.