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>
Swap Phase 3 (transport connect) before Phase 4 (warm-up) in
server.ts startup. Previously the transport was connected only after
warm-up completed (55-125s), which exceeded the MCP client's 30s
connection timeout on macOS cold-start.
PR #210 fixed the Python-side by daemon-threading warm_cache, but
the Node-side still blocked transport connect on warm-up completion.
Complements #210. Replaces the server.ts portion of #206.
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>
findPythonExecutable already auto-detects KiCAD's bundled python across versions
(10.0/9.0/…) and both Program Files and per-user %LOCALAPPDATA% installs, but the
spawn still defaulted PYTHONPATH to a hardcoded "C:/Program Files/KiCad/9.0/..."
path. So a KiCad 10 or per-user user whose python.exe was found correctly still
got the wrong PYTHONPATH unless they set it by hand — the exact manual fixup
people keep posting in #84.
Add deriveKiCadSitePackages(pythonExe): for a detected KiCAD python at
<root>/<version>/bin/python.exe it returns the matching site-packages
(<...>/bin/Lib/site-packages, or the older lib/python3/dist-packages layout),
verified to exist. Use it as the PYTHONPATH default. Precedence is unchanged at
the top: explicit PYTHONPATH env override still wins; the legacy 9.0 string
remains only as a last-resort fallback, so this can't regress below current
behavior.
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>
The background warm-cache change made list_symbols() guard cache writes with
self._cache_lock. _manager_for_fixture() builds the manager via __new__ (to skip
disk I/O to system libs), bypassing __init__ where the lock is created, so the 8
SPICE-parsing tests raised AttributeError. Set the lock in the fixture. The
string-aware parser itself is correct — all 8 pass once the lock exists.
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
The dehydration recovery test (test_auto_save_recovers_when_save_leaves_
board_dehydrated) builds a KiCADInterface via __new__, skipping __init__.
After #173 was rebased onto the #151/#172 auto-save guard, _auto_save_board
reads self._board_disk_signature (the content-hash conflict guard), which
__init__ normally sets to None. The fixture didn't, so the test tripped an
AttributeError before reaching the recovery logic it exercises.
Initialise _board_disk_signature = None in the _make_iface helper, matching
the pattern already used in test_auto_save_guard.py. Test-only change.
Co-authored-by: mixelpixx <11727006+mixelpixx@users.noreply.github.com>
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.