kicad-mcp/src/mckicad/utils/kicad_utils.py
Ryan Malloy 4ae38fed59 Rebuild on FastMCP 3 with src-layout and kicad-sch-api integration
Migrate from FastMCP 2.14.5 to 3.1.0 with complete architectural
overhaul. Adopt src-layout packaging, lazy config functions to
eliminate .env race condition, and decorator-based tool registration.

Consolidate 14 tool modules into 8 focused modules (33 tools total).
Add 9 new schematic tools via kicad-sch-api for creating and
manipulating .kicad_sch files. Drop pandas dependency (BOM uses
stdlib csv). Remove ~17k lines of stubs, over-engineering, and
dead code.

All checks pass: ruff clean, mypy 0 errors, 17/17 tests green.
2026-03-03 18:26:54 -07:00

140 lines
4.8 KiB
Python

"""
KiCad-specific utility functions.
"""
import logging
import os
import subprocess
import sys
from typing import Any
from mckicad.config import (
KICAD_EXTENSIONS,
get_kicad_app_path,
get_kicad_user_dir,
get_search_paths,
)
def find_kicad_projects() -> list[dict[str, Any]]:
"""Find KiCad projects in the user's directory.
Returns:
List of dictionaries with project information
"""
projects = []
logging.info("Attempting to find KiCad projects...")
kicad_user_dir = get_kicad_user_dir()
additional_search_paths = get_search_paths()
# Search directories to look for KiCad projects
raw_search_dirs = [kicad_user_dir] + additional_search_paths
logging.info(f"Raw kicad_user_dir: '{kicad_user_dir}'")
logging.info(f"Raw additional_search_paths: {additional_search_paths}")
logging.info(f"Raw search list before expansion: {raw_search_dirs}")
expanded_search_dirs = []
for raw_dir in raw_search_dirs:
expanded_dir = os.path.expanduser(raw_dir) # Expand ~ and ~user
if expanded_dir not in expanded_search_dirs:
expanded_search_dirs.append(expanded_dir)
else:
logging.info(f"Skipping duplicate expanded path: {expanded_dir}")
logging.info(f"Expanded search directories: {expanded_search_dirs}")
for search_dir in expanded_search_dirs:
if not os.path.exists(search_dir):
logging.warning(
f"Expanded search directory does not exist: {search_dir}"
)
continue
logging.info(f"Scanning expanded directory: {search_dir}")
# Use followlinks=True to follow symlinks if needed
for root, _, files in os.walk(search_dir, followlinks=True):
for file in files:
if file.endswith(KICAD_EXTENSIONS["project"]):
project_path = os.path.join(root, file)
# Check if it's a real file and not a broken symlink
if not os.path.isfile(project_path):
logging.info(f"Skipping non-file/broken symlink: {project_path}")
continue
try:
# Attempt to get modification time to ensure file is accessible
mod_time = os.path.getmtime(project_path)
rel_path = os.path.relpath(project_path, search_dir)
project_name = get_project_name_from_path(project_path)
logging.info(f"Found accessible KiCad project: {project_path}")
projects.append(
{
"name": project_name,
"path": project_path,
"relative_path": rel_path,
"modified": mod_time,
}
)
except OSError as e:
logging.error(
f"Error accessing project file {project_path}: {e}"
)
continue # Skip if we can't access it
logging.info(f"Found {len(projects)} KiCad projects after scanning.")
return projects
def get_project_name_from_path(project_path: str) -> str:
"""Extract the project name from a .kicad_pro file path.
Args:
project_path: Path to the .kicad_pro file
Returns:
Project name without extension
"""
basename = os.path.basename(project_path)
return basename[: -len(KICAD_EXTENSIONS["project"])]
def open_kicad_project(project_path: str) -> dict[str, Any]:
"""Open a KiCad project using the KiCad application.
Args:
project_path: Path to the .kicad_pro file
Returns:
Dictionary with result information
"""
if not os.path.exists(project_path):
return {"success": False, "error": f"Project not found: {project_path}"}
kicad_app_path = get_kicad_app_path()
try:
cmd = []
if sys.platform == "darwin": # macOS
# On MacOS, use the 'open' command to open the project in KiCad
cmd = ["open", "-a", kicad_app_path, project_path]
elif sys.platform == "linux": # Linux
# On Linux, use 'xdg-open'
cmd = ["xdg-open", project_path]
else:
# Fallback or error for unsupported OS
return {"success": False, "error": f"Unsupported operating system: {sys.platform}"}
result = subprocess.run(cmd, capture_output=True, text=True)
return {
"success": result.returncode == 0,
"command": " ".join(cmd),
"output": result.stdout,
"error": result.stderr if result.returncode != 0 else None,
}
except Exception as e:
return {"success": False, "error": str(e)}