feat: Add missing routing/component tools and fix SWIG/UUID bugs

New MCP tools added (TypeScript layer):
- Routing: delete_trace, query_traces, get_nets_list, modify_trace,
  create_netclass, route_differential_pair, refill_zones (with SWIG warning)
- Component: get_component_pads, get_component_list, get_pad_position,
  place_component_array, align_components, duplicate_component

Bug fixes:
- routing.py: Fix SwigPyObject UUID comparison (str() -> m_Uuid.AsString())
- routing.py: Fix SWIG iterator invalidation after board.Remove()
  by converting board.Tracks() to list() before iteration
- routing.py: Add board.SetModified() and clear Python refs after Remove()
  to prevent dangling SWIG pointers crashing subsequent calls
- routing.py: Wrap each track access in try/except in query_traces()
  to gracefully skip invalid track objects after bulk delete
- routing.py: Add missing return statement (mypy fix)
- library.py: Fix search_footprints param mapping search_term->pattern
- library.py: Fix fp.name -> fp.full_name field access
- library.py: Accept both 'pattern' and 'search_term' parameter names
- library.py: Add library filter support in search_footprints
- library.py: Fix loop variable shadowing Path object (mypy fix)
- design_rules.py: Add type annotation for violation_counts (mypy fix)

Contribution guidelines followed (CONTRIBUTING.md):
- black python/ applied (3 touched files pass without changes)
- mypy python/ passes with 0 errors on all changed files
- npx prettier --write applied to changed TypeScript files
- npm run build passes (tsc --noEmit: 0 errors)
- Commit messages follow feat:/fix: convention

Note on diff size: The large insertion/deletion count in the changed files
is due to black and prettier reformatting previously unformatted code
(missing trailing commas, quote style, line length). The actual logic
changes are limited to the 6 files listed above.

Note: refill_zones has known SWIG segfault risk (see KNOWN_ISSUES.md).
Prefer IPC backend (KiCAD open) or zone fill via KiCAD UI.
This commit is contained in:
Tom
2026-02-27 17:49:04 +01:00
parent b5a1483fc2
commit 2945b52eae
7 changed files with 1624 additions and 903 deletions

View File

@@ -2,6 +2,42 @@
All notable changes to the KiCAD MCP Server project are documented here.
## [2.2.0-alpha] - 2026-02-27
### New MCP Tools (TypeScript layer previously Python-only)
**Routing tools:**
- `delete_trace` - Delete traces by UUID, position or net name
- `query_traces` - Query/filter traces on the board
- `get_nets_list` - List all nets with net code and class
- `modify_trace` - Modify trace width or layer
- `create_netclass` - Create or update a net class
- `route_differential_pair` - Route a differential pair between two points
- `refill_zones` - Refill all copper zones ⚠️ SWIG segfault risk, prefer IPC/UI
**Component tools:**
- `get_component_pads` - Get all pad data for a component
- `get_component_list` - List all components on the board
- `get_pad_position` - Get absolute position of a specific pad
- `place_component_array` - Place components in a grid array
- `align_components` - Align components along an axis
- `duplicate_component` - Duplicate a component with offset
### Bug Fixes
- `routing.py`: Fix SwigPyObject UUID comparison (`str()``m_Uuid.AsString()`)
- `routing.py`: Fix SWIG iterator invalidation after `board.Remove()` by snapshotting `list(board.Tracks())`
- `routing.py`: Add `board.SetModified()` + `track = None` after `Remove()` to prevent dangling SWIG pointer crashes
- `routing.py`: Per-track `try/except` in `query_traces()` to skip invalid objects after bulk delete
- `routing.py`: Add missing return statement (mypy)
- `library.py`: Fix `search_footprints` parameter mapping (`search_term``pattern`)
- `library.py`: Fix field access (`fp.name``fp.full_name`)
- `library.py`: Accept both `pattern` and `search_term` parameter names
- `library.py`: Fix loop variable shadowing `Path` object (mypy)
- `design_rules.py`: Add type annotation for `violation_counts` (mypy)
---
## [2.1.0-alpha] - 2026-01-10
### Phase 1: Intelligent Schematic Wiring System - Core Infrastructure

View File

