feat: add export_gerber_single tool (kicad-cli, single-file Gerber)
New MCP tool `export_gerber_single` wrapping `kicad-cli pcb export gerber`: plots the selected layers to a SINGLE Gerber file (singular sibling of export_gerbers). Exposes the full single-file Plot option set (X2, netlist attributes, the four DNP fab-layer modes, soldermask subtraction, aperture macros, drill-file origin, precision, Protel extension). Reads the saved .kicad_pcb. Note: this subcommand is deprecated in KiCad 9.0 (still exits 0). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -597,6 +597,7 @@ class KiCADInterface:
|
||||
"export_pcb_pdf": self._handle_export_pcb_pdf,
|
||||
"export_pcb_svg": self._handle_export_pcb_svg,
|
||||
"export_pcb_dxf": self._handle_export_pcb_dxf,
|
||||
"export_gerber_single": self._handle_export_gerber_single,
|
||||
"generate_netlist": self._handle_generate_netlist,
|
||||
"sync_schematic_to_board": self._handle_sync_schematic_to_board,
|
||||
"list_schematic_libraries": self._handle_list_schematic_libraries,
|
||||
@@ -5354,6 +5355,107 @@ class KiCADInterface:
|
||||
logger.error(f"Error exporting PCB DXF: {e}")
|
||||
return {"success": False, "message": str(e)}
|
||||
|
||||
def _handle_export_gerber_single(self, params: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""Plot the given layers to a single Gerber file via kicad-cli
|
||||
(`pcb export gerber`).
|
||||
|
||||
Singular sibling of export_gerbers: emits ONE Gerber file containing the
|
||||
selected layers. Exposes the full single-file Plot option set (X2,
|
||||
netlist attributes, DNP fab-layer modes, soldermask subtraction, aperture
|
||||
macros, drill-file origin, precision, Protel extension). Reads the saved
|
||||
.kicad_pcb.
|
||||
"""
|
||||
import subprocess
|
||||
|
||||
logger.info("Exporting single Gerber 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", "gerber", "--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]
|
||||
|
||||
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",
|
||||
}
|
||||
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()}",
|
||||
}
|
||||
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 single Gerber: {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.
|
||||
|
||||
|
||||
@@ -867,5 +867,71 @@ export function registerExportTools(server: McpServer, callKicadScript: CommandF
|
||||
},
|
||||
);
|
||||
|
||||
// ------------------------------------------------------
|
||||
// Export Single Gerber Tool (kicad-cli, full Plot option set)
|
||||
// ------------------------------------------------------
|
||||
server.tool(
|
||||
"export_gerber_single",
|
||||
"Plot the given layers to a SINGLE Gerber file via kicad-cli (`pcb export gerber`). Singular sibling of export_gerbers. Exposes the full single-file Plot option set (X2, netlist attributes, DNP fab-layer modes, soldermask subtraction, aperture macros, drill-file origin, precision, Protel extension). Reads the last SAVED state of the .kicad_pcb.",
|
||||
{
|
||||
outputPath: z.string().describe("Output Gerber file path"),
|
||||
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 the 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"),
|
||||
precision: z.number().optional().describe("Gerber coordinate precision: 5 or 6 (default 6)"),
|
||||
},
|
||||
async (args) => {
|
||||
logger.debug(`Exporting single Gerber to: ${args.outputPath}`);
|
||||
const result = await callKicadScript("export_gerber_single", args);
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: JSON.stringify(result),
|
||||
},
|
||||
],
|
||||
};
|
||||
},
|
||||
);
|
||||
|
||||
logger.info("Export tools registered");
|
||||
}
|
||||
|
||||
@@ -68,6 +68,7 @@ export const toolCategories: ToolCategory[] = [
|
||||
"export_pcb_pdf",
|
||||
"export_pcb_svg",
|
||||
"export_pcb_dxf",
|
||||
"export_gerber_single",
|
||||
"export_pdf",
|
||||
"export_svg",
|
||||
"export_3d",
|
||||
|
||||
Reference in New Issue
Block a user