From ab7a2101afcba34428d7f0a483af0bbdd9d52dba Mon Sep 17 00:00:00 2001 From: Gavin Colonese Date: Fri, 12 Jun 2026 10:55:26 -0400 Subject: [PATCH] feat: add export_gencad tool (kicad-cli, GenCAD assembly/test format) New MCP tool `export_gencad` wrapping `kicad-cli pcb export gencad`: exposes define-var plus the flip-bottom-pads, unique-pins, unique-footprints, use-drill-origin and store-origin-coord flags. Self-contained interface handler reading the saved .kicad_pcb. Co-Authored-By: Claude Opus 4.8 (1M context) --- python/kicad_interface.py | 71 +++++++++++++++++++++++++++++++++++++++ src/tools/export.ts | 36 ++++++++++++++++++++ src/tools/registry.ts | 1 + 3 files changed, 108 insertions(+) diff --git a/python/kicad_interface.py b/python/kicad_interface.py index 340c721..e2ca486 100644 --- a/python/kicad_interface.py +++ b/python/kicad_interface.py @@ -592,6 +592,7 @@ class KiCADInterface: "export_ipc2581": self._handle_export_ipc2581, "export_odb": self._handle_export_odb, "export_ipcd356": self._handle_export_ipcd356, + "export_gencad": self._handle_export_gencad, "generate_netlist": self._handle_generate_netlist, "sync_schematic_to_board": self._handle_sync_schematic_to_board, "list_schematic_libraries": self._handle_list_schematic_libraries, @@ -4888,6 +4889,76 @@ class KiCADInterface: logger.error(f"Error exporting IPC-D-356: {e}") return {"success": False, "message": str(e)} + def _handle_export_gencad(self, params: Dict[str, Any]) -> Dict[str, Any]: + """Export the PCB in GenCAD format via kicad-cli (`pcb export gencad`). + + GenCAD is an assembly/test interchange format. Exposes the padstack-flip, + unique-pin/footprint, drill-origin, and store-origin flags. Reads the + saved .kicad_pcb. + """ + import subprocess + + logger.info("Exporting GenCAD 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", "gencad", "--output", output_path] + + for kv in params.get("defineVar", []) or []: + cmd += ["--define-var", kv] + + flag_map = { + "flipBottomPads": "--flip-bottom-pads", + "uniquePins": "--unique-pins", + "uniqueFootprints": "--unique-footprints", + "useDrillOrigin": "--use-drill-origin", + "storeOriginCoord": "--store-origin-coord", + } + 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 GenCAD: {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 727beff..cd42f57 100644 --- a/src/tools/export.ts +++ b/src/tools/export.ts @@ -558,5 +558,41 @@ export function registerExportTools(server: McpServer, callKicadScript: CommandF }, ); + // ------------------------------------------------------ + // Export GenCAD Tool (kicad-cli) + // ------------------------------------------------------ + server.tool( + "export_gencad", + "Export the PCB in GenCAD format via kicad-cli. Assembly/test interchange format. Exposes padstack flip, unique pin/footprint shape generation, drill-file origin, and store-origin-coordinate options. Reads the last SAVED state of the .kicad_pcb.", + { + outputPath: z.string().describe("Output .cad file path"), + 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"), + flipBottomPads: z.boolean().optional().describe("Flip bottom footprint padstacks"), + uniquePins: z.boolean().optional().describe("Generate unique pin names"), + uniqueFootprints: z + .boolean() + .optional() + .describe("Generate a new shape for each footprint instance (do not reuse shapes)"), + useDrillOrigin: z.boolean().optional().describe("Use drill/place file origin as origin"), + storeOriginCoord: z.boolean().optional().describe("Save the origin coordinates in the file"), + }, + async (args) => { + logger.debug(`Exporting GenCAD to: ${args.outputPath}`); + const result = await callKicadScript("export_gencad", 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 8b1a6a5..92d5c6c 100644 --- a/src/tools/registry.ts +++ b/src/tools/registry.ts @@ -63,6 +63,7 @@ export const toolCategories: ToolCategory[] = [ "export_ipc2581", "export_odb", "export_ipcd356", + "export_gencad", "export_pdf", "export_svg", "export_3d",