@@ -7,7 +7,8 @@ import pcbnew
import logging
from typing import Dict, Any, Optional, List, Tuple
logger = logging.getLogger('kicad_interface')
logger = logging.getLogger("kicad_interface")
class DesignRuleCommands:
"""Handles design rule checking and configuration"""
@@ -23,7 +24,7 @@ class DesignRuleCommands:
return {
"success": False,
"message": "No board is loaded",
"errorDetails": "Load or create a board first"
"errorDetails": "Load or create a board first",
}
design_settings = self.board.GetDesignSettings()
@@ -57,9 +58,13 @@ class DesignRuleCommands:
# Set micro via settings (use properties - methods removed in KiCAD 9.0)
if "microViaDiameter" in params:
design_settings.m_MicroViasMinSize = int(params["microViaDiameter"] * scale)
design_settings.m_MicroViasMinSize = int(
params["microViaDiameter"] * scale
)
if "microViaDrill" in params:
design_settings.m_MicroViasMinDrill = int(params["microViaDrill"] * scale)
design_settings.m_MicroViasMinDrill = int(
params["microViaDrill"] * scale
)
# Set minimum values
if "minTrackWidth" in params:
@@ -72,13 +77,19 @@ class DesignRuleCommands:
design_settings.m_MinThroughDrill = int(params["minViaDrill"] * scale)
if "minMicroViaDiameter" in params:
design_settings.m_MicroViasMinSize = int(params["minMicroViaDiameter"] * scale)
design_settings.m_MicroViasMinSize = int(
params["minMicroViaDiameter"] * scale
)
if "minMicroViaDrill" in params:
design_settings.m_MicroViasMinDrill = int(params["minMicroViaDrill"] * scale)
design_settings.m_MicroViasMinDrill = int(
params["minMicroViaDrill"] * scale
)
# KiCAD 9.0: m_MinHoleDiameter removed - use m_MinThroughDrill
if "minHoleDiameter" in params:
design_settings.m_MinThroughDrill = int(params["minHoleDiameter"] * scale)
design_settings.m_MinThroughDrill = int(
params["minHoleDiameter"] * scale
)
# KiCAD 9.0: Added hole clearance settings
if "holeClearance" in params:
@@ -102,13 +113,13 @@ class DesignRuleCommands:
"minMicroViaDrill": design_settings.m_MicroViasMinDrill / scale,
"holeClearance": design_settings.m_HoleClearance / scale,
"holeToHoleMin": design_settings.m_HoleToHoleMin / scale,
"viasMinAnnularWidth": design_settings.m_ViasMinAnnularWidth / scale
"viasMinAnnularWidth": design_settings.m_ViasMinAnnularWidth / scale,
}
return {
"success": True,
"message": "Updated design rules",
"rules": response_rules
"rules": response_rules,
}
except Exception as e:
@@ -116,7 +127,7 @@ class DesignRuleCommands:
return {
"success": False,
"message": "Failed to set design rules",
"errorDetails": str(e)
"errorDetails": str(e),
}
def get_design_rules(self, params: Dict[str, Any]) -> Dict[str, Any]:
@@ -126,7 +137,7 @@ class DesignRuleCommands:
return {
"success": False,
"message": "No board is loaded",
"errorDetails": "Load or create a board first"
"errorDetails": "Load or create a board first",
}
design_settings = self.board.GetDesignSettings()
@@ -138,42 +149,34 @@ class DesignRuleCommands:
"clearance": design_settings.m_MinClearance / scale,
"trackWidth": design_settings.GetCurrentTrackWidth() / scale,
"minTrackWidth": design_settings.m_TrackMinWidth / scale,
# Via settings (current values from methods)
"viaDiameter": design_settings.GetCurrentViaSize() / scale,
"viaDrill": design_settings.GetCurrentViaDrill() / scale,
# Via minimum values
"minViaDiameter": design_settings.m_ViasMinSize / scale,
"viasMinAnnularWidth": design_settings.m_ViasMinAnnularWidth / scale,
# Micro via settings
"microViaDiameter": design_settings.m_MicroViasMinSize / scale,
"microViaDrill": design_settings.m_MicroViasMinDrill / scale,
"minMicroViaDiameter": design_settings.m_MicroViasMinSize / scale,
"minMicroViaDrill": design_settings.m_MicroViasMinDrill / scale,
# KiCAD 9.0: Hole and drill settings (replaces removed m_ViasMinDrill and m_MinHoleDiameter)
"minThroughDrill": design_settings.m_MinThroughDrill / scale,
"holeClearance": design_settings.m_HoleClearance / scale,
"holeToHoleMin": design_settings.m_HoleToHoleMin / scale,
# Other constraints
"copperEdgeClearance": design_settings.m_CopperEdgeClearance / scale,
"silkClearance": design_settings.m_SilkClearance / scale,
}
return {
"success": True,
"rules": rules
}
return {"success": True, "rules": rules}
except Exception as e:
logger.error(f"Error getting design rules: {str(e)}")
return {
"success": False,
"message": "Failed to get design rules",
"errorDetails": str(e)
"errorDetails": str(e),
}
def run_drc(self, params: Dict[str, Any]) -> Dict[str, Any]:
@@ -189,7 +192,7 @@ class DesignRuleCommands:
return {
"success": False,
"message": "No board is loaded",
"errorDetails": "Load or create a board first"
"errorDetails": "Load or create a board first",
}
report_path = params.get("reportPath")
@@ -200,7 +203,7 @@ class DesignRuleCommands:
return {
"success": False,
"message": "Board file not found",
"errorDetails": "Cannot run DRC without a saved board file"
"errorDetails": "Cannot run DRC without a saved board file",
}
# Find kicad-cli executable
@@ -209,23 +212,28 @@ class DesignRuleCommands:
return {
"success": False,
"message": "kicad-cli not found",
"errorDetails": "KiCAD CLI tool not found in system. Install KiCAD 8.0+ or set PATH."
"errorDetails": "KiCAD CLI tool not found in system. Install KiCAD 8.0+ or set PATH.",
}
# Create temporary JSON output file
with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False) as tmp:
with tempfile.NamedTemporaryFile(
mode="w", suffix=".json", delete=False
) as tmp:
json_output = tmp.name
try:
# Build command
cmd = [
kicad_cli,
'pcb',
'drc',
'--format', 'json',
'--output', json_output,
'--units', 'mm',
board_file
"pcb",
"drc",
"--format",
"json",
"--output",
json_output,
"--units",
"mm",
board_file,
]
logger.info(f"Running DRC command: {' '.join(cmd)}")
@@ -235,7 +243,7 @@ class DesignRuleCommands:
cmd,
capture_output=True,
text=True,
timeout=600 # 10 minute timeout for large boards (21MB PCB needs time)
timeout=600, # 10 minute timeout for large boards (21MB PCB needs time)
)
if result.returncode != 0:
@@ -243,32 +251,34 @@ class DesignRuleCommands:
return {
"success": False,
"message": "DRC command failed",
"errorDetails": result.stderr
"errorDetails": result.stderr,
}
# Read JSON output
with open(json_output, 'r', encoding='utf-8') as f:
with open(json_output, "r", encoding="utf-8") as f:
drc_data = json.load(f)
# Parse violations from kicad-cli output
violations = []
violation_counts = {}
violation_counts: dict[str, int] = {}
severity_counts = {"error": 0, "warning": 0, "info": 0}
for violation in drc_data.get('violations', []):
for violation in drc_data.get("violations", []):
vtype = violation.get("type", "unknown")
vseverity = violation.get("severity", "error")
violations.append({
"type": vtype,
"severity": vseverity,
"message": violation.get("description", ""),
"location": {
"x": violation.get("x", 0),
"y": violation.get("y", 0),
"unit": "mm"
violations.append(
{
"type": vtype,
"severity": vseverity,
"message": violation.get("description", ""),
"location": {
"x": violation.get("x", 0),
"y": violation.get("y", 0),
"unit": "mm",
},
}
})
)
# Count violations by type
violation_counts[vtype] = violation_counts.get(vtype, 0) + 1
@@ -280,30 +290,39 @@ class DesignRuleCommands:
# Determine where to save the violations file
board_dir = os.path.dirname(board_file)
board_name = os.path.splitext(os.path.basename(board_file))[0]
violations_file = os.path.join(board_dir, f"{board_name}_drc_violations.json")
violations_file = os.path.join(
board_dir, f"{board_name}_drc_violations.json"
)
# Always save violations to JSON file (for large result sets)
with open(violations_file, 'w', encoding='utf-8') as f:
json.dump({
"board": board_file,
"timestamp": drc_data.get("date", "unknown"),
"total_violations": len(violations),
"violation_counts": violation_counts,
"severity_counts": severity_counts,
"violations": violations
}, f, indent=2)
with open(violations_file, "w", encoding="utf-8") as f:
json.dump(
{
"board": board_file,
"timestamp": drc_data.get("date", "unknown"),
"total_violations": len(violations),
"violation_counts": violation_counts,
"severity_counts": severity_counts,
"violations": violations,
},
f,
indent=2,
)
# Save text report if requested
if report_path:
report_path = os.path.abspath(os.path.expanduser(report_path))
cmd_report = [
kicad_cli,
'pcb',
'drc',
'--format', 'report',
'--output', report_path,
'--units', 'mm',
board_file
"pcb",
"drc",
"--format",
"report",
"--output",
report_path,
"--units",
"mm",
board_file,
]
subprocess.run(cmd_report, capture_output=True, timeout=600)
@@ -314,10 +333,10 @@ class DesignRuleCommands:
"summary": {
"total": len(violations),
"by_severity": severity_counts,
"by_type": violation_counts
"by_type": violation_counts,
},
"violationsFile": violations_file,
"reportPath": report_path if report_path else None
"reportPath": report_path if report_path else None,
}
finally:
@@ -330,14 +349,14 @@ class DesignRuleCommands:
return {
"success": False,
"message": "DRC command timed out",
"errorDetails": "Command took longer than 600 seconds (10 minutes)"
"errorDetails": "Command took longer than 600 seconds (10 minutes)",
}
except Exception as e:
logger.error(f"Error running DRC: {str(e)}")
return {
"success": False,
"message": "Failed to run DRC",
"errorDetails": str(e)
"errorDetails": str(e),
}
def _find_kicad_cli(self) -> Optional[str]:
@@ -399,7 +418,7 @@ class DesignRuleCommands:
return {
"success": False,
"message": "No board is loaded",
"errorDetails": "Load or create a board first"
"errorDetails": "Load or create a board first",
}
severity = params.get("severity", "all")
@@ -416,25 +435,27 @@ class DesignRuleCommands:
return {
"success": False,
"message": "Violations file not found",
"errorDetails": "run_drc did not create violations file"
"errorDetails": "run_drc did not create violations file",
}
# Load violations from file
with open(violations_file, 'r', encoding='utf-8') as f:
with open(violations_file, "r", encoding="utf-8") as f:
data = json.load(f)
all_violations = data.get("violations", [])
# Filter by severity if specified
if severity != "all":
filtered_violations = [v for v in all_violations if v.get("severity") == severity]
filtered_violations = [
v for v in all_violations if v.get("severity") == severity
]
else:
filtered_violations = all_violations
return {
"success": True,
"violations": filtered_violations,
"violationsFile": violations_file # Include file path for reference
"violationsFile": violations_file, # Include file path for reference
}
except Exception as e:
@@ -442,5 +463,5 @@ class DesignRuleCommands:
return {
"success": False,
"message": "Failed to get DRC violations",
"errorDetails": str(e)
"errorDetails": str(e),
}

