From 7210e0b59c16f8b70f80b0628aa6cadf740f282a Mon Sep 17 00:00:00 2001 From: Gavin Colonese Date: Fri, 12 Jun 2026 10:58:25 -0400 Subject: [PATCH] feat: add export_sch_bom tool (kicad-cli, schematic BOM) New MCP tool `export_sch_bom` wrapping `kicad-cli sch export bom`: exposes the full BOM option set (presets, field/label lists, group-by, sort field/direction, filter, exclude-DNP, include-excluded-from-BOM, and the field/string/ref/ref-range delimiters, plus keep-tabs/keep-line-breaks). schematicPath is required and validated. Self-contained interface handler. Co-Authored-By: Claude Opus 4.8 (1M context) --- python/kicad_interface.py | 84 +++++++++++++++++++++++++++++++++++++++ src/tools/export.ts | 73 ++++++++++++++++++++++++++++++++++ src/tools/registry.ts | 1 + 3 files changed, 158 insertions(+) diff --git a/python/kicad_interface.py b/python/kicad_interface.py index e1ef9be..d892640 100644 --- a/python/kicad_interface.py +++ b/python/kicad_interface.py @@ -599,6 +599,7 @@ class KiCADInterface: "export_pcb_dxf": self._handle_export_pcb_dxf, "export_gerber_single": self._handle_export_gerber_single, "export_3d_cli": self._handle_export_3d_cli, + "export_sch_bom": self._handle_export_sch_bom, "generate_netlist": self._handle_generate_netlist, "sync_schematic_to_board": self._handle_sync_schematic_to_board, "list_schematic_libraries": self._handle_list_schematic_libraries, @@ -5583,6 +5584,89 @@ class KiCADInterface: logger.error(f"Error exporting 3D model: {e}") return {"success": False, "message": str(e)} + def _handle_export_sch_bom(self, params: Dict[str, Any]) -> Dict[str, Any]: + """Generate a Bill of Materials from a schematic via kicad-cli + (`sch export bom`). + + Exposes the full BOM option set: presets, field/label lists, grouping, + sorting, filtering, DNP/excluded handling, and the field/string/ref + delimiters. schematicPath is required (no current-schematic resolver). + """ + import subprocess + + logger.info("Exporting schematic BOM via kicad-cli") + try: + schematic_path = params.get("schematicPath") + output_path = params.get("outputPath") + + if not schematic_path: + return {"success": False, "message": "schematicPath is required"} + if not os.path.exists(schematic_path): + return {"success": False, "message": f"Schematic not found: {schematic_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, "sch", "export", "bom", "--output", output_path] + + value_map = { + "preset": "--preset", + "formatPreset": "--format-preset", + "fields": "--fields", + "labels": "--labels", + "groupBy": "--group-by", + "sortField": "--sort-field", + "sortAsc": "--sort-asc", + "filter": "--filter", + "fieldDelimiter": "--field-delimiter", + "stringDelimiter": "--string-delimiter", + "refDelimiter": "--ref-delimiter", + "refRangeDelimiter": "--ref-range-delimiter", + } + for key, flag in value_map.items(): + val = params.get(key) + if val is not None and val != "": + cmd += [flag, str(val)] + + flag_map = { + "excludeDnp": "--exclude-dnp", + "includeExcludedFromBom": "--include-excluded-from-bom", + "keepTabs": "--keep-tabs", + "keepLineBreaks": "--keep-line-breaks", + } + for key, flag in flag_map.items(): + if params.get(key): + cmd.append(flag) + + cmd.append(schematic_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 schematic BOM: {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 afa242a..d1364e9 100644 --- a/src/tools/export.ts +++ b/src/tools/export.ts @@ -1033,5 +1033,78 @@ export function registerExportTools(server: McpServer, callKicadScript: CommandF }, ); + // ------------------------------------------------------ + // Export Schematic BOM Tool (kicad-cli, full option set) + // ------------------------------------------------------ + server.tool( + "export_sch_bom", + "Generate a Bill of Materials from a schematic via kicad-cli (`sch export bom`), exposing the full option set (presets, field/label lists, grouping, sorting, filtering, DNP/excluded-from-BOM handling, and field/string/ref delimiters). schematicPath is REQUIRED.", + { + schematicPath: z.string().describe("Path to the .kicad_sch (required)"), + outputPath: z.string().describe("Output BOM file path"), + preset: z + .string() + .optional() + .describe("Named BOM preset from the schematic, e.g. 'Grouped By Value'"), + formatPreset: z + .string() + .optional() + .describe("Named BOM format preset from the schematic, e.g. 'CSV'"), + fields: z + .string() + .optional() + .describe("Ordered comma list of fields to export (supports special substitutions)"), + labels: z + .string() + .optional() + .describe("Ordered comma list of labels to apply to the exported fields"), + groupBy: z + .string() + .optional() + .describe("Fields to group references by when field values match"), + sortField: z.string().optional().describe("Field name to sort by (default Reference)"), + sortAsc: z.string().optional().describe("Sort ascending ('true') or descending ('false')"), + filter: z.string().optional().describe("Filter string to remove output lines"), + excludeDnp: z.boolean().optional().describe("Exclude symbols marked Do-Not-Populate"), + includeExcludedFromBom: z + .boolean() + .optional() + .describe("Include symbols marked 'Exclude from BOM'"), + fieldDelimiter: z + .string() + .optional() + .describe("Separator between output fields/columns (default ',')"), + stringDelimiter: z + .string() + .optional() + .describe("Character to surround fields with (default '\"')"), + refDelimiter: z + .string() + .optional() + .describe("Character between individual references (default ',')"), + refRangeDelimiter: z + .string() + .optional() + .describe("Character for reference ranges; blank disables ranges (default '-')"), + keepTabs: z.boolean().optional().describe("Keep tab characters from input fields"), + keepLineBreaks: z + .boolean() + .optional() + .describe("Keep line break characters from input fields"), + }, + async (args) => { + logger.debug(`Exporting schematic BOM to: ${args.outputPath}`); + const result = await callKicadScript("export_sch_bom", 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 8441b22..f04a979 100644 --- a/src/tools/registry.ts +++ b/src/tools/registry.ts @@ -70,6 +70,7 @@ export const toolCategories: ToolCategory[] = [ "export_pcb_dxf", "export_gerber_single", "export_3d_cli", + "export_sch_bom", "export_pdf", "export_svg", "export_3d",