From 82e5de7aa94696ac768276db1f5f9d0390bbbd08 Mon Sep 17 00:00:00 2001 From: Gavin Colonese Date: Fri, 12 Jun 2026 10:53:19 -0400 Subject: [PATCH] feat: add export_gerbers tool (kicad-cli, full Plot option set) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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) --- python/kicad_interface.py | 108 +++++++++++++++++++++++++++++++++++++- src/tools/export.ts | 70 ++++++++++++++++++++++++ src/tools/registry.ts | 1 + 3 files changed, 177 insertions(+), 2 deletions(-) diff --git a/python/kicad_interface.py b/python/kicad_interface.py index eb15e26..0ecb4fd 100644 --- a/python/kicad_interface.py +++ b/python/kicad_interface.py @@ -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. diff --git a/src/tools/export.ts b/src/tools/export.ts index 41d3f90..a03588d 100644 --- a/src/tools/export.ts +++ b/src/tools/export.ts @@ -323,5 +323,75 @@ export function registerExportTools(server: McpServer, callKicadScript: CommandF }, ); + // ------------------------------------------------------ + // Export Gerbers Tool (kicad-cli, full option set) + // ------------------------------------------------------ + server.tool( + "export_gerbers", + "Plot Gerber files for a PCB via kicad-cli, exposing the full Plot-dialog option set (X2, netlist attributes, DNP handling, soldermask subtraction, precision, drill-file origin, stored board plot settings, etc). Reads the board from disk, so it reflects the last SAVED state of the .kicad_pcb.", + { + outputDir: z.string().describe("Output directory for the Gerber files"), + boardPath: z.string().optional().describe("Path to the .kicad_pcb (default: current board)"), + layers: z + .array(z.string()) + .optional() + .describe("Layers to plot, untranslated names e.g. ['F.Cu','B.Cu','Edge.Cuts']"), + commonLayers: z + .array(z.string()) + .optional() + .describe("Layers to include on every plot (e.g. ['Edge.Cuts'])"), + drawingSheet: z.string().optional().describe("Path to a drawing sheet override"), + defineVar: z + .array(z.string()) + .optional() + .describe("Project variable overrides as 'KEY=VALUE' strings"), + excludeRefdes: z.boolean().optional().describe("Exclude reference designator text"), + excludeValue: z.boolean().optional().describe("Exclude value text"), + includeBorderTitle: z.boolean().optional().describe("Include border and title block"), + sketchPadsOnFabLayers: z + .boolean() + .optional() + .describe("Draw pad outlines and numbers on fab layers"), + hideDnpFootprintsOnFabLayers: z + .boolean() + .optional() + .describe("Don't plot DNP footprint text/graphics on fab layers"), + sketchDnpFootprintsOnFabLayers: z + .boolean() + .optional() + .describe("Plot DNP footprints in sketch mode on fab layers"), + crossoutDnpFootprintsOnFabLayers: z + .boolean() + .optional() + .describe("Plot an 'X' over DNP footprint courtyards and strike out their refdes"), + noX2: z.boolean().optional().describe("Do not use the extended X2 Gerber format"), + noNetlist: z.boolean().optional().describe("Do not generate netlist attributes"), + subtractSoldermask: z.boolean().optional().describe("Subtract soldermask from silkscreen"), + disableApertureMacros: z.boolean().optional().describe("Disable aperture macros"), + useDrillFileOrigin: z.boolean().optional().describe("Use the drill/place file origin"), + noProtelExt: z + .boolean() + .optional() + .describe("Use KiCad Gerber file extensions instead of Protel"), + boardPlotParams: z + .boolean() + .optional() + .describe("Use the Gerber plot settings already stored in the board file"), + precision: z.number().optional().describe("Gerber coordinate precision: 5 or 6 (default 6)"), + }, + async (args) => { + logger.debug(`Exporting Gerbers to: ${args.outputDir}`); + const result = await callKicadScript("export_gerbers", 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 6f1f569..482ede6 100644 --- a/src/tools/registry.ts +++ b/src/tools/registry.ts @@ -58,6 +58,7 @@ export const toolCategories: ToolCategory[] = [ description: "File export for fabrication and documentation: Gerber, PDF, BOM, 3D models", tools: [ "export_gerber", + "export_gerbers", "export_pdf", "export_svg", "export_3d",