View File

@@ -12,7 +12,7 @@ from pathlib import Path
from typing import Dict, List, Optional, Tuple
import glob
logger = logging.getLogger('kicad_interface')
logger = logging.getLogger("kicad_interface")
class LibraryManager:
@@ -85,7 +85,7 @@ class LibraryManager:
)
"""
try:
with open(table_path, 'r') as f:
with open(table_path, "r") as f:
content = f.read()
# Simple regex-based parser for lib entries
@@ -103,7 +103,9 @@ class LibraryManager:
self.libraries[nickname] = resolved_uri
logger.debug(f" Found library: {nickname} -> {resolved_uri}")
else:
logger.warning(f" Could not resolve URI for library {nickname}: {uri}")
logger.warning(
f" Could not resolve URI for library {nickname}: {uri}"
)
except Exception as e:
logger.error(f"Error parsing fp-lib-table at {table_path}: {e}")
@@ -124,23 +126,23 @@ class LibraryManager:
# Common KiCAD environment variables
env_vars = {
'KICAD9_FOOTPRINT_DIR': self._find_kicad_footprint_dir(),
'KICAD8_FOOTPRINT_DIR': self._find_kicad_footprint_dir(),
'KICAD_FOOTPRINT_DIR': self._find_kicad_footprint_dir(),
'KISYSMOD': self._find_kicad_footprint_dir(),
'KICAD9_3RD_PARTY': self._find_kicad_3rdparty_dir(),
'KICAD8_3RD_PARTY': self._find_kicad_3rdparty_dir(),
"KICAD9_FOOTPRINT_DIR": self._find_kicad_footprint_dir(),
"KICAD8_FOOTPRINT_DIR": self._find_kicad_footprint_dir(),
"KICAD_FOOTPRINT_DIR": self._find_kicad_footprint_dir(),
"KISYSMOD": self._find_kicad_footprint_dir(),
"KICAD9_3RD_PARTY": self._find_kicad_3rdparty_dir(),
"KICAD8_3RD_PARTY": self._find_kicad_3rdparty_dir(),
}
# Project directory
if self.project_path:
env_vars['KIPRJMOD'] = str(self.project_path)
env_vars["KIPRJMOD"] = str(self.project_path)
# Replace environment variables
for var, value in env_vars.items():
if value:
resolved = resolved.replace(f'${{{var}}}', value)
resolved = resolved.replace(f'${var}', value)
resolved = resolved.replace(f"${{{var}}}", value)
resolved = resolved.replace(f"${var}", value)
# Expand ~ to home directory
resolved = os.path.expanduser(resolved)
@@ -167,10 +169,10 @@ class LibraryManager:
]
# Also check environment variable
if 'KICAD9_FOOTPRINT_DIR' in os.environ:
possible_paths.insert(0, os.environ['KICAD9_FOOTPRINT_DIR'])
if 'KICAD8_FOOTPRINT_DIR' in os.environ:
possible_paths.insert(0, os.environ['KICAD8_FOOTPRINT_DIR'])
if "KICAD9_FOOTPRINT_DIR" in os.environ:
possible_paths.insert(0, os.environ["KICAD9_FOOTPRINT_DIR"])
if "KICAD8_FOOTPRINT_DIR" in os.environ:
possible_paths.insert(0, os.environ["KICAD8_FOOTPRINT_DIR"])
for path in possible_paths:
if os.path.isdir(path):
@@ -190,26 +192,36 @@ class LibraryManager:
import json
# 1. Check shell environment variable first
if 'KICAD9_3RD_PARTY' in os.environ:
path = os.environ['KICAD9_3RD_PARTY']
if "KICAD9_3RD_PARTY" in os.environ:
path = os.environ["KICAD9_3RD_PARTY"]
if os.path.isdir(path):
return path
# 2. Check kicad_common.json for user-defined variables
kicad_common_paths = [
Path.home() / "Library" / "Preferences" / "kicad" / "9.0" / "kicad_common.json", # macOS
Path.home()
/ "Library"
/ "Preferences"
/ "kicad"
/ "9.0"
/ "kicad_common.json", # macOS
Path.home() / ".config" / "kicad" / "9.0" / "kicad_common.json", # Linux
Path.home() / "AppData" / "Roaming" / "kicad" / "9.0" / "kicad_common.json", # Windows
Path.home()
/ "AppData"
/ "Roaming"
/ "kicad"
/ "9.0"
/ "kicad_common.json", # Windows
]
for config_path in kicad_common_paths:
if config_path.exists():
try:
with open(config_path, 'r') as f:
with open(config_path, "r") as f:
config = json.load(f)
env_vars = config.get('environment', {}).get('vars', {})
if env_vars and 'KICAD9_3RD_PARTY' in env_vars:
path = env_vars['KICAD9_3RD_PARTY']
env_vars = config.get("environment", {}).get("vars", {})
if env_vars and "KICAD9_3RD_PARTY" in env_vars:
path = env_vars["KICAD9_3RD_PARTY"]
if os.path.isdir(path):
return path
except (json.JSONDecodeError, KeyError, TypeError):
@@ -231,10 +243,10 @@ class LibraryManager:
Path.home() / "Documents" / "KiCad" / version / "3rdparty",
]
for path in possible_paths:
if path.exists():
logger.info(f"Found KiCad 3rd party directory: {path}")
return str(path)
for candidate in possible_paths:
if candidate.exists():
logger.info(f"Found KiCad 3rd party directory: {candidate}")
return str(candidate)
logger.warning("Could not find KiCad 3rd party directory")
return None
@@ -325,7 +337,9 @@ class LibraryManager:
for library_nickname, library_path in self.libraries.items():
fp_file = Path(library_path) / f"{footprint_name}.kicad_mod"
if fp_file.exists():
logger.info(f"Found footprint {footprint_name} in library {library_nickname}")
logger.info(
f"Found footprint {footprint_name} in library {library_nickname}"
)
return (library_path, footprint_name)
logger.warning(f"Footprint not found in any library: {footprint_name}")
@@ -354,18 +368,22 @@ class LibraryManager:
for footprint in footprints:
if regex.search(footprint.lower()):
results.append({
'library': library_nickname,
'footprint': footprint,
'full_name': f"{library_nickname}:{footprint}"
})
results.append(
{
"library": library_nickname,
"footprint": footprint,
"full_name": f"{library_nickname}:{footprint}",
}
)
if len(results) >= limit:
return results
return results
def get_footprint_info(self, library_nickname: str, footprint_name: str) -> Optional[Dict[str, str]]:
def get_footprint_info(
self, library_nickname: str, footprint_name: str
) -> Optional[Dict[str, str]]:
"""
Get information about a specific footprint
@@ -385,11 +403,11 @@ class LibraryManager:
return None
return {
'library': library_nickname,
'footprint': footprint_name,
'full_name': f"{library_nickname}:{footprint_name}",
'path': str(fp_file),
'library_path': library_path
"library": library_nickname,
"footprint": footprint_name,
"full_name": f"{library_nickname}:{footprint_name}",
"path": str(fp_file),
"library_path": library_path,
}
@@ -404,39 +422,48 @@ class LibraryCommands:
"""List all available footprint libraries"""
try:
libraries = self.library_manager.list_libraries()
return {
"success": True,
"libraries": libraries,
"count": len(libraries)
}
return {"success": True, "libraries": libraries, "count": len(libraries)}
except Exception as e:
logger.error(f"Error listing libraries: {e}")
return {
"success": False,
"message": "Failed to list libraries",
"errorDetails": str(e)
"errorDetails": str(e),
}
def search_footprints(self, params: Dict) -> Dict:
"""Search for footprints by pattern"""
try:
pattern = params.get("pattern", "*")
# Support both 'pattern' and 'search_term' parameter names
pattern = params.get("pattern") or params.get("search_term", "*")
limit = params.get("limit", 20)
library_filter = params.get("library")
results = self.library_manager.search_footprints(pattern, limit)
results = self.library_manager.search_footprints(
pattern, limit * 10 if library_filter else limit
)
# Filter by library if specified
if library_filter:
results = [
r
for r in results
if r.get("library", "").lower() == library_filter.lower()
]
results = results[:limit]
return {
"success": True,
"footprints": results,
"count": len(results),
"pattern": pattern
"pattern": pattern,
}
except Exception as e:
logger.error(f"Error searching footprints: {e}")
return {
"success": False,
"message": "Failed to search footprints",
"errorDetails": str(e)
"errorDetails": str(e),
}
def list_library_footprints(self, params: Dict) -> Dict:
@@ -444,10 +471,7 @@ class LibraryCommands:
try:
library = params.get("library")
if not library:
return {
"success": False,
"message": "Missing library parameter"
}
return {"success": False, "message": "Missing library parameter"}
footprints = self.library_manager.list_footprints(library)
@@ -455,14 +479,14 @@ class LibraryCommands:
"success": True,
"library": library,
"footprints": footprints,
"count": len(footprints)
"count": len(footprints),
}
except Exception as e:
logger.error(f"Error listing library footprints: {e}")
return {
"success": False,
"message": "Failed to list library footprints",
"errorDetails": str(e)
"errorDetails": str(e),
}
def get_footprint_info(self, params: Dict) -> Dict:
@@ -470,10 +494,7 @@ class LibraryCommands:
try:
footprint_spec = params.get("footprint")
if not footprint_spec:
return {
"success": False,
"message": "Missing footprint parameter"
}
return {"success": False, "message": "Missing footprint parameter"}
# Try to find the footprint
result = self.library_manager.find_footprint(footprint_spec)
@@ -491,17 +512,14 @@ class LibraryCommands:
"library": library_nickname,
"footprint": footprint_name,
"full_name": f"{library_nickname}:{footprint_name}",
"library_path": library_path
"library_path": library_path,
}
return {
"success": True,
"footprint_info": info
}
return {"success": True, "footprint_info": info}
else:
return {
"success": False,
"message": f"Footprint not found: {footprint_spec}"
"message": f"Footprint not found: {footprint_spec}",
}
except Exception as e:
@@ -509,5 +527,5 @@ class LibraryCommands:
return {
"success": False,
"message": "Failed to get footprint info",
"errorDetails": str(e)
"errorDetails": str(e),
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,291 +1,644 @@
/**
* Component management tools for KiCAD MCP server
*/
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { z } from 'zod';
import { logger } from '../logger.js';
// Command function type for KiCAD script calls
type CommandFunction = (command: string, params: Record<string, unknown>) => Promise<any>;
/**
* Register component management tools with the MCP server
*
* @param server MCP server instance
* @param callKicadScript Function to call KiCAD script commands
*/
export function registerComponentTools(server: McpServer, callKicadScript: CommandFunction): void {
logger.info('Registering component management tools');
// ------------------------------------------------------
// Place Component Tool
// ------------------------------------------------------
server.tool(
"place_component",
{
componentId: z.string().describe("Identifier for the component to place (e.g., 'R_0603_10k')"),
position: z.object({
x: z.number().describe("X coordinate"),
y: z.number().describe("Y coordinate"),
unit: z.enum(["mm", "inch"]).describe("Unit of measurement")
}).describe("Position coordinates and unit"),
reference: z.string().optional().describe("Optional desired reference (e.g., 'R5')"),
value: z.string().optional().describe("Optional component value (e.g., '10k')"),
footprint: z.string().optional().describe("Optional specific footprint name"),
rotation: z.number().optional().describe("Optional rotation in degrees"),
layer: z.string().optional().describe("Optional layer (e.g., 'F.Cu', 'B.SilkS')")
},
async ({ componentId, position, reference, value, footprint, rotation, layer }) => {
logger.debug(`Placing component: ${componentId} at ${position.x},${position.y} ${position.unit}`);
const result = await callKicadScript("place_component", {
componentId,
position,
reference,
value,
footprint,
rotation,
layer
});
return {
content: [{
type: "text",
text: JSON.stringify(result)
}]
};
}
);
// ------------------------------------------------------
// Move Component Tool
// ------------------------------------------------------
server.tool(
"move_component",
{
reference: z.string().describe("Reference designator of the component (e.g., 'R5')"),
position: z.object({
x: z.number().describe("X coordinate"),
y: z.number().describe("Y coordinate"),
unit: z.enum(["mm", "inch"]).describe("Unit of measurement")
}).describe("New position coordinates and unit"),
rotation: z.number().optional().describe("Optional new rotation in degrees")
},
async ({ reference, position, rotation }) => {
logger.debug(`Moving component: ${reference} to ${position.x},${position.y} ${position.unit}`);
const result = await callKicadScript("move_component", {
reference,
position,
rotation
});
return {
content: [{
type: "text",
text: JSON.stringify(result)
}]
};
}
);
// ------------------------------------------------------
// Rotate Component Tool
// ------------------------------------------------------
server.tool(
"rotate_component",
{
reference: z.string().describe("Reference designator of the component (e.g., 'R5')"),
angle: z.number().describe("Rotation angle in degrees (absolute, not relative)")
},
async ({ reference, angle }) => {
logger.debug(`Rotating component: ${reference} to ${angle} degrees`);
const result = await callKicadScript("rotate_component", {
reference,
angle
});
return {
content: [{
type: "text",
text: JSON.stringify(result)
}]
};
}
);
// ------------------------------------------------------
// Delete Component Tool
// ------------------------------------------------------
server.tool(
"delete_component",
{
reference: z.string().describe("Reference designator of the component to delete (e.g., 'R5')")
},
async ({ reference }) => {
logger.debug(`Deleting component: ${reference}`);
const result = await callKicadScript("delete_component", { reference });
return {
content: [{
type: "text",
text: JSON.stringify(result)
}]
};
}
);
// ------------------------------------------------------
// Edit Component Properties Tool
// ------------------------------------------------------
server.tool(
"edit_component",
{
reference: z.string().describe("Reference designator of the component (e.g., 'R5')"),
newReference: z.string().optional().describe("Optional new reference designator"),
value: z.string().optional().describe("Optional new component value"),
footprint: z.string().optional().describe("Optional new footprint")
},
async ({ reference, newReference, value, footprint }) => {
logger.debug(`Editing component: ${reference}`);
const result = await callKicadScript("edit_component", {
reference,
newReference,
value,
footprint
});
return {
content: [{
type: "text",
text: JSON.stringify(result)
}]
};
}
);
// ------------------------------------------------------
// Find Component Tool
// ------------------------------------------------------
server.tool(
"find_component",
{
reference: z.string().optional().describe("Reference designator to search for"),
value: z.string().optional().describe("Component value to search for")
},
async ({ reference, value }) => {
logger.debug(`Finding component with ${reference ? `reference: ${reference}` : `value: ${value}`}`);
const result = await callKicadScript("find_component", { reference, value });
return {
content: [{
type: "text",
text: JSON.stringify(result)
}]
};
}
);
// ------------------------------------------------------
// Get Component Properties Tool
// ------------------------------------------------------
server.tool(
"get_component_properties",
{
reference: z.string().describe("Reference designator of the component (e.g., 'R5')")
},
async ({ reference }) => {
logger.debug(`Getting properties for component: ${reference}`);
const result = await callKicadScript("get_component_properties", { reference });
return {
content: [{
type: "text",
text: JSON.stringify(result)
}]
};
}
);
// ------------------------------------------------------
// Add Component Annotation Tool
// ------------------------------------------------------
server.tool(
"add_component_annotation",
{
reference: z.string().describe("Reference designator of the component (e.g., 'R5')"),
annotation: z.string().describe("Annotation or comment text to add"),
visible: z.boolean().optional().describe("Whether the annotation should be visible on the PCB")
},
async ({ reference, annotation, visible }) => {
logger.debug(`Adding annotation to component: ${reference}`);
const result = await callKicadScript("add_component_annotation", {
reference,
annotation,
visible
});
return {
content: [{
type: "text",
text: JSON.stringify(result)
}]
};
}
);
// ------------------------------------------------------
// Group Components Tool
// ------------------------------------------------------
server.tool(
"group_components",
{
references: z.array(z.string()).describe("Reference designators of components to group"),
groupName: z.string().describe("Name for the component group")
},
async ({ references, groupName }) => {
logger.debug(`Grouping components: ${references.join(', ')} as ${groupName}`);
const result = await callKicadScript("group_components", {
references,
groupName
});
return {
content: [{
type: "text",
text: JSON.stringify(result)
}]
};
}
);
// ------------------------------------------------------
// Replace Component Tool
// ------------------------------------------------------
server.tool(
"replace_component",
{
reference: z.string().describe("Reference designator of the component to replace"),
newComponentId: z.string().describe("ID of the new component to use"),
newFootprint: z.string().optional().describe("Optional new footprint"),
newValue: z.string().optional().describe("Optional new component value")
},
async ({ reference, newComponentId, newFootprint, newValue }) => {
logger.debug(`Replacing component: ${reference} with ${newComponentId}`);
const result = await callKicadScript("replace_component", {
reference,
newComponentId,
newFootprint,
newValue
});
return {
content: [{
type: "text",
text: JSON.stringify(result)
}]
};
}
);
logger.info('Component management tools registered');
}
/**
* Component management tools for KiCAD MCP server
*/
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";
import { logger } from "../logger.js";
// Command function type for KiCAD script calls
type CommandFunction = (
command: string,
params: Record<string, unknown>,
) => Promise<any>;
/**
* Register component management tools with the MCP server
*
* @param server MCP server instance
* @param callKicadScript Function to call KiCAD script commands
*/
export function registerComponentTools(
server: McpServer,
callKicadScript: CommandFunction,
): void {
logger.info("Registering component management tools");
// ------------------------------------------------------
// Place Component Tool
// ------------------------------------------------------
server.tool(
"place_component",
{
componentId: z
.string()
.describe("Identifier for the component to place (e.g., 'R_0603_10k')"),
position: z
.object({
x: z.number().describe("X coordinate"),
y: z.number().describe("Y coordinate"),
unit: z.enum(["mm", "inch"]).describe("Unit of measurement"),
})
.describe("Position coordinates and unit"),
reference: z
.string()
.optional()
.describe("Optional desired reference (e.g., 'R5')"),
value: z
.string()
.optional()
.describe("Optional component value (e.g., '10k')"),
footprint: z
.string()
.optional()
.describe("Optional specific footprint name"),
rotation: z.number().optional().describe("Optional rotation in degrees"),
layer: z
.string()
.optional()
.describe("Optional layer (e.g., 'F.Cu', 'B.SilkS')"),
},
async ({
componentId,
position,
reference,
value,
footprint,
rotation,
layer,
}) => {
logger.debug(
`Placing component: ${componentId} at ${position.x},${position.y} ${position.unit}`,
);
const result = await callKicadScript("place_component", {
componentId,
position,
reference,
value,
footprint,
rotation,
layer,
});
return {
content: [
{
type: "text",
text: JSON.stringify(result),
},
],
};
},
);
// ------------------------------------------------------
// Move Component Tool
// ------------------------------------------------------
server.tool(
"move_component",
{
reference: z
.string()
.describe("Reference designator of the component (e.g., 'R5')"),
position: z
.object({
x: z.number().describe("X coordinate"),
y: z.number().describe("Y coordinate"),
unit: z.enum(["mm", "inch"]).describe("Unit of measurement"),
})
.describe("New position coordinates and unit"),
rotation: z
.number()
.optional()
.describe("Optional new rotation in degrees"),
},
async ({ reference, position, rotation }) => {
logger.debug(
`Moving component: ${reference} to ${position.x},${position.y} ${position.unit}`,
);
const result = await callKicadScript("move_component", {
reference,
position,
rotation,
});
return {
content: [
{
type: "text",
text: JSON.stringify(result),
},
],
};
},
);
// ------------------------------------------------------
// Rotate Component Tool
// ------------------------------------------------------
server.tool(
"rotate_component",
{
reference: z
.string()
.describe("Reference designator of the component (e.g., 'R5')"),
angle: z
.number()
.describe("Rotation angle in degrees (absolute, not relative)"),
},
async ({ reference, angle }) => {
logger.debug(`Rotating component: ${reference} to ${angle} degrees`);
const result = await callKicadScript("rotate_component", {
reference,
angle,
});
return {
content: [
{
type: "text",
text: JSON.stringify(result),
},
],
};
},
);
// ------------------------------------------------------
// Delete Component Tool
// ------------------------------------------------------
server.tool(
"delete_component",
{
reference: z
.string()
.describe(
"Reference designator of the component to delete (e.g., 'R5')",
),
},
async ({ reference }) => {
logger.debug(`Deleting component: ${reference}`);
const result = await callKicadScript("delete_component", { reference });
return {
content: [
{
type: "text",
text: JSON.stringify(result),
},
],
};
},
);
// ------------------------------------------------------
// Edit Component Properties Tool
// ------------------------------------------------------
server.tool(
"edit_component",
{
reference: z
.string()
.describe("Reference designator of the component (e.g., 'R5')"),
newReference: z
.string()
.optional()
.describe("Optional new reference designator"),
value: z.string().optional().describe("Optional new component value"),
footprint: z.string().optional().describe("Optional new footprint"),
},
async ({ reference, newReference, value, footprint }) => {
logger.debug(`Editing component: ${reference}`);
const result = await callKicadScript("edit_component", {
reference,
newReference,
value,
footprint,
});
return {
content: [
{
type: "text",
text: JSON.stringify(result),
},
],
};
},
);
// ------------------------------------------------------
// Find Component Tool
// ------------------------------------------------------
server.tool(
"find_component",
{
reference: z
.string()
.optional()
.describe("Reference designator to search for"),
value: z.string().optional().describe("Component value to search for"),
},
async ({ reference, value }) => {
logger.debug(
`Finding component with ${reference ? `reference: ${reference}` : `value: ${value}`}`,
);
const result = await callKicadScript("find_component", {
reference,
value,
});
return {
content: [
{
type: "text",
text: JSON.stringify(result),
},
],
};
},
);
// ------------------------------------------------------
// Get Component Properties Tool
// ------------------------------------------------------
server.tool(
"get_component_properties",
{
reference: z
.string()
.describe("Reference designator of the component (e.g., 'R5')"),
},
async ({ reference }) => {
logger.debug(`Getting properties for component: ${reference}`);
const result = await callKicadScript("get_component_properties", {
reference,
});
return {
content: [
{
type: "text",
text: JSON.stringify(result),
},
],
};
},
);
// ------------------------------------------------------
// Add Component Annotation Tool
// ------------------------------------------------------
server.tool(
"add_component_annotation",
{
reference: z
.string()
.describe("Reference designator of the component (e.g., 'R5')"),
annotation: z.string().describe("Annotation or comment text to add"),
visible: z
.boolean()
.optional()
.describe("Whether the annotation should be visible on the PCB"),
},
async ({ reference, annotation, visible }) => {
logger.debug(`Adding annotation to component: ${reference}`);
const result = await callKicadScript("add_component_annotation", {
reference,
annotation,
visible,
});
return {
content: [
{
type: "text",
text: JSON.stringify(result),
},
],
};
},
);
// ------------------------------------------------------
// Group Components Tool
// ------------------------------------------------------
server.tool(
"group_components",
{
references: z
.array(z.string())
.describe("Reference designators of components to group"),
groupName: z.string().describe("Name for the component group"),
},
async ({ references, groupName }) => {
logger.debug(
`Grouping components: ${references.join(", ")} as ${groupName}`,
);
const result = await callKicadScript("group_components", {
references,
groupName,
});
return {
content: [
{
type: "text",
text: JSON.stringify(result),
},
],
};
},
);
// ------------------------------------------------------
// Replace Component Tool
// ------------------------------------------------------
server.tool(
"replace_component",
{
reference: z
.string()
.describe("Reference designator of the component to replace"),
newComponentId: z.string().describe("ID of the new component to use"),
newFootprint: z.string().optional().describe("Optional new footprint"),
newValue: z.string().optional().describe("Optional new component value"),
},
async ({ reference, newComponentId, newFootprint, newValue }) => {
logger.debug(`Replacing component: ${reference} with ${newComponentId}`);
const result = await callKicadScript("replace_component", {
reference,
newComponentId,
newFootprint,
newValue,
});
return {
content: [
{
type: "text",
text: JSON.stringify(result),
},
],
};
},
);
// ------------------------------------------------------
// Get Component Pads Tool
// ------------------------------------------------------
server.tool(
"get_component_pads",
{
reference: z
.string()
.describe("Reference designator of the component (e.g., 'U1')"),
unit: z
.enum(["mm", "inch"])
.optional()
.describe("Unit for coordinates (default: mm)"),
},
async ({ reference, unit }) => {
logger.debug(`Getting pads for component: ${reference}`);
const result = await callKicadScript("get_component_pads", {
reference,
unit: unit || "mm",
});
return {
content: [
{
type: "text",
text: JSON.stringify(result),
},
],
};
},
);
// ------------------------------------------------------
// Get Component List Tool
// ------------------------------------------------------
server.tool(
"get_component_list",
{
layer: z
.string()
.optional()
.describe("Filter by layer (e.g., 'F.Cu', 'B.Cu')"),
boundingBox: z
.object({
x1: z.number(),
y1: z.number(),
x2: z.number(),
y2: z.number(),
unit: z.enum(["mm", "inch"]).optional(),
})
.optional()
.describe("Filter by bounding box region"),
unit: z
.enum(["mm", "inch"])
.optional()
.describe("Unit for coordinates (default: mm)"),
},
async ({ layer, boundingBox, unit }) => {
logger.debug("Getting component list");
const result = await callKicadScript("get_component_list", {
layer,
boundingBox,
unit: unit || "mm",
});
return {
content: [
{
type: "text",
text: JSON.stringify(result),
},
],
};
},
);
// ------------------------------------------------------
// Get Pad Position Tool
// ------------------------------------------------------
server.tool(
"get_pad_position",
{
reference: z
.string()
.describe("Component reference designator (e.g., 'U1')"),
pad: z.string().describe("Pad number or name (e.g., '1', 'A1')"),
unit: z
.enum(["mm", "inch"])
.optional()
.describe("Unit for coordinates (default: mm)"),
},
async ({ reference, pad, unit }) => {
logger.debug(`Getting pad position for ${reference} pad ${pad}`);
const result = await callKicadScript("get_pad_position", {
reference,
pad,
unit: unit || "mm",
});
return {
content: [
{
type: "text",
text: JSON.stringify(result),
},
],
};
},
);
// ------------------------------------------------------
// Place Component Array Tool
// ------------------------------------------------------
server.tool(
"place_component_array",
{
componentId: z.string().describe("Component identifier"),
startPosition: z
.object({
x: z.number(),
y: z.number(),
unit: z.enum(["mm", "inch"]),
})
.describe("Starting position"),
rows: z.number().describe("Number of rows"),
columns: z.number().describe("Number of columns"),
rowSpacing: z.number().describe("Spacing between rows"),
columnSpacing: z.number().describe("Spacing between columns"),
startReference: z
.string()
.optional()
.describe("Starting reference (e.g., 'R1')"),
footprint: z.string().optional().describe("Footprint name"),
value: z.string().optional().describe("Component value"),
rotation: z.number().optional().describe("Rotation in degrees"),
},
async ({
componentId,
startPosition,
rows,
columns,
rowSpacing,
columnSpacing,
startReference,
footprint,
value,
rotation,
}) => {
logger.debug(
`Placing component array: ${rows}x${columns} of ${componentId}`,
);
const result = await callKicadScript("place_component_array", {
componentId,
startPosition,
rows,
columns,
rowSpacing,
columnSpacing,
startReference,
footprint,
value,
rotation,
});
return {
content: [
{
type: "text",
text: JSON.stringify(result),
},
],
};
},
);
// ------------------------------------------------------
// Align Components Tool
// ------------------------------------------------------
server.tool(
"align_components",
{
references: z
.array(z.string())
.describe("Array of component references to align"),
alignmentType: z
.enum(["horizontal", "vertical", "grid"])
.describe("Type of alignment"),
spacing: z
.number()
.optional()
.describe("Spacing between components in mm"),
referenceComponent: z
.string()
.optional()
.describe("Reference component for alignment"),
},
async ({ references, alignmentType, spacing, referenceComponent }) => {
logger.debug(`Aligning components: ${references.join(", ")}`);
const result = await callKicadScript("align_components", {
references,
alignmentType,
spacing,
referenceComponent,
});
return {
content: [
{
type: "text",
text: JSON.stringify(result),
},
],
};
},
);
// ------------------------------------------------------
// Duplicate Component Tool
// ------------------------------------------------------
server.tool(
"duplicate_component",
{
reference: z.string().describe("Reference of component to duplicate"),
offset: z
.object({
x: z.number(),
y: z.number(),
unit: z.enum(["mm", "inch"]).optional(),
})
.describe("Offset from original position"),
newReference: z.string().optional().describe("New reference designator"),
count: z
.number()
.optional()
.describe("Number of duplicates (default: 1)"),
},
async ({ reference, offset, newReference, count }) => {
logger.debug(`Duplicating component: ${reference}`);
const result = await callKicadScript("duplicate_component", {
reference,
offset,
newReference,
count,
});
return {
content: [
{
type: "text",
text: JSON.stringify(result),
},
],
};
},
);
logger.info("Component management tools registered");
}

View File

@@ -1,159 +1,193 @@
/**
* Library tools for KiCAD MCP server
* Provides access to KiCAD footprint libraries and symbols
*/
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { z } from 'zod';
export function registerLibraryTools(server: McpServer, callKicadScript: Function) {
// List available footprint libraries
server.tool(
"list_libraries",
"List all available KiCAD footprint libraries",
{
search_paths: z.array(z.string()).optional()
.describe("Optional additional search paths for libraries")
},
async (args: { search_paths?: string[] }) => {
const result = await callKicadScript("list_libraries", args);
if (result.success && result.libraries) {
return {
content: [
{
type: "text",
text: `Found ${result.libraries.length} footprint libraries:\n${result.libraries.join('\n')}`
}
]
};
}
return {
content: [
{
type: "text",
text: `Failed to list libraries: ${result.message || 'Unknown error'}`
}
]
};
}
);
// Search for footprints across all libraries
server.tool(
"search_footprints",
"Search for footprints matching a pattern across all libraries",
{
search_term: z.string()
.describe("Search term or pattern to match footprint names"),
library: z.string().optional()
.describe("Optional specific library to search in"),
limit: z.number().optional().default(50)
.describe("Maximum number of results to return")
},
async (args: { search_term: string; library?: string; limit?: number }) => {
const result = await callKicadScript("search_footprints", args);
if (result.success && result.footprints) {
const footprintList = result.footprints.map((fp: any) =>
`${fp.library}:${fp.name}${fp.description ? ' - ' + fp.description : ''}`
).join('\n');
return {
content: [
{
type: "text",
text: `Found ${result.footprints.length} matching footprints:\n${footprintList}`
}
]
};
}
return {
content: [
{
type: "text",
text: `Failed to search footprints: ${result.message || 'Unknown error'}`
}
]
};
}
);
// List footprints in a specific library
server.tool(
"list_library_footprints",
"List all footprints in a specific KiCAD library",
{
library_name: z.string()
.describe("Name of the library to list footprints from"),
filter: z.string().optional()
.describe("Optional filter pattern for footprint names"),
limit: z.number().optional().default(100)
.describe("Maximum number of footprints to list")
},
async (args: { library_name: string; filter?: string; limit?: number }) => {
const result = await callKicadScript("list_library_footprints", args);
if (result.success && result.footprints) {
const footprintList = result.footprints.map((fp: string) => ` - ${fp}`).join('\n');
return {
content: [
{
type: "text",
text: `Library ${args.library_name} contains ${result.footprints.length} footprints:\n${footprintList}`
}
]
};
}
return {
content: [
{
type: "text",
text: `Failed to list footprints in library ${args.library_name}: ${result.message || 'Unknown error'}`
}
]
};
}
);
// Get detailed information about a specific footprint
server.tool(
"get_footprint_info",
"Get detailed information about a specific footprint",
{
library_name: z.string()
.describe("Name of the library containing the footprint"),
footprint_name: z.string()
.describe("Name of the footprint to get information about")
},
async (args: { library_name: string; footprint_name: string }) => {
const result = await callKicadScript("get_footprint_info", args);
if (result.success && result.info) {
const info = result.info;
const details = [
`Footprint: ${info.name}`,
`Library: ${info.library}`,
info.description ? `Description: ${info.description}` : '',
info.keywords ? `Keywords: ${info.keywords}` : '',
info.pads ? `Number of pads: ${info.pads}` : '',
info.layers ? `Layers used: ${info.layers.join(', ')}` : '',
info.courtyard ? `Courtyard size: ${info.courtyard.width}mm x ${info.courtyard.height}mm` : '',
info.attributes ? `Attributes: ${JSON.stringify(info.attributes)}` : ''
].filter(line => line).join('\n');
return {
content: [
{
type: "text",
text: details
}
]
};
}
return {
content: [
{
type: "text",
text: `Failed to get footprint info: ${result.message || 'Unknown error'}`
}
]
};
}
);
}
/**
* Library tools for KiCAD MCP server
* Provides access to KiCAD footprint libraries and symbols
*/
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";
export function registerLibraryTools(
server: McpServer,
callKicadScript: Function,
) {
// List available footprint libraries
server.tool(
"list_libraries",
"List all available KiCAD footprint libraries",
{
search_paths: z
.array(z.string())
.optional()
.describe("Optional additional search paths for libraries"),
},
async (args: { search_paths?: string[] }) => {
const result = await callKicadScript("list_libraries", args);
if (result.success && result.libraries) {
return {
content: [
{
type: "text",
text: `Found ${result.libraries.length} footprint libraries:\n${result.libraries.join("\n")}`,
},
],
};
}
return {
content: [
{
type: "text",
text: `Failed to list libraries: ${result.message || "Unknown error"}`,
},
],
};
},
);
// Search for footprints across all libraries
server.tool(
"search_footprints",
"Search for footprints matching a pattern across all libraries",
{
search_term: z
.string()
.describe("Search term or pattern to match footprint names"),
library: z
.string()
.optional()
.describe("Optional specific library to search in"),
limit: z
.number()
.optional()
.default(50)
.describe("Maximum number of results to return"),
},
async (args: { search_term: string; library?: string; limit?: number }) => {
const result = await callKicadScript("search_footprints", {
pattern: args.search_term,
library: args.library,
limit: args.limit,
});
if (result.success && result.footprints) {
const footprintList = result.footprints
.map(
(fp: any) =>
`${fp.full_name || fp.library + ":" + fp.footprint}${fp.description ? " - " + fp.description : ""}`,
)
.join("\n");
return {
content: [
{
type: "text",
text: `Found ${result.footprints.length} matching footprints:\n${footprintList}`,
},
],
};
}
return {
content: [
{
type: "text",
text: `Failed to search footprints: ${result.message || "Unknown error"}`,
},
],
};
},
);
// List footprints in a specific library
server.tool(
"list_library_footprints",
"List all footprints in a specific KiCAD library",
{
library_name: z
.string()
.describe("Name of the library to list footprints from"),
filter: z
.string()
.optional()
.describe("Optional filter pattern for footprint names"),
limit: z
.number()
.optional()
.default(100)
.describe("Maximum number of footprints to list"),
},
async (args: { library_name: string; filter?: string; limit?: number }) => {
const result = await callKicadScript("list_library_footprints", args);
if (result.success && result.footprints) {
const footprintList = result.footprints
.map((fp: string) => ` - ${fp}`)
.join("\n");
return {
content: [
{
type: "text",
text: `Library ${args.library_name} contains ${result.footprints.length} footprints:\n${footprintList}`,
},
],
};
}
return {
content: [
{
type: "text",
text: `Failed to list footprints in library ${args.library_name}: ${result.message || "Unknown error"}`,
},
],
};
},
);
// Get detailed information about a specific footprint
server.tool(
"get_footprint_info",
"Get detailed information about a specific footprint",
{
library_name: z
.string()
.describe("Name of the library containing the footprint"),
footprint_name: z
.string()
.describe("Name of the footprint to get information about"),
},
async (args: { library_name: string; footprint_name: string }) => {
const result = await callKicadScript("get_footprint_info", args);
if (result.success && result.info) {
const info = result.info;
const details = [
`Footprint: ${info.name}`,
`Library: ${info.library}`,
info.description ? `Description: ${info.description}` : "",
info.keywords ? `Keywords: ${info.keywords}` : "",
info.pads ? `Number of pads: ${info.pads}` : "",
info.layers ? `Layers used: ${info.layers.join(", ")}` : "",
info.courtyard
? `Courtyard size: ${info.courtyard.width}mm x ${info.courtyard.height}mm`
: "",
info.attributes
? `Attributes: ${JSON.stringify(info.attributes)}`
: "",
]
.filter((line) => line)
.join("\n");
return {
content: [
{
type: "text",
text: details,
},
],
};
}
return {
content: [
{
type: "text",
text: `Failed to get footprint info: ${result.message || "Unknown error"}`,
},
],
};
},
);
}

View File

@@ -1,101 +1,324 @@
/**
* Routing tools for KiCAD MCP server
*/
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { z } from 'zod';
export function registerRoutingTools(server: McpServer, callKicadScript: Function) {
// Add net tool
server.tool(
"add_net",
"Create a new net on the PCB",
{
name: z.string().describe("Net name"),
netClass: z.string().optional().describe("Net class name"),
},
async (args: { name: string; netClass?: string }) => {
const result = await callKicadScript("add_net", args);
return {
content: [{
type: "text",
text: JSON.stringify(result, null, 2)
}]
};
}
);
// Route trace tool
server.tool(
"route_trace",
"Route a trace between two points",
{
start: z.object({
x: z.number(),
y: z.number(),
unit: z.string().optional()
}).describe("Start position"),
end: z.object({
x: z.number(),
y: z.number(),
unit: z.string().optional()
}).describe("End position"),
layer: z.string().describe("PCB layer"),
width: z.number().describe("Trace width in mm"),
net: z.string().describe("Net name"),
},
async (args: any) => {
const result = await callKicadScript("route_trace", args);
return {
content: [{
type: "text",
text: JSON.stringify(result, null, 2)
}]
};
}
);
// Add via tool
server.tool(
"add_via",
"Add a via to the PCB",
{
position: z.object({
x: z.number(),
y: z.number(),
unit: z.string().optional()
}).describe("Via position"),
net: z.string().describe("Net name"),
viaType: z.string().optional().describe("Via type (through, blind, buried)"),
},
async (args: any) => {
const result = await callKicadScript("add_via", args);
return {
content: [{
type: "text",
text: JSON.stringify(result, null, 2)
}]
};
}
);
// Add copper pour tool
server.tool(
"add_copper_pour",
"Add a copper pour (ground/power plane) to the PCB",
{
layer: z.string().describe("PCB layer"),
net: z.string().describe("Net name"),
clearance: z.number().optional().describe("Clearance in mm"),
},
async (args: any) => {
const result = await callKicadScript("add_copper_pour", args);
return {
content: [{
type: "text",
text: JSON.stringify(result, null, 2)
}]
};
}
);
}
/**
* Routing tools for KiCAD MCP server
*/
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";
export function registerRoutingTools(
server: McpServer,
callKicadScript: Function,
) {
// Add net tool
server.tool(
"add_net",
"Create a new net on the PCB",
{
name: z.string().describe("Net name"),
netClass: z.string().optional().describe("Net class name"),
},
async (args: { name: string; netClass?: string }) => {
const result = await callKicadScript("add_net", args);
return {
content: [
{
type: "text",
text: JSON.stringify(result, null, 2),
},
],
};
},
);
// Route trace tool
server.tool(
"route_trace",
"Route a trace between two points",
{
start: z
.object({
x: z.number(),
y: z.number(),
unit: z.string().optional(),
})
.describe("Start position"),
end: z
.object({
x: z.number(),
y: z.number(),
unit: z.string().optional(),
})
.describe("End position"),
layer: z.string().describe("PCB layer"),
width: z.number().describe("Trace width in mm"),
net: z.string().describe("Net name"),
},
async (args: any) => {
const result = await callKicadScript("route_trace", args);
return {
content: [
{
type: "text",
text: JSON.stringify(result, null, 2),
},
],
};
},
);
// Add via tool
server.tool(
"add_via",
"Add a via to the PCB",
{
position: z
.object({
x: z.number(),
y: z.number(),
unit: z.string().optional(),
})
.describe("Via position"),
net: z.string().describe("Net name"),
viaType: z
.string()
.optional()
.describe("Via type (through, blind, buried)"),
},
async (args: any) => {
const result = await callKicadScript("add_via", args);
return {
content: [
{
type: "text",
text: JSON.stringify(result, null, 2),
},
],
};
},
);
// Add copper pour tool
server.tool(
"add_copper_pour",
"Add a copper pour (ground/power plane) to the PCB",
{
layer: z.string().describe("PCB layer"),
net: z.string().describe("Net name"),
clearance: z.number().optional().describe("Clearance in mm"),
},
async (args: any) => {
const result = await callKicadScript("add_copper_pour", args);
return {
content: [
{
type: "text",
text: JSON.stringify(result, null, 2),
},
],
};
},
);
// Delete trace tool
server.tool(
"delete_trace",
"Delete traces from the PCB. Can delete by UUID, position, or bulk-delete all traces on a net.",
{
traceUuid: z
.string()
.optional()
.describe("UUID of a specific trace to delete"),
position: z
.object({
x: z.number(),
y: z.number(),
unit: z.enum(["mm", "inch"]).optional(),
})
.optional()
.describe("Delete trace nearest to this position"),
net: z
.string()
.optional()
.describe("Delete all traces on this net (bulk delete)"),
layer: z
.string()
.optional()
.describe("Filter by layer when using net-based deletion"),
includeVias: z
.boolean()
.optional()
.describe("Include vias in net-based deletion"),
},
async (args: any) => {
const result = await callKicadScript("delete_trace", args);
return {
content: [
{
type: "text",
text: JSON.stringify(result, null, 2),
},
],
};
},
);
// Query traces tool
server.tool(
"query_traces",
"Query traces on the board with optional filters by net, layer, or bounding box.",
{
net: z.string().optional().describe("Filter by net name"),
layer: z.string().optional().describe("Filter by layer name"),
boundingBox: z
.object({
x1: z.number(),
y1: z.number(),
x2: z.number(),
y2: z.number(),
unit: z.enum(["mm", "inch"]).optional(),
})
.optional()
.describe("Filter by bounding box region"),
unit: z.enum(["mm", "inch"]).optional().describe("Unit for coordinates"),
},
async (args: any) => {
const result = await callKicadScript("query_traces", args);
return {
content: [
{
type: "text",
text: JSON.stringify(result, null, 2),
},
],
};
},
);
// Get nets list tool
server.tool(
"get_nets_list",
"Get a list of all nets in the PCB with optional statistics.",
{
includeStats: z
.boolean()
.optional()
.describe("Include statistics (track count, total length, etc.)"),
unit: z
.enum(["mm", "inch"])
.optional()
.describe("Unit for length measurements"),
},
async (args: any) => {
const result = await callKicadScript("get_nets_list", args);
return {
content: [
{
type: "text",
text: JSON.stringify(result, null, 2),
},
],
};
},
);
// Modify trace tool
server.tool(
"modify_trace",
"Modify an existing trace (change width, layer, or net).",
{
traceUuid: z.string().describe("UUID of the trace to modify"),
width: z.number().optional().describe("New trace width in mm"),
layer: z.string().optional().describe("New layer name"),
net: z.string().optional().describe("New net name"),
},
async (args: any) => {
const result = await callKicadScript("modify_trace", args);
return {
content: [
{
type: "text",
text: JSON.stringify(result, null, 2),
},
],
};
},
);
// Create netclass tool
server.tool(
"create_netclass",
"Create a new net class with custom design rules.",
{
name: z.string().describe("Net class name"),
traceWidth: z.number().optional().describe("Default trace width in mm"),
clearance: z.number().optional().describe("Clearance in mm"),
viaDiameter: z.number().optional().describe("Via diameter in mm"),
viaDrill: z.number().optional().describe("Via drill size in mm"),
},
async (args: any) => {
const result = await callKicadScript("create_netclass", args);
return {
content: [
{
type: "text",
text: JSON.stringify(result, null, 2),
},
],
};
},
);
// Route differential pair tool
server.tool(
"route_differential_pair",
"Route a differential pair between two sets of points.",
{
positivePad: z
.object({
reference: z.string(),
pad: z.string(),
})
.describe("Positive pad (component and pad number)"),
negativePad: z
.object({
reference: z.string(),
pad: z.string(),
})
.describe("Negative pad (component and pad number)"),
layer: z.string().describe("PCB layer"),
width: z.number().describe("Trace width in mm"),
gap: z.number().describe("Gap between traces in mm"),
positiveNet: z.string().describe("Positive net name"),
negativeNet: z.string().describe("Negative net name"),
},
async (args: any) => {
const result = await callKicadScript("route_differential_pair", args);
return {
content: [
{
type: "text",
text: JSON.stringify(result, null, 2),
},
],
};
},
);
// Refill zones tool
server.tool(
"refill_zones",
"Refill all copper zones on the board. WARNING: SWIG path has known segfault risk (see KNOWN_ISSUES.md). Prefer using IPC backend (KiCAD open) or triggering zone fill via KiCAD UI instead.",
{},
async (args: any) => {
const result = await callKicadScript("refill_zones", args);
return {
content: [
{
type: "text",
text: JSON.stringify(result, null, 2),
},
],
};
},
);
}