From f6d38f194211ed2205e12b01badad9e4a31e02cb Mon Sep 17 00:00:00 2001 From: Gavin Colonese Date: Fri, 12 Jun 2026 10:55:50 -0400 Subject: [PATCH] feat: add export_pos tool (kicad-cli, full placement-file option set) New MCP tool `export_pos` wrapping `kicad-cli pcb export pos`: exposes side, format, units, bottom-negate-X, drill-file origin, SMD-only, exclude-through-hole, exclude-DNP and gerber-board-edge. Rich CLI sibling of the existing SWIG-limited export_position_file (left untouched). Self-contained interface handler reading the saved .kicad_pcb. Co-Authored-By: Claude Opus 4.8 (1M context) --- python/kicad_interface.py | 80 +++++++++++++++++++++++++++++++++++++++ src/tools/export.ts | 54 ++++++++++++++++++++++++++ src/tools/registry.ts | 1 + 3 files changed, 135 insertions(+) diff --git a/python/kicad_interface.py b/python/kicad_interface.py index e2ca486..6f36c5a 100644 --- a/python/kicad_interface.py +++ b/python/kicad_interface.py @@ -593,6 +593,7 @@ class KiCADInterface: "export_odb": self._handle_export_odb, "export_ipcd356": self._handle_export_ipcd356, "export_gencad": self._handle_export_gencad, + "export_pos": self._handle_export_pos, "generate_netlist": self._handle_generate_netlist, "sync_schematic_to_board": self._handle_sync_schematic_to_board, "list_schematic_libraries": self._handle_list_schematic_libraries, @@ -4959,6 +4960,85 @@ class KiCADInterface: logger.error(f"Error exporting GenCAD: {e}") return {"success": False, "message": str(e)} + def _handle_export_pos(self, params: Dict[str, Any]) -> Dict[str, Any]: + """Generate a component placement (position) file via kicad-cli + (`pcb export pos`). + + This is the rich CLI sibling of export_position_file: full option set + (side, format, units, bottom-negate-X, drill origin, SMD-only, TH/DNP + exclusion, gerber board edge). Reads the saved .kicad_pcb. + """ + import subprocess + + logger.info("Exporting position file 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", "pos", "--output", output_path] + + value_map = { + "side": "--side", + "format": "--format", + "units": "--units", + } + for key, flag in value_map.items(): + val = params.get(key) + if val is not None and val != "": + cmd += [flag, str(val)] + + flag_map = { + "bottomNegateX": "--bottom-negate-x", + "useDrillFileOrigin": "--use-drill-file-origin", + "smdOnly": "--smd-only", + "excludeFpTh": "--exclude-fp-th", + "excludeDnp": "--exclude-dnp", + "gerberBoardEdge": "--gerber-board-edge", + } + 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 position file: {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 cd42f57..8dae799 100644 --- a/src/tools/export.ts +++ b/src/tools/export.ts @@ -594,5 +594,59 @@ export function registerExportTools(server: McpServer, callKicadScript: CommandF }, ); + // ------------------------------------------------------ + // Export Position File Tool (kicad-cli, full option set) + // ------------------------------------------------------ + server.tool( + "export_pos", + "Generate a component placement (position / pick-and-place) file via kicad-cli, exposing the full CLI option set (side, format, units, bottom-negate-X, drill-file origin, SMD-only, exclude through-hole / DNP, gerber board edge). Rich CLI sibling of export_position_file. Reads the last SAVED state of the .kicad_pcb.", + { + outputPath: z.string().describe("Output position file path"), + boardPath: z.string().optional().describe("Path to the .kicad_pcb (default: current board)"), + side: z + .enum(["front", "back", "both"]) + .optional() + .describe("Board side (gerber format only supports front or back; default both)"), + format: z + .enum(["ascii", "csv", "gerber"]) + .optional() + .describe("Output format (default ascii)"), + units: z + .enum(["in", "mm"]) + .optional() + .describe("Output units; ascii or csv format only (default in)"), + bottomNegateX: z + .boolean() + .optional() + .describe("Use negative X coordinates for bottom-layer footprints (ascii/csv only)"), + useDrillFileOrigin: z + .boolean() + .optional() + .describe("Use drill/place file origin (ascii/csv only)"), + smdOnly: z.boolean().optional().describe("Include only SMD footprints (ascii/csv only)"), + excludeFpTh: z + .boolean() + .optional() + .describe("Exclude all footprints with through-hole pads (ascii/csv only)"), + excludeDnp: z + .boolean() + .optional() + .describe("Exclude all footprints with the Do Not Populate flag set"), + gerberBoardEdge: z.boolean().optional().describe("Include board edge layer (Gerber only)"), + }, + async (args) => { + logger.debug(`Exporting position file to: ${args.outputPath}`); + const result = await callKicadScript("export_pos", 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 92d5c6c..e38a605 100644 --- a/src/tools/registry.ts +++ b/src/tools/registry.ts @@ -64,6 +64,7 @@ export const toolCategories: ToolCategory[] = [ "export_odb", "export_ipcd356", "export_gencad", + "export_pos", "export_pdf", "export_svg", "export_3d",