From 494c2e1ffb35ca1887b2b18e70594351a0e9a1cd Mon Sep 17 00:00:00 2001 From: Gavin Colonese Date: Fri, 12 Jun 2026 10:56:41 -0400 Subject: [PATCH] feat: add export_pcb_svg tool (kicad-cli, full layer-plot SVG) New MCP tool `export_pcb_svg` wrapping `kicad-cli pcb export svg`: exposes the full layer-plot surface (layer/common-layer lists, mirror, soldermask subtraction, negative, B&W, theme, the four DNP fab-layer modes, page-size-mode, fit-page-to-board, exclude-drawing-sheet, drill-shape, and the single/multi output modes). Rich CLI sibling of the existing SWIG export_svg (left untouched). Reads the saved .kicad_pcb. Co-Authored-By: Claude Opus 4.8 (1M context) --- python/kicad_interface.py | 105 ++++++++++++++++++++++++++++++++++++++ src/tools/export.ts | 76 +++++++++++++++++++++++++++ src/tools/registry.ts | 1 + 3 files changed, 182 insertions(+) diff --git a/python/kicad_interface.py b/python/kicad_interface.py index dc00d69..6617c85 100644 --- a/python/kicad_interface.py +++ b/python/kicad_interface.py @@ -595,6 +595,7 @@ class KiCADInterface: "export_gencad": self._handle_export_gencad, "export_pos": self._handle_export_pos, "export_pcb_pdf": self._handle_export_pcb_pdf, + "export_pcb_svg": self._handle_export_pcb_svg, "generate_netlist": self._handle_generate_netlist, "sync_schematic_to_board": self._handle_sync_schematic_to_board, "list_schematic_libraries": self._handle_list_schematic_libraries, @@ -5145,6 +5146,110 @@ class KiCADInterface: logger.error(f"Error exporting PCB PDF: {e}") return {"success": False, "message": str(e)} + def _handle_export_pcb_svg(self, params: Dict[str, Any]) -> Dict[str, Any]: + """Plot the PCB to SVG via kicad-cli (`pcb export svg`). + + Exposes the full layer-plot option set: layer lists, mirror, soldermask + subtraction, negative/B&W, theme, DNP fab-layer modes, page-size mode, + fit-page, drill-shape, and single/multi output modes. Reads the saved + .kicad_pcb. + """ + import subprocess + + logger.info("Exporting PCB SVG 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", "svg", "--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 = { + "theme": "--theme", + "pageSizeMode": "--page-size-mode", + "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 = { + "subtractSoldermask": "--subtract-soldermask", + "mirror": "--mirror", + "negative": "--negative", + "blackAndWhite": "--black-and-white", + "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", + "fitPageToBoard": "--fit-page-to-board", + "excludeDrawingSheet": "--exclude-drawing-sheet", + "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 SVG: {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 db44ab7..031d214 100644 --- a/src/tools/export.ts +++ b/src/tools/export.ts @@ -719,5 +719,81 @@ export function registerExportTools(server: McpServer, callKicadScript: CommandF }, ); + // ------------------------------------------------------ + // Export PCB SVG Tool (kicad-cli, full layer-plot option set) + // ------------------------------------------------------ + server.tool( + "export_pcb_svg", + "Plot the PCB layout to SVG via kicad-cli, exposing the full layer-plot option set (layer + common-layer lists, mirror, soldermask subtraction, negative, black-and-white, theme, DNP fab-layer modes, page-size mode, fit-page-to-board, exclude-drawing-sheet, drill shape, single/multi output modes). Rich CLI sibling of export_svg. Reads the last SAVED state of the .kicad_pcb.", + { + outputPath: z.string().describe("Output SVG file path (or directory in multi mode)"), + 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"), + subtractSoldermask: z.boolean().optional().describe("Subtract soldermask from silkscreen"), + mirror: z.boolean().optional().describe("Mirror the board (to show bottom layers)"), + negative: z.boolean().optional().describe("Plot as negative"), + blackAndWhite: z.boolean().optional().describe("Black and white only"), + theme: z.string().optional().describe("Color theme to use (default: PCB editor settings)"), + 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"), + pageSizeMode: z + .number() + .optional() + .describe("Page sizing mode (0 frame+title block, 1 current page size, 2 board area only)"), + fitPageToBoard: z.boolean().optional().describe("Fit the page to the board"), + excludeDrawingSheet: z.boolean().optional().describe("No drawing sheet"), + drillShapeOpt: z + .number() + .optional() + .describe("Pad/via drill shape option (0 none, 1 small, 2 actual; default 2)"), + modeSingle: z + .boolean() + .optional() + .describe("Single file; output path is full path; LAYER_LIST controls all layers"), + modeMulti: z + .boolean() + .optional() + .describe("Multi output; output path is a directory (GUI-like plotting)"), + }, + async (args) => { + logger.debug(`Exporting PCB SVG to: ${args.outputPath}`); + const result = await callKicadScript("export_pcb_svg", 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 a53d71f..8d5eb79 100644 --- a/src/tools/registry.ts +++ b/src/tools/registry.ts @@ -66,6 +66,7 @@ export const toolCategories: ToolCategory[] = [ "export_gencad", "export_pos", "export_pcb_pdf", + "export_pcb_svg", "export_pdf", "export_svg", "export_3d",