CONTRIBUTING.md mandates pathlib.Path over os.path (added for
cross-platform/Linux support); the rest of the codebase's newer code
already follows it. Converts the 19 new _handle_export_* handlers to
pathlib (exists/mkdir/iterdir/is_file, expanduser().resolve()) so this
feature's new code is compliant. Tests updated to patch pathlib.Path.
Scope is limited to the new export-handler block; the pre-existing
os.path usage elsewhere in kicad_interface.py/export.py is untouched
here and will be migrated in a dedicated refactor PR to keep that
sweep reviewable in isolation.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
New MCP tool `export_sch_python_bom` wrapping `kicad-cli sch export
python-bom`: emits the legacy intermediate XML netlist consumed by the
schematic editor's Python BOM scripts. Minimal option set (outputPath +
schematicPath only, matching the subcommand's --help). schematicPath
required and validated.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
New MCP tool `export_sch_hpgl` wrapping `kicad-cli sch export hpgl`: outputs
one plot per page into a directory. Exposes drawing-sheet override,
exclude-drawing-sheet, default-font, page selection, pen size, and the
origin/scale mode. schematicPath required; directory output uses outputDir.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
New MCP tool `export_sch_dxf` wrapping `kicad-cli sch export dxf`: outputs
one DXF per page into a directory. Exposes drawing-sheet override, theme,
B&W, exclude-drawing-sheet, default-font, and page selection.
schematicPath required; directory output uses outputDir.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
New MCP tool `export_sch_pdf` wrapping `kicad-cli sch export pdf`: exposes
the full option set (drawing-sheet override, theme, B&W,
exclude-drawing-sheet, default-font, the PDF property-popup /
hierarchical-link / metadata excludes, no-background-color, and page
selection). schematicPath is required and validated.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
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) <noreply@anthropic.com>
New MCP tool `export_3d_cli` wrapping the kicad-cli 3D subcommands. A
`format` enum {step,glb,stl,ply,brep,xao,vrml} selects the subcommand and
the handler forwards only flags valid for that subcommand: the shared
geometry/include set for step/glb/stl/ply/brep/xao, no-optimize-step for
STEP only, and units + models-dir/models-relative for VRML. Rich CLI
sibling of the existing export_3d / export_vrml (left untouched). Reads
the saved .kicad_pcb.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
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>
New MCP tool `export_pcb_dxf` wrapping `kicad-cli pcb export dxf`: exposes
the full layer-plot surface (layer/common-layer lists, refdes/value
exclusion, soldermask subtraction, use-contours, use-drill-origin,
border+title, output-units, the four DNP fab-layer modes, drill-shape, and
the single/multi output modes). Reads the saved .kicad_pcb.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
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) <noreply@anthropic.com>
New MCP tool `export_pcb_pdf` wrapping `kicad-cli pcb export pdf`: exposes
the full layer-plot surface (layer/common-layer lists, mirror,
refdes/value exclusion, border+title, soldermask subtraction, the four
DNP fab-layer modes, negative, B&W, theme, drill-shape, and the
single/separate/multipage output modes). Rich CLI sibling of the existing
SWIG export_pdf (left untouched). Reads the saved .kicad_pcb.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
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) <noreply@anthropic.com>
New MCP tool `export_ipcd356` wrapping `kicad-cli pcb export ipcd356`:
generates an IPC-D-356 bare-board electrical-test netlist for flying-probe
and bed-of-nails testers. Minimal option set (outputPath + boardPath only,
matching the subcommand's --help). Self-contained interface handler reading
the saved .kicad_pcb.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
New MCP tool `export_odb` wrapping `kicad-cli pcb export odb`: precision,
compression mode (zip/tgz/none), and units. Single ODB++ job archive for
CAM/MES/assembly. Self-contained interface handler reading the saved
.kicad_pcb.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
New MCP tool `export_ipc2581` wrapping `kicad-cli pcb export ipc2581`:
precision, compression, standard version, units, and the five
--bom-col-* field mappings (internal id, mfg P/N, mfg, distributor P/N,
distributor) that control the BOM part data embedded in the IPC-2581
file — directly useful for MES/assembly imports that need a real
internal P/N rather than the description. Self-contained interface
handler reading the saved .kicad_pcb.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
New MCP tool `export_gerbers` wrapping `kicad-cli pcb export gerbers`,
exposing the complete Plot-dialog option surface that the existing
SWIG-based export_gerber lacks: layer + common-layer lists, X2 on/off,
netlist attributes, soldermask subtraction, aperture macros, the three
DNP fab-layer modes, refdes/value exclusion, border+title, drill-file
origin, coordinate precision (5/6), Protel vs KiCad extensions, and
--board-plot-params to reuse the board's stored plot settings.
Implemented as a self-contained interface handler (_handle_export_gerbers)
that resolves the board path (param or current board) and shells out to
kicad-cli, mirroring the _handle_export_netlist pattern — no dependence
on a live SWIG board, since the KiCad IPC API exposes no plot/export
endpoints. Reads the saved .kicad_pcb on disk.
Wiring: dispatch map + src/tools/export.ts registration + export
category in registry.ts.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Adds batch authoring tools that collapse the dozens of round-trips needed to
stand up a schematic into a handful: batch_add_components,
batch_edit_schematic_components, replace_schematic_component,
batch_add_no_connects, batch_connect, and batch_add_and_connect (place a set of
parts and wire them in one call). These reuse the existing single-item handlers
internally, so behavior matches exactly.
- python/commands/schematic_batch.py: SchematicBatchCommands(iface)
- python/commands/schematic_text_utils.py: shared .kicad_sch text helpers
- src/tools/schematic-batch.ts + registry 'schematic_batch' category
- python/kicad_interface.py: import + instantiate + dispatch routes
- tests/test_schematic_batch.py: 13 unit tests
Note: schematic_text_utils.py is also shipped by the field-placement and
hierarchy PRs; if those merge first, drop the duplicate copy on rebase.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Adds field-placement tools:
- set_schematic_property_position / batch_set_schematic_property_positions:
move a symbol's Reference/Value field labels
- autoplace_schematic_fields: place every symbol's fields clear of its body
and nearby net labels (the #1 readability problem in generated schematics)
- check_schematic_layout: audit out-of-bounds / fields-in-body / duplicate
labels (note: overlaps upstream find_overlapping_elements etc. — reuse or
drop on request)
Generic .kicad_sch text helpers are factored into commands/schematic_text_utils.py
so the batch/hierarchy modules don't import from one another.
- python/commands/schematic_text_utils.py: shared text/S-expr helpers
- python/commands/schematic_field_layout.py: SchematicFieldLayoutCommands
- src/tools/schematic-layout.ts + registry 'schematic_layout' category
- python/kicad_interface.py: import + instantiate + dispatch routes
- tests/test_schematic_field_layout.py: 23 unit tests incl. end-to-end on real .kicad_sch
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Adds add_hierarchical_sheet (insert a sheet symbol referencing a child
.kicad_sch, with sheet_instances + fixed component instance paths) and
create_hierarchical_subsheet (create the child file + wire it into the parent
in one call). Upstream has add_sheet_pin / add_schematic_hierarchical_label
but no way to create a sheet or stand up a child sheet, so hierarchical
designs can't be built through the MCP server today.
- python/commands/schematic_hierarchy.py: SchematicHierarchyCommands
- src/tools/schematic-hierarchy.ts + registry 'schematic_hierarchy' category
- python/kicad_interface.py: import + instantiate + dispatch routes
- tests/test_schematic_hierarchy.py: 5 unit/integration tests on real .kicad_sch
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Adds list_symbol_pins and batch_list_symbol_pins: read a symbol's pin
number/name/type/local-position straight from the .kicad_sym libraries,
without placing it on a schematic. Fills a gap in library_symbol.py
(which can search/list symbols and read properties but not pins) and
complements get_schematic_pin_locations (placed-symbol coords only).
- python/commands/symbol_pins.py: SymbolPinCommands (stateless)
- src/tools/library-symbol.ts: tool wrappers; registry 'symbol_pins' category
- python/kicad_interface.py: import + instantiate + dispatch routes
- tests/test_symbol_pins.py: 12 unit tests (MagicMock loader; no system KiCad)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
When a project is opened for the first time (e.g. right after
create_project) the sym-lib-table may not exist on disk yet.
SymbolLibraryManager.__init__ succeeds but leaves self.libraries={}.
The original guard in use_project() was:
if self.library_manager.project_path == project_path:
return
Because the path already matched the newly-created manager, the
early-return fired and the manager was never rebuilt once the
sym-lib-table appeared. All subsequent list_symbols / search calls
returned nothing.
Fix: also require that at least one library was loaded before
treating the cache as valid.
Adds three unit tests that cover:
- rebuild triggered when project_path matches but libraries={}
- no spurious rebuild when libraries are already loaded
- rebuild on project_path change (existing behaviour)
The server wrote gigabytes to ~/.kicad-mcp/logs and ignored LOG_LEVEL. Three
root causes, all fixed here (the logging carve-out of #182):
- Python (kicad_interface.py): replace the unbounded FileHandler with a
RotatingFileHandler (10 MB x 3 backups, env-tunable via KICAD_MCP_LOG_MAX_BYTES
/ KICAD_MCP_LOG_BACKUP_COUNT); read the level from KICAD_MCP_LOG_LEVEL or
LOG_LEVEL (default INFO) instead of hardcoding DEBUG; mute the noisy
skip / skip.sexp.* loggers to WARNING unless KICAD_MCP_DEBUG_SKIP is set.
- TypeScript (config.ts): honor KICAD_MCP_LOG_LEVEL / LOG_LEVEL for the TS logger.
- TypeScript (logger.ts): size-cap the per-day log files with the same env knobs.
- Docs + a no-network test for the env helpers, skip muting, and that no
unbounded handler targets kicad_interface.log.
Verified: LOG_LEVEL is now applied, skip is muted, and the file rotates instead
of growing forever. Full suite unchanged from baseline.
The hierarchical-sheet rewrite from #182 is intentionally left out (stays as a
separate PR pending the #169/#170 design discussion).
Co-Authored-By: angelorodem <angelorodem@users.noreply.github.com>
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
KiCad 10 changed `kicad-cli pcb export svg` in three ways that broke
get_board_2d_view (reported with a verified fix in #209):
- `--output` is now a FILE path, not a directory (a dir fails with
"Failed to create file '<dir>'").
- `--mode-single` is required to merge layers into one SVG (the default
multi-file behavior is deprecated).
- exit code 2 is returned for the deprecation warning even on success.
Pass a file path to `--output` and add `--mode-single` (both also valid on
KiCad 8/9). Stop gating on the exit code — judge success by whether an SVG was
actually produced — so the exit-2 deprecation warning is no longer a false
failure. Add regression tests for the exit-2-is-success case and the command
shape (file output + --mode-single).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
bhoot found that download_cdfer 416-loops when a complete cdfer.sqlite3 already
exists in the cache (e.g. a prior run downloaded it but died before
conversion/cleanup): resuming a complete file sends Range: bytes=<size>- which
the server answers with HTTP 416, and raise_for_status treated that as a
retryable error, spinning until max_retries then failing.
Fix: HEAD once for Content-Length up front and short-circuit when the local file
already matches the full size; and in the loop, treat a 416 as "complete" when
the size matches (else drop the stale partial and restart fresh). Remove the now
-unused _head_last_modified helper (HEAD is done inline). Add a no-network test.
Verified live: happy path still downloads+converts 616k parts (~50s); a
pre-existing complete file now short-circuits in ~0.4s instead of looping.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Add optional `justify` property to `fieldPositions` entries in
`edit_schematic_component` and to `set_schematic_component_property`.
Changes:
- `python/kicad_interface.py`: new `_set_justify_on_property()` helper
that adds/replaces/removes the `(justify ...)` token inside a property's
`(effects ...)` block. Passing "center" (the KiCad default) removes the
directive entirely. Integrated into `_set_property_in_block()` (for the
`properties` dict path) and into the `field_positions` loop in
`_handle_edit_schematic_component()`. `_handle_set_schematic_component_property()`
now forwards `justify` from params through to the spec dict.
Also fixes pre-existing mypy type-ignore on `circle.radius` (kipy stub).
- `src/tools/schematic.ts`: extend the `fieldPositions` Zod schema to accept
`justify?: string | string[]` (array form normalised to a space-separated
string before the Python call). Add `justify?: string` to
`set_schematic_component_property`.
- `python/commands/routing.py`: fix pre-existing mypy error — annotate `ex`
and `ey` as `float` in `_point_to_segment_distance_nm`.
- `python/commands/pin_locator.py`: fix pre-existing mypy error — use explicit
`str()` cast on `pin_data["number"]` before `dict.get()` call.
- `tests/test_schematic_field_justify.py`: 14 unit + integration tests
covering add/replace/remove of the justify directive and backward
compatibility (calls without justify leave existing directives untouched).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
cacb27b omitted the closing parenthesis anchor in _extract_lib_property_positions, leaving lib_props empty and falling back to generic resistor positions.
- New angle parameter for component rotation (degrees, KiCad CCW-in-screen)
- New mirrorY parameter for horizontal symbol flipping (transistor orientation)
- Property positions (Reference, Value, Footprint) automatically rotated
- Property text effects preserved from library definitions
- Updates to add_schematic_component tool with new parameters
- Implements proper S-expression formatting for (mirror y) attribute
- Text angles and offsets derived from library properties for correct placement
People want to be able to pull the whole catalog, and prior downloads stalled or
repeated the same parts. Two fixes:
- Full catalog correctness: yaqwsx's cache.sqlite3 (the full ~10GB set) stores
category/manufacturer as IDs with no v_components view, so the convert left
those fields blank. Build an equivalent v_components join for yaqwsx-style
sources so the full catalog converts with category/subcategory/manufacturer
populated. Clarify in the tool schema that source="yaqwsx" = full catalog
(needs 7z) vs cdfer = in-stock subset.
- Resumable downloads: CDFER stream download now uses a read timeout and resumes
from the partial file via HTTP Range on interruption (up to 5 retries); the
yaqwsx curl calls use -C - / --retry. Addresses the stall/partial-download
complaints.
Adds a yaqwsx-schema conversion test.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Per review feedback: CDFER's upstream scraper pipeline has stalled for weeks
(broken cart API + a bug in their scraper), so a "fresh download" can still be
old data. Compute the catalog age from the source Last-Modified header, expose
catalog_age_days, and emit a stale=True + warning when older than 14 days that
points users to source='yaqwsx' (fresh, needs 7z) or source='official'. Surface
the warning in the MCP tool output.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The download_jlcpcb_database tool paged the community JLCSearch API with an
offset parameter, but that endpoint is a search front-end that ignores offset
and returns the same first 100 parts on every page, so a full catalog download
was impossible.
Add commands/jlcpcb_downloader.py with a layered strategy that reuses prebuilt
catalogs the whole ecosystem already trusts:
- CDFER single-file SQLite (primary; no 7z/zip, reliable on Windows)
- yaqwsx/jlcparts split 7z (fallback; only if a 7z CLI is present)
- official JLCPCB API (optional; cursor pagination, if credentials set)
Conversion reads CDFER's v_components view (or sniffs the largest table for
yaqwsx), C-prefixes integer lcsc, derives library_type from basic/preferred,
maps mfr->mfr_part, and normalizes price JSON to the manager's [{qty,price}]
shape. Rewire _handle_download_jlcpcb_database to use it (closing/reopening the
manager connection so the on-disk db can be rewritten on Windows). Remove the
broken offset loop from jlcsearch.py (client kept for interactive lookups).
Reduce download_jlcpcb.py to a thin CLI wrapper and update the TS tool schema.
Verified end-to-end against live CDFER: 616k parts downloaded + converted in
~40s, FTS search and price-break parsing correct. New unit tests cover the
conversion and source fall-through; no network in tests.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Three-phase MCP server startup: wait for Python READY handshake, send
_warmup command (pcbnew.BOARD() triggers wxApp init on macOS), connect
to MCP transport only after warm-up completes.
Also pre-populate symbol library cache during SymbolLibraryManager
init so the first search_symbols call doesn't parse 241 .kicad_sym
files from disk (30-120s). Both warm-up and cache population happen
before tools are registered with the MCP client.
Fixes#195
KiCAD nightly builds occasionally return a SwigPyObject from
pcbnew.LoadBoard, and SaveBoard can leave self.board with no method
dispatch as a side-effect of certain sequences (delete_trace + auto-save
is the one users have hit in the wild). Before this fix, open_project
would keep reporting "Opened project: foo.kicad_pcb" while every
subsequent board operation failed with AttributeError on
GetDesignSettings / GetBoardEdgesBoundingBox / GetCurrentViaSize, with
no path to recovery short of restarting the MCP server.
Add two helpers in KiCADInterface:
* _is_board_healthy(board=None) probes for stable BOARD methods
(GetDesignSettings, GetBoardEdgesBoundingBox, GetFileName) — these
are missing on a dehydrated SwigPyObject, so hasattr() catches the
state without segfaulting.
* _safe_load_board(path) wraps pcbnew.LoadBoard, checks health, and
on dehydration reloads the pcbnew module via importlib.reload and
retries once. Returns None when recovery is impossible so callers
surface real failure rather than fake success.
Wire the helpers in:
* handle_command's open_project / create_project path validates the
loaded board and either recovers (with a warnings[] entry) or
returns success=False with an explicit "restart the MCP server"
errorDetails — never claims success when the board is unusable.
* _auto_save_board now detects dehydration introduced by SaveBoard
itself and reloads from disk so the next command sees a usable
proxy. This is the post-delete_trace failure mode users hit.
* _handle_place_component, _handle_sync_schematic_to_board,
_handle_import_svg_logo and _handle_refill_zones all go through
_safe_load_board instead of bare LoadBoard, surfacing real errors
consistently.
Also fix two adjacent issues observed in the same incident:
* _handle_check_kicad_ui used to call manager.is_running() and
manager.get_process_info() separately, with different detection
methods. They could disagree, producing the confusing
running=True, processes=[] state users hit after manually
quitting KiCAD. processes is now the single source of truth and
running is derived from len().
* run_drc accepts a timeoutSec param (default 600s, clamped to
[10, 1800]) so callers with smaller MCP transport budgets can
bound the kicad-cli subprocess. Same timeout is applied to the
optional report-generation subprocess. Error message names the
actual timeout that fired.
Tests: tests/test_swig_dehydration.py adds 17 unit tests covering
detection, recovery, the open_project surfacing path, the auto-save
post-recovery path, the check_kicad_ui consistency, and the run_drc
timeout clamping. Full suite: same 12 pre-existing failures both
before and after this change, +17 new tests passing.
Note: the SWIG dehydration is fundamentally a pcbnew memory bug
exposed by repeated LoadBoard calls in a single Python process;
this PR is a defensive recovery layer, not a fix to the underlying
binding. Complementary to PR #151 (auto-save-guard), which expands
the LoadBoard call rate by refusing saves on external file change
and forcing re-open_project cycles.