docs: comprehensive documentation overhaul for v2.2.3
Major documentation update bringing all docs current with the 122-tool, 16-category state of the project (previously frozen at v2.1.0-alpha/59 tools). New documentation (9 files): - FREEROUTING_GUIDE.md - autorouter setup, Docker/Podman, all 4 tools - SCHEMATIC_TOOLS_REFERENCE.md - all 27 schematic tools with parameters - ROUTING_TOOLS_REFERENCE.md - all 13 routing tools with examples - FOOTPRINT_SYMBOL_CREATOR_GUIDE.md - 8 creator tools with examples - SVG_IMPORT_GUIDE.md - SVG logo import tool - DATASHEET_TOOLS_GUIDE.md - datasheet enrichment tools - PCB_DESIGN_WORKFLOW.md - end-to-end design guide - ARCHITECTURE.md - system architecture for contributors - INDEX.md - documentation table of contents Updated documentation (12 files): - README.md - tool count 64->122, feature list, contributor credits - TOOL_INVENTORY.md - complete rebuild with all 122 tools - STATUS_SUMMARY.md - updated to v2.2.3 feature matrix - ROADMAP.md - marked completed milestones, added v2.3+ vision - KNOWN_ISSUES.md - removed resolved issues, added v2.2.x fixes - CLIENT_CONFIGURATION.md - added KICAD_MCP_DEV, FREEROUTING_JAR env vars - LIBRARY_INTEGRATION.md - added symbol and project-local library support - ROUTER_ARCHITECTURE.md, ROUTER_QUICK_START.md - updated tool counts - IPC_BACKEND_STATUS.md - updated dates - JLCPCB_USAGE_GUIDE.md - added cross-reference note - CONTRIBUTING.md - added ARCHITECTURE.md reference, updated tool count Archived 10 completed planning docs to docs/archive/. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
490
docs/archive/BUILD_AND_TEST_SESSION.md
Normal file
490
docs/archive/BUILD_AND_TEST_SESSION.md
Normal file
@@ -0,0 +1,490 @@
|
||||
# Build and Test Session Summary
|
||||
**Date:** October 25, 2025 (Evening)
|
||||
**Status:** ✅ **SUCCESS**
|
||||
|
||||
---
|
||||
|
||||
## Session Goals
|
||||
|
||||
Complete the MCP server build and test it with various MCP clients (Claude Desktop, Cline, Claude Code).
|
||||
|
||||
---
|
||||
|
||||
## Completed Work
|
||||
|
||||
### 1. **Fixed TypeScript Compilation Errors** 🔧
|
||||
|
||||
**Problem:** Missing TypeScript source files preventing build
|
||||
|
||||
**Files Created:**
|
||||
- `src/tools/project.ts` (80 lines)
|
||||
- Registers MCP tools: `create_project`, `open_project`, `save_project`, `get_project_info`
|
||||
|
||||
- `src/tools/routing.ts` (100 lines)
|
||||
- Registers MCP tools: `add_net`, `route_trace`, `add_via`, `add_copper_pour`
|
||||
|
||||
- `src/tools/schematic.ts` (76 lines)
|
||||
- Registers MCP tools: `create_schematic`, `add_schematic_component`, `add_wire`
|
||||
|
||||
- `src/utils/resource-helpers.ts` (60 lines)
|
||||
- Helper functions: `createJsonResponse()`, `createBinaryResponse()`, `createErrorResponse()`
|
||||
|
||||
**Total New Code:** ~316 lines of TypeScript
|
||||
|
||||
**Result:** ✅ TypeScript compilation successful, 72 JavaScript files generated in `dist/`
|
||||
|
||||
---
|
||||
|
||||
### 2. **Fixed Duplicate Resource Registration** 🐛
|
||||
|
||||
**Problem:** Both `component.ts` and `library.ts` registered a resource named "component_details"
|
||||
|
||||
**Fix Applied:**
|
||||
- Renamed library resource to `library_component_details`
|
||||
- Updated URI template from `kicad://component/{componentId}` to `kicad://library/component/{componentId}`
|
||||
|
||||
**File Modified:** `src/resources/library.ts`
|
||||
|
||||
**Result:** ✅ No more registration conflicts, server starts cleanly
|
||||
|
||||
---
|
||||
|
||||
### 3. **Successful Server Startup Test** 🚀
|
||||
|
||||
**Test Command:**
|
||||
```bash
|
||||
timeout --signal=TERM 3 node dist/index.js
|
||||
```
|
||||
|
||||
**Server Output (All Green):**
|
||||
```
|
||||
[INFO] Using STDIO transport for local communication
|
||||
[INFO] Registering KiCAD tools, resources, and prompts...
|
||||
[INFO] Registering board management tools
|
||||
[INFO] Board management tools registered
|
||||
[INFO] Registering component management tools
|
||||
[INFO] Component management tools registered
|
||||
[INFO] Registering design rule tools
|
||||
[INFO] Design rule tools registered
|
||||
[INFO] Registering export tools
|
||||
[INFO] Export tools registered
|
||||
[INFO] Registering project resources
|
||||
[INFO] Project resources registered
|
||||
[INFO] Registering board resources
|
||||
[INFO] Board resources registered
|
||||
[INFO] Registering component resources
|
||||
[INFO] Component resources registered
|
||||
[INFO] Registering library resources
|
||||
[INFO] Library resources registered
|
||||
[INFO] Registering component prompts
|
||||
[INFO] Component prompts registered
|
||||
[INFO] Registering routing prompts
|
||||
[INFO] Routing prompts registered
|
||||
[INFO] Registering design prompts
|
||||
[INFO] Design prompts registered
|
||||
[INFO] All KiCAD tools, resources, and prompts registered
|
||||
[INFO] Starting KiCAD MCP server...
|
||||
[INFO] Starting Python process with script: /home/chris/MCP/KiCAD-MCP-Server/python/kicad_interface.py
|
||||
[INFO] Using Python executable: python
|
||||
[INFO] Connecting MCP server to STDIO transport...
|
||||
[INFO] Successfully connected to STDIO transport
|
||||
```
|
||||
|
||||
**Exit Code:** 0 (graceful shutdown)
|
||||
|
||||
**Result:** ✅ Server starts successfully, connects to STDIO, and shuts down gracefully
|
||||
|
||||
---
|
||||
|
||||
### 4. **Comprehensive Client Configuration Guide** 📖
|
||||
|
||||
**File Created:** `docs/CLIENT_CONFIGURATION.md` (500+ lines)
|
||||
|
||||
**Contents:**
|
||||
- Platform-specific configurations:
|
||||
- Linux (Ubuntu/Debian, Arch)
|
||||
- macOS (with KiCAD.app paths)
|
||||
- Windows 10/11 (with proper backslash escaping)
|
||||
|
||||
- Client-specific setup:
|
||||
- **Claude Desktop** - Full configuration for all platforms
|
||||
- **Cline (VSCode)** - User settings and workspace settings
|
||||
- **Claude Code CLI** - MCP config location
|
||||
- **Generic MCP Client** - STDIO transport setup
|
||||
|
||||
- Troubleshooting section:
|
||||
- Server not starting
|
||||
- Client can't connect
|
||||
- Python module errors
|
||||
- Finding KiCAD Python paths
|
||||
|
||||
- Advanced topics:
|
||||
- Multiple KiCAD versions
|
||||
- Custom logging
|
||||
- Development vs Production configs
|
||||
- Security considerations
|
||||
|
||||
**Impact:** New users can configure any MCP client in < 5 minutes!
|
||||
|
||||
---
|
||||
|
||||
### 5. **Updated Configuration Examples** 📝
|
||||
|
||||
**Files Updated:**
|
||||
|
||||
1. **`config/linux-config.example.json`**
|
||||
- Cleaner format (removed unnecessary fields)
|
||||
- Correct PYTHONPATH with both scripting and dist-packages
|
||||
- Placeholder: `YOUR_USERNAME` for easy customization
|
||||
|
||||
2. **`config/windows-config.example.json`**
|
||||
- Fixed path separators (consistent backslashes)
|
||||
- Correct KiCAD 9.0 Python path: `bin\Lib\site-packages`
|
||||
- Simplified structure
|
||||
|
||||
3. **`config/macos-config.example.json`**
|
||||
- Using `Versions/Current` symlink for Python version flexibility
|
||||
- Updated to match CLIENT_CONFIGURATION.md format
|
||||
|
||||
---
|
||||
|
||||
### 6. **Updated README.md** 📚
|
||||
|
||||
**Addition:** New "Configuration for Other Clients" section after Quick Start
|
||||
|
||||
**Changes:**
|
||||
- Added links to CLIENT_CONFIGURATION.md guide
|
||||
- Listed all supported MCP clients (Claude Desktop, Cline, Claude Code)
|
||||
- Highlighted that KiCAD MCP works with ANY MCP-compatible client
|
||||
- Clear guide reference with feature list
|
||||
|
||||
**Result:** Users immediately know where to find setup instructions for their client
|
||||
|
||||
---
|
||||
|
||||
## Statistics
|
||||
|
||||
### Files Created/Modified (This Session)
|
||||
|
||||
**New Files (5):**
|
||||
```
|
||||
src/tools/project.ts # 80 lines
|
||||
src/tools/routing.ts # 100 lines
|
||||
src/tools/schematic.ts # 76 lines
|
||||
src/utils/resource-helpers.ts # 60 lines
|
||||
docs/CLIENT_CONFIGURATION.md # 500+ lines
|
||||
docs/BUILD_AND_TEST_SESSION.md # This file
|
||||
```
|
||||
|
||||
**Modified Files (5):**
|
||||
```
|
||||
src/resources/library.ts # Fixed duplicate registration
|
||||
config/linux-config.example.json # Updated format
|
||||
config/windows-config.example.json # Fixed paths
|
||||
config/macos-config.example.json # Updated format
|
||||
README.md # Added config guide section
|
||||
```
|
||||
|
||||
**Total New Lines:** ~816+ lines of code and documentation
|
||||
|
||||
---
|
||||
|
||||
## Build Artifacts
|
||||
|
||||
### Generated Files
|
||||
|
||||
**TypeScript Compilation:**
|
||||
- 72 JavaScript files in `dist/`
|
||||
- 24 declaration files (`.d.ts`)
|
||||
- 24 source maps (`.js.map`)
|
||||
|
||||
**Directory Structure:**
|
||||
```
|
||||
dist/
|
||||
├── index.js (entry point)
|
||||
├── server.js (MCP server implementation)
|
||||
├── kicad-server.js (KiCAD interface)
|
||||
├── tools/ (10 tool modules)
|
||||
├── resources/ (6 resource modules)
|
||||
├── prompts/ (4 prompt modules)
|
||||
└── utils/ (helper utilities)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Verification Tests
|
||||
|
||||
### ✅ Test 1: TypeScript Compilation
|
||||
```bash
|
||||
npm run build
|
||||
# Result: SUCCESS (no errors)
|
||||
```
|
||||
|
||||
### ✅ Test 2: Server Startup
|
||||
```bash
|
||||
timeout --signal=TERM 3 node dist/index.js
|
||||
# Result: SUCCESS (exit code 0)
|
||||
# - All tools registered
|
||||
# - All resources registered
|
||||
# - All prompts registered
|
||||
# - STDIO transport connected
|
||||
# - Python process spawned
|
||||
# - Graceful shutdown
|
||||
```
|
||||
|
||||
### ✅ Test 3: Python Integration
|
||||
- Python process successfully spawned: `/home/chris/MCP/KiCAD-MCP-Server/python/kicad_interface.py`
|
||||
- Using system Python: `python` (resolved to Python 3.12)
|
||||
- No Python import errors during startup
|
||||
|
||||
---
|
||||
|
||||
## Ready for Testing
|
||||
|
||||
### MCP Server Capabilities
|
||||
|
||||
**Registered Tools (20+):**
|
||||
- Project: create_project, open_project, save_project, get_project_info
|
||||
- Board: set_board_size, add_board_outline, get_board_properties
|
||||
- Component: add_component, move_component, rotate_component, get_component_list
|
||||
- Routing: add_net, route_trace, add_via, add_copper_pour
|
||||
- Schematic: create_schematic, add_schematic_component, add_wire
|
||||
- Design Rules: set_track_width, set_via_size, set_clearance, run_drc
|
||||
- Export: export_gerber, export_pdf, export_svg, export_3d_model
|
||||
|
||||
**Registered Resources (15+):**
|
||||
- Project info and metadata
|
||||
- Board info, layers, extents
|
||||
- Board 2D/3D views (PNG, SVG)
|
||||
- Component details (placed and library)
|
||||
- Statistics and analytics
|
||||
|
||||
**Registered Prompts (10+):**
|
||||
- Component selection guidance
|
||||
- Routing strategy suggestions
|
||||
- Design best practices
|
||||
|
||||
---
|
||||
|
||||
## Next Steps
|
||||
|
||||
### Immediate Testing (Ready Now)
|
||||
|
||||
1. **Test with Claude Code CLI:**
|
||||
```bash
|
||||
# Create config
|
||||
mkdir -p ~/.config/claude-code
|
||||
cp docs/CLIENT_CONFIGURATION.md ~/.config/claude-code/
|
||||
|
||||
# Test connection
|
||||
claude-code mcp list
|
||||
claude-code mcp test kicad
|
||||
```
|
||||
|
||||
2. **Test with Claude Desktop:**
|
||||
- Copy config from `config/linux-config.example.json`
|
||||
- Edit `~/.config/Claude/claude_desktop_config.json`
|
||||
- Restart Claude Desktop
|
||||
- Start conversation and look for KiCAD tools
|
||||
|
||||
3. **Test with Cline (VSCode):**
|
||||
- Already configured from previous session
|
||||
- Open VSCode, start Cline chat
|
||||
- Ask: "What KiCAD tools are available?"
|
||||
|
||||
### Integration Testing
|
||||
|
||||
**Test basic workflow:**
|
||||
```
|
||||
1. Create new project
|
||||
2. Set board size
|
||||
3. Add component
|
||||
4. Create trace
|
||||
5. Export Gerber files
|
||||
```
|
||||
|
||||
**Test resources:**
|
||||
```
|
||||
1. Request board info
|
||||
2. View 2D board rendering
|
||||
3. Get component list
|
||||
4. Check board statistics
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Technical Highlights
|
||||
|
||||
### 1. **Modular Tool Registration**
|
||||
|
||||
Each tool module follows consistent pattern:
|
||||
```typescript
|
||||
export function registerXxxTools(server: McpServer, callKicadScript: Function) {
|
||||
server.tool("tool_name", "Description", schema, async (args) => {
|
||||
const result = await callKicadScript("command_name", args);
|
||||
return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
**Benefits:**
|
||||
- Easy to add new tools
|
||||
- Consistent error handling
|
||||
- Clean separation of concerns
|
||||
|
||||
### 2. **Resource Helper Utilities**
|
||||
|
||||
Abstracted common response patterns:
|
||||
```typescript
|
||||
createJsonResponse(data, uri) // For JSON data
|
||||
createBinaryResponse(data, mime) // For images/binary
|
||||
createErrorResponse(error, msg) // For errors
|
||||
```
|
||||
|
||||
**Benefits:**
|
||||
- DRY principle (Don't Repeat Yourself)
|
||||
- Consistent response format
|
||||
- Easy to modify response structure
|
||||
|
||||
### 3. **STDIO Transport**
|
||||
|
||||
Using standard STDIO (stdin/stdout) for MCP protocol:
|
||||
- No network ports required
|
||||
- Maximum security (process isolation)
|
||||
- Works with all MCP clients
|
||||
- Simple debugging (can pipe commands)
|
||||
|
||||
### 4. **Python Subprocess Integration**
|
||||
|
||||
Server spawns Python process for KiCAD operations:
|
||||
- Persistent Python process (faster than per-call spawn)
|
||||
- JSON-RPC communication over stdin/stdout
|
||||
- Proper error propagation
|
||||
- Graceful shutdown handling
|
||||
|
||||
---
|
||||
|
||||
## Achievements
|
||||
|
||||
### Development Infrastructure ✅
|
||||
- ✅ TypeScript build pipeline working
|
||||
- ✅ All source files complete
|
||||
- ✅ No compilation errors
|
||||
- ✅ Source maps generated for debugging
|
||||
|
||||
### Server Functionality ✅
|
||||
- ✅ MCP protocol implementation working
|
||||
- ✅ STDIO transport connected
|
||||
- ✅ Python subprocess integration
|
||||
- ✅ Tool/resource/prompt registration
|
||||
- ✅ Graceful startup and shutdown
|
||||
|
||||
### Documentation ✅
|
||||
- ✅ Comprehensive client configuration guide
|
||||
- ✅ Platform-specific examples
|
||||
- ✅ Troubleshooting section
|
||||
- ✅ Advanced configuration options
|
||||
|
||||
### Configuration ✅
|
||||
- ✅ Linux config example
|
||||
- ✅ Windows config example
|
||||
- ✅ macOS config example
|
||||
- ✅ README updated with guide links
|
||||
|
||||
---
|
||||
|
||||
## Build Status
|
||||
|
||||
**Week 1 Progress:** 100% ✅
|
||||
|
||||
| Category | Status |
|
||||
|----------|--------|
|
||||
| TypeScript compilation | ✅ Complete |
|
||||
| Server startup | ✅ Working |
|
||||
| STDIO transport | ✅ Connected |
|
||||
| Python integration | ✅ Functional |
|
||||
| Client configs | ✅ Documented |
|
||||
| Testing guides | ✅ Available |
|
||||
|
||||
---
|
||||
|
||||
## Success Criteria Met
|
||||
|
||||
✅ **Build completes without errors**
|
||||
✅ **Server starts and connects to STDIO**
|
||||
✅ **All tools/resources registered successfully**
|
||||
✅ **Python subprocess spawns correctly**
|
||||
✅ **Configuration documented for all clients**
|
||||
✅ **Ready for end-to-end testing**
|
||||
|
||||
---
|
||||
|
||||
## Testing Readiness
|
||||
|
||||
### Can Test Now With:
|
||||
|
||||
1. **Claude Code CLI** - Via `~/.config/claude-code/mcp_config.json`
|
||||
2. **Claude Desktop** - Via `~/.config/Claude/claude_desktop_config.json`
|
||||
3. **Cline (VSCode)** - Already configured
|
||||
4. **Direct STDIO** - Manual JSON-RPC testing
|
||||
|
||||
### Testing Checklist:
|
||||
|
||||
- [ ] Server responds to `initialize` request
|
||||
- [ ] Server lists tools correctly
|
||||
- [ ] Server lists resources correctly
|
||||
- [ ] Server lists prompts correctly
|
||||
- [ ] Tool invocation returns results
|
||||
- [ ] Resource fetch returns data
|
||||
- [ ] Prompt templates work
|
||||
- [ ] Error handling works
|
||||
- [ ] Graceful shutdown works
|
||||
|
||||
---
|
||||
|
||||
## Code Quality
|
||||
|
||||
**Metrics:**
|
||||
- TypeScript strict mode: ✅ Enabled
|
||||
- ESLint compliance: ✅ Clean
|
||||
- Type coverage: ✅ 100% (all exports typed)
|
||||
- Source maps: ✅ Generated
|
||||
- Build warnings: 0
|
||||
- Build errors: 0
|
||||
|
||||
---
|
||||
|
||||
## Session Impact
|
||||
|
||||
### Before This Session:
|
||||
- TypeScript wouldn't compile (missing files)
|
||||
- Server had duplicate resource registration bug
|
||||
- No client configuration documentation
|
||||
- Unclear how to use with different MCP clients
|
||||
|
||||
### After This Session:
|
||||
- Complete TypeScript build working
|
||||
- Server starts cleanly with all features registered
|
||||
- Comprehensive 500+ line configuration guide
|
||||
- Ready for testing with any MCP client
|
||||
|
||||
---
|
||||
|
||||
## Momentum Check
|
||||
|
||||
**Status:** 🟢 **EXCELLENT**
|
||||
|
||||
- Build: ✅ Working
|
||||
- Tests: ✅ Passing (server startup)
|
||||
- Docs: ✅ Comprehensive
|
||||
- Code Quality: ⭐⭐⭐⭐⭐
|
||||
|
||||
**Ready for:** Live testing with MCP clients
|
||||
|
||||
---
|
||||
|
||||
**End of Build and Test Session**
|
||||
|
||||
**Next:** Test with Claude Desktop/Code/Cline and verify tool invocations work end-to-end
|
||||
|
||||
🎉 **BUILD SUCCESSFUL - READY FOR TESTING!** 🎉
|
||||
485
docs/archive/DYNAMIC_LIBRARY_LOADING_PLAN.md
Normal file
485
docs/archive/DYNAMIC_LIBRARY_LOADING_PLAN.md
Normal file
@@ -0,0 +1,485 @@
|
||||
# Option 2: Dynamic Library Loading Plan
|
||||
|
||||
## Executive Summary
|
||||
|
||||
Replace the template-based schematic workflow with dynamic symbol loading from KiCad's installed symbol libraries. This would eliminate the 13-component limitation and provide access to ALL KiCad symbols (~10,000+ symbols from standard libraries).
|
||||
|
||||
**Current Status (Option 1):**
|
||||
- ✅ Template-based approach working
|
||||
- ✅ 13 component types supported
|
||||
- ❌ Limited symbol variety
|
||||
- ❌ Requires manual template updates for new types
|
||||
|
||||
**Proposed (Option 2):**
|
||||
- 🎯 Dynamic loading from `.kicad_sym` library files
|
||||
- 🎯 Access to ~10,000+ KiCad symbols
|
||||
- 🎯 No template maintenance required
|
||||
- 🎯 User can specify any library/symbol combination
|
||||
|
||||
---
|
||||
|
||||
## Problem Analysis
|
||||
|
||||
### kicad-skip Library Limitation
|
||||
|
||||
**Core Issue:** kicad-skip **cannot create symbols from scratch**. It can only:
|
||||
1. Clone existing symbols from a loaded schematic
|
||||
2. Modify properties of cloned symbols
|
||||
|
||||
**Current Workaround:** Pre-load template symbols in schematic file
|
||||
|
||||
**Proposed Solution:** Load symbols from KiCad's `.kicad_sym` library files, inject them into the schematic's `lib_symbols` section, then clone from there.
|
||||
|
||||
---
|
||||
|
||||
## KiCad Symbol Library Architecture
|
||||
|
||||
### Symbol Library File Format (`.kicad_sym`)
|
||||
|
||||
KiCad symbol libraries are S-expression files containing symbol definitions:
|
||||
|
||||
```lisp
|
||||
(kicad_symbol_lib (version 20211014) (generator kicad_symbol_editor)
|
||||
(symbol "Device:R"
|
||||
(pin_numbers hide)
|
||||
(pin_names (offset 0))
|
||||
(in_bom yes)
|
||||
(on_board yes)
|
||||
(property "Reference" "R" ...)
|
||||
(property "Value" "R" ...)
|
||||
;; Graphics definitions
|
||||
(symbol "R_0_1" ...)
|
||||
(symbol "R_1_1"
|
||||
(pin passive line ...)
|
||||
)
|
||||
)
|
||||
(symbol "Device:C" ...)
|
||||
(symbol "Device:L" ...)
|
||||
;; ... thousands more
|
||||
)
|
||||
```
|
||||
|
||||
### Standard KiCad Library Locations
|
||||
|
||||
**Linux:**
|
||||
- System libraries: `/usr/share/kicad/symbols/`
|
||||
- User libraries: `~/.local/share/kicad/8.0/symbols/` or `~/.config/kicad/8.0/symbols/`
|
||||
|
||||
**Windows:**
|
||||
- System libraries: `C:\Program Files\KiCad\9.0\share\kicad\symbols\`
|
||||
- User libraries: `%APPDATA%\kicad\8.0\symbols\`
|
||||
|
||||
**macOS:**
|
||||
- System libraries: `/Applications/KiCad/KiCad.app/Contents/SharedSupport/symbols/`
|
||||
- User libraries: `~/Library/Preferences/kicad/8.0/symbols/`
|
||||
|
||||
### Standard Library Files
|
||||
|
||||
Common libraries (each containing 50-500 symbols):
|
||||
- `Device.kicad_sym` - Passives (R, C, L, D, LED, Crystal, etc.)
|
||||
- `Connector.kicad_sym` - Connectors (headers, USB, etc.)
|
||||
- `Connector_Generic.kicad_sym` - Generic connectors
|
||||
- `Transistor_BJT.kicad_sym` - Bipolar transistors
|
||||
- `Transistor_FET.kicad_sym` - MOSFETs
|
||||
- `Amplifier_Operational.kicad_sym` - Op-amps
|
||||
- `Regulator_Linear.kicad_sym` - Voltage regulators
|
||||
- `MCU_*.kicad_sym` - Microcontrollers
|
||||
- `Interface_*.kicad_sym` - Interface ICs
|
||||
- ... 100+ more libraries
|
||||
|
||||
---
|
||||
|
||||
## Implementation Strategy
|
||||
|
||||
### Phase 1: Library Discovery & Indexing
|
||||
|
||||
**Goal:** Build an index of all available symbols and their locations
|
||||
|
||||
**Implementation:**
|
||||
```python
|
||||
class SymbolLibraryManager:
|
||||
def __init__(self):
|
||||
self.library_paths = []
|
||||
self.symbol_index = {} # {"Device:R": "/path/to/Device.kicad_sym", ...}
|
||||
|
||||
def discover_libraries(self):
|
||||
"""Find all KiCad symbol libraries on the system"""
|
||||
search_paths = [
|
||||
"/usr/share/kicad/symbols/",
|
||||
os.path.expanduser("~/.local/share/kicad/8.0/symbols/"),
|
||||
os.path.expanduser("~/.config/kicad/8.0/symbols/"),
|
||||
]
|
||||
|
||||
for search_path in search_paths:
|
||||
if os.path.exists(search_path):
|
||||
for lib_file in os.listdir(search_path):
|
||||
if lib_file.endswith('.kicad_sym'):
|
||||
self.library_paths.append(os.path.join(search_path, lib_file))
|
||||
|
||||
def index_symbols(self):
|
||||
"""Parse all libraries and build symbol index"""
|
||||
for lib_path in self.library_paths:
|
||||
lib_name = os.path.basename(lib_path).replace('.kicad_sym', '')
|
||||
symbols = self._parse_library(lib_path)
|
||||
|
||||
for symbol_name in symbols:
|
||||
full_name = f"{lib_name}:{symbol_name}"
|
||||
self.symbol_index[full_name] = {
|
||||
'library': lib_name,
|
||||
'library_path': lib_path,
|
||||
'symbol_name': symbol_name
|
||||
}
|
||||
|
||||
def _parse_library(self, lib_path):
|
||||
"""Parse .kicad_sym file and extract symbol names"""
|
||||
# Use sexpdata (already a dependency of kicad-skip)
|
||||
import sexpdata
|
||||
|
||||
with open(lib_path, 'r') as f:
|
||||
data = sexpdata.load(f)
|
||||
|
||||
symbols = []
|
||||
for item in data[2:]: # Skip header
|
||||
if isinstance(item, list) and item[0] == Symbol('symbol'):
|
||||
symbol_name = item[1] # e.g., "Device:R"
|
||||
# Extract just the symbol part after ':'
|
||||
if ':' in symbol_name:
|
||||
symbol_name = symbol_name.split(':')[1]
|
||||
symbols.append(symbol_name)
|
||||
|
||||
return symbols
|
||||
```
|
||||
|
||||
### Phase 2: Dynamic Symbol Injection
|
||||
|
||||
**Goal:** Load symbol definition from library file and inject into schematic
|
||||
|
||||
**Challenge:** kicad-skip works with loaded schematics, but we need to dynamically add symbols to the `lib_symbols` section.
|
||||
|
||||
**Solution:** Modify the schematic's S-expression data directly before loading with kicad-skip:
|
||||
|
||||
```python
|
||||
def inject_symbol_into_schematic(schematic_path, library_path, symbol_name):
|
||||
"""
|
||||
1. Read schematic S-expression
|
||||
2. Read library S-expression
|
||||
3. Extract symbol definition from library
|
||||
4. Inject into schematic's lib_symbols section
|
||||
5. Save modified schematic
|
||||
6. Reload with kicad-skip
|
||||
"""
|
||||
import sexpdata
|
||||
|
||||
# Load schematic
|
||||
with open(schematic_path, 'r') as f:
|
||||
sch_data = sexpdata.load(f)
|
||||
|
||||
# Load library
|
||||
with open(library_path, 'r') as f:
|
||||
lib_data = sexpdata.load(f)
|
||||
|
||||
# Find symbol definition in library
|
||||
symbol_def = None
|
||||
for item in lib_data[2:]:
|
||||
if isinstance(item, list) and item[0] == Symbol('symbol'):
|
||||
if symbol_name in str(item[1]):
|
||||
symbol_def = item
|
||||
break
|
||||
|
||||
if not symbol_def:
|
||||
raise ValueError(f"Symbol {symbol_name} not found in {library_path}")
|
||||
|
||||
# Find lib_symbols section in schematic
|
||||
lib_symbols_index = None
|
||||
for i, item in enumerate(sch_data):
|
||||
if isinstance(item, list) and item[0] == Symbol('lib_symbols'):
|
||||
lib_symbols_index = i
|
||||
break
|
||||
|
||||
# Inject symbol definition
|
||||
if lib_symbols_index:
|
||||
sch_data[lib_symbols_index].append(symbol_def)
|
||||
|
||||
# Save modified schematic
|
||||
with open(schematic_path, 'w') as f:
|
||||
sexpdata.dump(sch_data, f)
|
||||
|
||||
# Reload with kicad-skip
|
||||
return Schematic(schematic_path)
|
||||
```
|
||||
|
||||
### Phase 3: Template Instance Creation
|
||||
|
||||
**Goal:** Create offscreen template instances that can be cloned
|
||||
|
||||
**After injection:** Symbol definition is in `lib_symbols`, but we need an instance to clone from:
|
||||
|
||||
```python
|
||||
def create_template_instance(schematic, library_name, symbol_name):
|
||||
"""
|
||||
Create an offscreen template instance that can be cloned
|
||||
Similar to our current _TEMPLATE_R approach
|
||||
"""
|
||||
# This requires directly manipulating the S-expression
|
||||
# Add a symbol instance at offscreen position with special reference
|
||||
|
||||
template_ref = f"_TEMPLATE_{library_name}_{symbol_name}"
|
||||
|
||||
# Create symbol instance (S-expression)
|
||||
symbol_instance = [
|
||||
Symbol('symbol'),
|
||||
[Symbol('lib_id'), f"{library_name}:{symbol_name}"],
|
||||
[Symbol('at'), -100, -100 - (len(schematic.symbol) * 10), 0],
|
||||
[Symbol('unit'), 1],
|
||||
[Symbol('in_bom'), Symbol('no')],
|
||||
[Symbol('on_board'), Symbol('no')],
|
||||
[Symbol('dnp'), Symbol('yes')],
|
||||
[Symbol('uuid'), str(uuid.uuid4())],
|
||||
[Symbol('property'), "Reference", template_ref, ...],
|
||||
# ... more properties
|
||||
]
|
||||
|
||||
# Inject into schematic and reload
|
||||
# ... (similar to inject_symbol_into_schematic)
|
||||
|
||||
return template_ref
|
||||
```
|
||||
|
||||
### Phase 4: User-Facing API
|
||||
|
||||
**Goal:** Simple interface for users to add any KiCad symbol
|
||||
|
||||
**New MCP Tool: `add_schematic_component_dynamic`**
|
||||
|
||||
```python
|
||||
def add_schematic_component_dynamic(params):
|
||||
"""
|
||||
Add component by library:symbol notation
|
||||
|
||||
Example:
|
||||
{
|
||||
"library": "Device",
|
||||
"symbol": "R",
|
||||
"reference": "R1",
|
||||
"value": "10k",
|
||||
"x": 100,
|
||||
"y": 100
|
||||
}
|
||||
|
||||
OR using full notation:
|
||||
{
|
||||
"lib_symbol": "Device:R", # Full notation
|
||||
"reference": "R1",
|
||||
...
|
||||
}
|
||||
"""
|
||||
lib_symbol = params.get('lib_symbol') or f"{params['library']}:{params['symbol']}"
|
||||
|
||||
# 1. Check if symbol is already in schematic's lib_symbols
|
||||
# 2. If not, inject it from library file
|
||||
# 3. Create template instance if needed
|
||||
# 4. Clone template and set properties
|
||||
|
||||
return {"success": True, "reference": params['reference']}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Advantages Over Template Approach
|
||||
|
||||
### ✅ Unlimited Symbol Access
|
||||
- Access to ~10,000+ standard KiCad symbols
|
||||
- Support for custom user libraries
|
||||
- Support for 3rd-party libraries (JLCPCB, Espressif, etc.)
|
||||
|
||||
### ✅ No Maintenance Required
|
||||
- Template doesn't need updates for new component types
|
||||
- Automatically supports new KiCad library additions
|
||||
- Works with custom symbol libraries
|
||||
|
||||
### ✅ Better User Experience
|
||||
```
|
||||
User: "Add an STM32F103C8T6 microcontroller at position 100,100"
|
||||
AI: *Searches symbol index*
|
||||
*Finds MCU_ST_STM32F1:STM32F103C8Tx*
|
||||
*Loads from library*
|
||||
*Injects into schematic*
|
||||
*Places component*
|
||||
✓ Done!
|
||||
```
|
||||
|
||||
### ✅ Flexible Symbol Search
|
||||
```python
|
||||
# Find all resistors
|
||||
symbols = lib_manager.search_symbols(query="resistor")
|
||||
# Returns: ["Device:R", "Device:R_Small", "Device:R_Network", ...]
|
||||
|
||||
# Find all STM32 MCUs
|
||||
symbols = lib_manager.search_symbols(query="STM32", library="MCU_ST_STM32F1")
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Challenges & Mitigations
|
||||
|
||||
### Challenge 1: S-expression Manipulation Complexity
|
||||
|
||||
**Problem:** Directly manipulating S-expression data is error-prone
|
||||
|
||||
**Mitigation:**
|
||||
- Use `sexpdata` library (already a dependency)
|
||||
- Create helper functions for common operations
|
||||
- Add comprehensive validation and error handling
|
||||
- Extensive testing with various symbol types
|
||||
|
||||
### Challenge 2: Performance
|
||||
|
||||
**Problem:** Loading/reloading schematics after injection could be slow
|
||||
|
||||
**Mitigation:**
|
||||
- **Cache loaded symbols**: Once injected, symbol stays in schematic
|
||||
- **Batch injection**: Inject multiple symbols at once
|
||||
- **Lazy loading**: Only inject symbols when first used
|
||||
|
||||
### Challenge 3: Symbol Compatibility
|
||||
|
||||
**Problem:** Some symbols may have complex pin configurations or multiple units
|
||||
|
||||
**Mitigation:**
|
||||
- Start with simple 2-pin passives (R, C, L)
|
||||
- Gradually add support for multi-pin ICs
|
||||
- Handle multi-unit symbols (gates, OpAmp sections) explicitly
|
||||
- Document supported symbol types
|
||||
|
||||
### Challenge 4: Library Version Compatibility
|
||||
|
||||
**Problem:** KiCad symbol format may change between versions
|
||||
|
||||
**Mitigation:**
|
||||
- Parse KiCad version from library files
|
||||
- Version-specific handling if needed
|
||||
- Fallback to template approach for unsupported formats
|
||||
|
||||
---
|
||||
|
||||
## Implementation Phases
|
||||
|
||||
### Phase A: Proof of Concept (1-2 weeks)
|
||||
- [ ] Create `SymbolLibraryManager` class
|
||||
- [ ] Implement library discovery (Linux paths only)
|
||||
- [ ] Implement symbol indexing
|
||||
- [ ] Test with Device.kicad_sym (R, C, L)
|
||||
- [ ] Implement basic S-expression injection
|
||||
- [ ] Test end-to-end with simple components
|
||||
|
||||
### Phase B: Core Functionality (2-3 weeks)
|
||||
- [ ] Cross-platform library discovery (Windows, macOS)
|
||||
- [ ] Symbol search functionality
|
||||
- [ ] Template instance creation automation
|
||||
- [ ] Multi-pin component support
|
||||
- [ ] Error handling and validation
|
||||
- [ ] Unit tests for all operations
|
||||
|
||||
### Phase C: MCP Integration (1 week)
|
||||
- [ ] Create `add_schematic_component_dynamic` tool
|
||||
- [ ] Update `search_symbols` to use library index
|
||||
- [ ] Add `list_available_symbols` tool
|
||||
- [ ] Add `list_symbol_libraries` tool
|
||||
- [ ] Documentation and examples
|
||||
|
||||
### Phase D: Advanced Features (2-3 weeks)
|
||||
- [ ] Multi-unit symbol support (e.g., quad OpAmps)
|
||||
- [ ] Custom library registration
|
||||
- [ ] Symbol caching and optimization
|
||||
- [ ] 3rd-party library support (JLCPCB, etc.)
|
||||
- [ ] Symbol preview generation
|
||||
|
||||
---
|
||||
|
||||
## Migration Strategy
|
||||
|
||||
### Backward Compatibility
|
||||
|
||||
Keep template-based approach as fallback:
|
||||
|
||||
```python
|
||||
def add_schematic_component(params):
|
||||
"""Smart component addition with fallback"""
|
||||
# Try dynamic loading first
|
||||
try:
|
||||
if 'library' in params or 'lib_symbol' in params:
|
||||
return add_schematic_component_dynamic(params)
|
||||
except Exception as e:
|
||||
logger.warning(f"Dynamic loading failed: {e}, falling back to template")
|
||||
|
||||
# Fallback to template-based
|
||||
return add_schematic_component_template(params)
|
||||
```
|
||||
|
||||
### Gradual Rollout
|
||||
|
||||
1. **Week 1-2:** Implement basic dynamic loading
|
||||
2. **Week 3-4:** Test with power users, gather feedback
|
||||
3. **Week 5-6:** Make dynamic loading the default
|
||||
4. **Week 7+:** Deprecate template-only approach (keep as fallback)
|
||||
|
||||
---
|
||||
|
||||
## Success Criteria
|
||||
|
||||
### Must Have
|
||||
- [ ] Load symbols from Device.kicad_sym (passives)
|
||||
- [ ] Support R, C, L, D, LED (5 core types)
|
||||
- [ ] Cross-platform library discovery
|
||||
- [ ] Proper error handling
|
||||
|
||||
### Should Have
|
||||
- [ ] Support for all Device.kicad_sym symbols (~50 symbols)
|
||||
- [ ] Support for Connector.kicad_sym symbols
|
||||
- [ ] Symbol search by name/keyword
|
||||
- [ ] Performance: < 1 second per symbol injection
|
||||
|
||||
### Nice to Have
|
||||
- [ ] Support for all standard libraries (~10,000 symbols)
|
||||
- [ ] Multi-unit symbol support
|
||||
- [ ] Custom library registration
|
||||
- [ ] Symbol preview/documentation
|
||||
|
||||
---
|
||||
|
||||
## Risk Assessment
|
||||
|
||||
| Risk | Probability | Impact | Mitigation |
|
||||
|------|-------------|--------|------------|
|
||||
| S-expression parsing complexity | High | High | Use proven `sexpdata` library, extensive testing |
|
||||
| Performance degradation | Medium | Medium | Implement caching, lazy loading |
|
||||
| KiCad version incompatibility | Low | High | Version detection, format validation |
|
||||
| Template fallback breaks | Low | Medium | Maintain template approach in parallel |
|
||||
| User confusion | Medium | Low | Clear documentation, gradual rollout |
|
||||
|
||||
---
|
||||
|
||||
## Conclusion
|
||||
|
||||
Dynamic library loading is **feasible and highly beneficial** for the schematic workflow. While the template-based approach (Option 1) provides immediate value with 13 component types, Option 2 would:
|
||||
|
||||
1. **Eliminate the 13-component limitation**
|
||||
2. **Provide access to 10,000+ KiCad symbols**
|
||||
3. **Remove manual template maintenance**
|
||||
4. **Enable true "natural language PCB design"**
|
||||
|
||||
**Recommendation:**
|
||||
- ✅ **Keep Option 1 (expanded template) for immediate use**
|
||||
- ✅ **Implement Option 2 (dynamic loading) over 6-8 weeks**
|
||||
- ✅ **Maintain template fallback for compatibility**
|
||||
|
||||
This gives users immediate value while we build the robust long-term solution.
|
||||
|
||||
---
|
||||
|
||||
## References
|
||||
|
||||
- [KiCad File Formats Documentation](https://dev-docs.kicad.org/en/file-formats/)
|
||||
- [kicad-skip GitHub](https://github.com/mvnmgrx/kicad-skip)
|
||||
- [sexpdata Python Library](https://github.com/jd-boyd/sexpdata)
|
||||
- [KiCad Symbol Library Format Spec](https://dev-docs.kicad.org/en/file-formats/sexpr-intro/)
|
||||
390
docs/archive/DYNAMIC_LOADING_STATUS.md
Normal file
390
docs/archive/DYNAMIC_LOADING_STATUS.md
Normal file
@@ -0,0 +1,390 @@
|
||||
# Dynamic Symbol Loading - Implementation Status
|
||||
|
||||
**Date:** 2026-01-10
|
||||
**Status:** Phase A-C - ✅ **COMPLETE AND PRODUCTION-READY!**
|
||||
|
||||
## 🚀 BREAKTHROUGH: Full MCP Integration Complete!
|
||||
|
||||
We went from **planning** to **full production integration** in a single session!
|
||||
|
||||
**Phase A** (Proof of Concept): ✅ Complete - Core dynamic loading works
|
||||
**Phase B** (Core Functionality): ✅ ~60% Complete - Cross-platform, caching working
|
||||
**Phase C** (MCP Integration): ✅ **COMPLETE!** - Fully integrated through MCP interface
|
||||
|
||||
The dynamic symbol loading is now **FULLY OPERATIONAL** and accessible through the MCP interface!
|
||||
|
||||
---
|
||||
|
||||
## What's Working (Core Functionality)
|
||||
|
||||
### ✅ Symbol Extraction
|
||||
- Parse `.kicad_sym` library files using S-expression parser
|
||||
- Extract specific symbol definitions by name
|
||||
- Cache parsed libraries for performance
|
||||
- Tested with Device.kicad_sym (533 symbols)
|
||||
|
||||
### ✅ S-Expression Manipulation
|
||||
- Load schematic files as S-expression trees
|
||||
- Inject symbol definitions into `lib_symbols` section
|
||||
- Preserve schematic structure and formatting
|
||||
- Write modified schematics back to disk
|
||||
|
||||
### ✅ Template Instance Creation
|
||||
- Create offscreen template instances at negative Y coordinates
|
||||
- Generate unique UUIDs for each template
|
||||
- Set proper properties (Reference, Value, Footprint, Datasheet)
|
||||
- Templates marked as: `in_bom: no`, `on_board: no`, `dnp: yes`
|
||||
|
||||
### ✅ Component Cloning
|
||||
- kicad-skip successfully clones from dynamic templates
|
||||
- Components inherit symbol structure from injected definitions
|
||||
- Properties can be modified after cloning
|
||||
- Full integration with existing ComponentManager
|
||||
|
||||
### ✅ Cross-Platform Library Discovery
|
||||
- Linux: `/usr/share/kicad/symbols`, `~/.local/share/kicad/*/symbols`
|
||||
- Windows: `C:/Program Files/KiCad/*/share/kicad/symbols`
|
||||
- macOS: `/Applications/KiCad/KiCad.app/Contents/SharedSupport/symbols`
|
||||
- Environment variable support: `KICAD9_SYMBOL_DIR`, etc.
|
||||
|
||||
---
|
||||
|
||||
## Test Results
|
||||
|
||||
### End-to-End Test (Successful)
|
||||
|
||||
**Test:** Load 5 symbols dynamically and create components
|
||||
|
||||
```python
|
||||
Symbols Tested:
|
||||
- Device:R ✓ Injected, template created, cloned successfully
|
||||
- Device:C ✓ Injected, template created, cloned successfully
|
||||
- Device:LED ✓ Injected, template created, cloned successfully
|
||||
- Device:L ✓ Injected, template created, cloned successfully
|
||||
- Device:D ✓ Injected, template created, cloned successfully
|
||||
|
||||
Results:
|
||||
✓ All 5 symbols extracted from Device.kicad_sym
|
||||
✓ All 5 symbol definitions injected into schematic
|
||||
✓ All 5 template instances created
|
||||
✓ kicad-skip loaded modified schematic without errors
|
||||
✓ Components successfully cloned from dynamic templates
|
||||
```
|
||||
|
||||
### Performance Metrics
|
||||
|
||||
- **Library parsing:** ~0.3s for Device.kicad_sym (first time)
|
||||
- **Library parsing:** ~0.001s (cached)
|
||||
- **Symbol extraction:** <0.01s
|
||||
- **Symbol injection:** ~0.05s
|
||||
- **Template creation:** ~0.02s
|
||||
- **Total per symbol:** ~0.08s (first time), ~0.03s (cached)
|
||||
|
||||
**Conclusion:** Fast enough for real-time use!
|
||||
|
||||
---
|
||||
|
||||
## Code Structure
|
||||
|
||||
### New File: `python/commands/dynamic_symbol_loader.py`
|
||||
|
||||
**Class:** `DynamicSymbolLoader`
|
||||
|
||||
**Key Methods:**
|
||||
```python
|
||||
# Library Discovery
|
||||
find_kicad_symbol_libraries() -> List[Path]
|
||||
find_library_file(library_name: str) -> Optional[Path]
|
||||
|
||||
# Parsing & Extraction
|
||||
parse_library_file(library_path: Path) -> List # Returns S-expression
|
||||
extract_symbol_definition(library_path: Path, symbol_name: str) -> Optional[List]
|
||||
|
||||
# Injection & Template Creation
|
||||
inject_symbol_into_schematic(schematic_path: Path, library: str, symbol: str) -> bool
|
||||
create_template_instance(schematic_path: Path, library: str, symbol: str) -> str
|
||||
|
||||
# Complete Workflow
|
||||
load_symbol_dynamically(schematic_path: Path, library: str, symbol: str) -> str
|
||||
```
|
||||
|
||||
**Caching:**
|
||||
- `library_cache`: Parsed library files (path → S-expression data)
|
||||
- `symbol_cache`: Extracted symbols (lib:symbol → symbol definition)
|
||||
|
||||
---
|
||||
|
||||
## What's NOT Yet Done (Integration Layer)
|
||||
|
||||
### ⏳ MCP Tool Integration
|
||||
- Need to create `add_schematic_component_dynamic` MCP tool
|
||||
- Wire dynamic loader through MCP interface (has schematic path)
|
||||
- Update existing `add_schematic_component` to auto-detect and use dynamic loading
|
||||
|
||||
### ⏳ Smart Symbol Discovery
|
||||
- Automatic library detection from component type
|
||||
- Search across all libraries for symbol names
|
||||
- Fuzzy matching for symbol names
|
||||
|
||||
### ⏳ Advanced Features
|
||||
- Multi-unit symbol support (e.g., quad op-amps)
|
||||
- Pin configuration handling
|
||||
- Custom library registration
|
||||
- Symbol preview generation
|
||||
|
||||
---
|
||||
|
||||
## Technical Challenges Solved
|
||||
|
||||
### Challenge 1: S-Expression Parsing
|
||||
**Problem:** KiCad files use Lisp-style S-expressions, complex to parse
|
||||
**Solution:** Used `sexpdata` library (already a dependency of kicad-skip)
|
||||
**Result:** ✅ Robust parsing with proper handling of nested structures
|
||||
|
||||
### Challenge 2: Symbol Structure Complexity
|
||||
**Problem:** Symbols have complex nested structure with multiple sub-symbols
|
||||
**Solution:** Extract entire symbol tree as-is, inject without modification
|
||||
**Result:** ✅ Preserves all symbol details (graphics, pins, properties)
|
||||
|
||||
### Challenge 3: kicad-skip Integration
|
||||
**Problem:** kicad-skip can only clone existing symbols, can't create from scratch
|
||||
**Solution:** Inject symbol into lib_symbols, create template instance, then clone
|
||||
**Result:** ✅ Seamless integration, kicad-skip unaware of dynamic loading
|
||||
|
||||
### Challenge 4: Schematic File Path Access
|
||||
**Problem:** kicad-skip Schematic object doesn't expose file path
|
||||
**Solution:** Pass schematic path explicitly at MCP interface layer
|
||||
**Result:** ⏳ Workaround identified, integration pending
|
||||
|
||||
---
|
||||
|
||||
## Example Usage (Current)
|
||||
|
||||
### Direct Python Usage
|
||||
|
||||
```python
|
||||
from commands.dynamic_symbol_loader import DynamicSymbolLoader
|
||||
from pathlib import Path
|
||||
|
||||
# Initialize loader
|
||||
loader = DynamicSymbolLoader()
|
||||
|
||||
# Load a symbol dynamically
|
||||
schematic_path = Path("/path/to/project.kicad_sch")
|
||||
template_ref = loader.load_symbol_dynamically(
|
||||
schematic_path,
|
||||
library_name="Device",
|
||||
symbol_name="R"
|
||||
)
|
||||
|
||||
# Now use template_ref with kicad-skip to clone components
|
||||
# template_ref will be something like "_TEMPLATE_Device_R"
|
||||
```
|
||||
|
||||
### Future MCP Tool Usage
|
||||
|
||||
```typescript
|
||||
// This is what it WILL look like after integration:
|
||||
|
||||
await mcpServer.callTool("add_schematic_component_dynamic", {
|
||||
library: "MCU_ST_STM32F1",
|
||||
symbol: "STM32F103C8Tx",
|
||||
reference: "U1",
|
||||
x: 100,
|
||||
y: 100,
|
||||
footprint: "Package_QFP:LQFP-48_7x7mm_P0.5mm"
|
||||
});
|
||||
|
||||
// The tool will:
|
||||
// 1. Check if symbol exists in static templates (no)
|
||||
// 2. Dynamically load from MCU_ST_STM32F1.kicad_sym
|
||||
// 3. Inject symbol definition
|
||||
// 4. Create template instance
|
||||
// 5. Clone to create actual component
|
||||
// 6. Set properties (reference, position, footprint)
|
||||
// All of this happens AUTOMATICALLY!
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Comparison: Before vs After
|
||||
|
||||
| Feature | Static Templates (Current) | Dynamic Loading (New) |
|
||||
|---------|---------------------------|----------------------|
|
||||
| **Available Symbols** | 13 types | ~10,000+ types |
|
||||
| **Maintenance** | Manual template updates | Zero maintenance |
|
||||
| **Custom Symbols** | Not supported | Fully supported |
|
||||
| **3rd Party Libs** | Not supported | Fully supported |
|
||||
| **Setup Time** | Pre-created templates | On-demand loading |
|
||||
| **Performance** | Instant (pre-loaded) | ~80ms first time, ~30ms cached |
|
||||
| **Flexibility** | Limited to template list | Any .kicad_sym file |
|
||||
|
||||
---
|
||||
|
||||
## Phase Progress
|
||||
|
||||
### ✅ Phase A: Proof of Concept (COMPLETE)
|
||||
- [x] Create `DynamicSymbolLoader` class
|
||||
- [x] Implement library discovery (Linux paths)
|
||||
- [x] Implement symbol indexing
|
||||
- [x] Test with Device.kicad_sym (R, C, L)
|
||||
- [x] Implement basic S-expression injection
|
||||
- [x] Test end-to-end with simple components
|
||||
|
||||
**Time Estimate:** 1-2 weeks
|
||||
**Actual Time:** 4 hours! 🎉
|
||||
|
||||
### ⏳ Phase B: Core Functionality (IN PROGRESS)
|
||||
- [ ] Cross-platform library discovery (Windows, macOS)
|
||||
- [ ] Symbol search functionality
|
||||
- [ ] Template instance creation automation
|
||||
- [ ] Multi-pin component support
|
||||
- [ ] Error handling and validation
|
||||
- [ ] Unit tests for all operations
|
||||
|
||||
**Time Estimate:** 2-3 weeks
|
||||
**Progress:** 25% (cross-platform discovery done)
|
||||
|
||||
### ✅ Phase C: MCP Integration (COMPLETE!)
|
||||
- [x] Integrate dynamic loading into `add_schematic_component` MCP handler
|
||||
- [x] Implement save → inject → reload → clone orchestration
|
||||
- [x] Add schematic_path parameter throughout component chain
|
||||
- [x] Smart detection of when dynamic loading is needed
|
||||
- [x] Proper error handling and fallback to static templates
|
||||
- [x] End-to-end integration testing (100% passing!)
|
||||
|
||||
**Time Estimate:** 1 week
|
||||
**Actual Time:** 2 hours! 🎉
|
||||
**Status:** PRODUCTION READY!
|
||||
|
||||
**What Works Now:**
|
||||
- ✅ Users can add ANY symbol from KiCad libraries via MCP interface
|
||||
- ✅ Automatic detection and dynamic loading
|
||||
- ✅ Seamless fallback to static templates
|
||||
- ✅ Response includes dynamic_loading_used flag and symbol_source info
|
||||
- ✅ Compatible with all existing MCP clients
|
||||
|
||||
### ⏸️ Phase D: Advanced Features (PENDING)
|
||||
- [ ] Multi-unit symbol support (e.g., quad OpAmps)
|
||||
- [ ] Custom library registration
|
||||
- [ ] Symbol caching and optimization
|
||||
- [ ] 3rd-party library support (JLCPCB, etc.)
|
||||
- [ ] Symbol preview generation
|
||||
|
||||
**Time Estimate:** 2-3 weeks
|
||||
|
||||
---
|
||||
|
||||
## Next Immediate Steps
|
||||
|
||||
1. **Wire Through MCP Interface** (2-3 hours)
|
||||
- Update `python/kicad_interface.py` to pass schematic path
|
||||
- Create wrapper function that combines dynamic loading + cloning
|
||||
- Test with MCP client
|
||||
|
||||
2. **Create MCP Tool** (1-2 hours)
|
||||
- Define `add_schematic_component_dynamic` tool schema
|
||||
- Register in tool registry
|
||||
- Add to documentation
|
||||
|
||||
3. **Integration Testing** (1-2 hours)
|
||||
- Test with Claude Desktop/Cline
|
||||
- Test with complex symbols (ICs, connectors)
|
||||
- Verify error handling
|
||||
|
||||
**Total Time to Full Integration:** ~6 hours
|
||||
|
||||
---
|
||||
|
||||
## Success Metrics
|
||||
|
||||
### Phase A Metrics (All Achieved ✅)
|
||||
- [x] Load symbols from Device.kicad_sym (passives)
|
||||
- [x] Support R, C, L, D, LED (5 core types)
|
||||
- [x] Cross-platform library discovery
|
||||
- [x] Proper error handling
|
||||
|
||||
### Phase B Metrics (Target)
|
||||
- [ ] Support for all Device.kicad_sym symbols (~500 symbols)
|
||||
- [ ] Support for Connector.kicad_sym symbols
|
||||
- [ ] Symbol search by name/keyword
|
||||
- [ ] Performance: < 1 second per symbol injection
|
||||
|
||||
### Overall Success Criteria
|
||||
- [ ] Access to all standard libraries (~10,000 symbols)
|
||||
- [ ] Works on Linux, Windows, macOS
|
||||
- [ ] <100ms latency for cached symbols
|
||||
- [ ] Zero template maintenance required
|
||||
- [ ] Backward compatible with static templates
|
||||
|
||||
---
|
||||
|
||||
## Risks & Mitigations
|
||||
|
||||
| Risk | Status | Mitigation |
|
||||
|------|--------|------------|
|
||||
| S-expression complexity | ✅ RESOLVED | Used proven sexpdata library |
|
||||
| Performance degradation | ✅ RESOLVED | Caching works great (<30ms cached) |
|
||||
| KiCad version compatibility | ⚠️ TESTING | Version detection, format validation |
|
||||
| Template fallback breaks | ✅ PREVENTED | Maintained static templates in parallel |
|
||||
| Integration complexity | ⏳ IN PROGRESS | Clean separation of concerns |
|
||||
|
||||
---
|
||||
|
||||
## Conclusion
|
||||
|
||||
**We did it!** The core dynamic symbol loading is **fully functional**. This is a game-changer for the KiCAD MCP Server:
|
||||
|
||||
- ✅ No more 13-component limitation
|
||||
- ✅ Access to thousands of symbols
|
||||
- ✅ Zero template maintenance
|
||||
- ✅ Production-ready performance
|
||||
|
||||
**The hardest part is DONE.** What remains is integration work (wiring through MCP interface), which is straightforward plumbing.
|
||||
|
||||
**Estimated time to full production deployment:** 6-8 hours of integration work.
|
||||
|
||||
---
|
||||
|
||||
## 🎯 MCP Integration Test Results (2026-01-10)
|
||||
|
||||
**Test:** Full MCP interface with dynamic symbol loading
|
||||
**Status:** ✅ **100% PASSING**
|
||||
|
||||
### Test Components
|
||||
|
||||
| Component | Type | Library | Dynamic? | Result |
|
||||
|-----------|------|---------|----------|--------|
|
||||
| R1 | Resistor | Device | Yes | ✅ Added successfully |
|
||||
| C1 | Capacitor | Device | Yes | ✅ Added successfully |
|
||||
| BT1 | Battery | Device | **Yes** | ✅ **Dynamic load + clone** |
|
||||
| F1 | Fuse | Device | **Yes** | ✅ **Dynamic load + clone** |
|
||||
| T1 | Transformer_1P_1S | Device | **Yes** | ✅ **Dynamic load + clone** |
|
||||
|
||||
### Results Summary
|
||||
|
||||
- **Static templates:** 2/2 successful (R, C)
|
||||
- **Dynamic loading:** 3/3 successful (Battery, Fuse, Transformer)
|
||||
- **Total success rate:** 5/5 (100%)
|
||||
- **Templates created:** 5 (all persisted correctly)
|
||||
- **Reload orchestration:** Working perfectly
|
||||
- **Error handling:** No failures, all fallbacks untested (no errors!)
|
||||
|
||||
### What This Means
|
||||
|
||||
✅ Users can now add **ANY symbol from ~10,000 KiCad symbols** through the MCP interface!
|
||||
|
||||
✅ The system automatically:
|
||||
1. Detects if symbol needs dynamic loading
|
||||
2. Saves current schematic
|
||||
3. Injects symbol definition from library
|
||||
4. Creates template instance
|
||||
5. Reloads schematic
|
||||
6. Clones template to create component
|
||||
7. Saves final result
|
||||
|
||||
✅ **Zero configuration required** - just specify library and symbol name!
|
||||
|
||||
---
|
||||
|
||||
**Amazing progress! From planning to full production in one session!** 🚀 🎉
|
||||
477
docs/archive/IPC_API_MIGRATION_PLAN.md
Normal file
477
docs/archive/IPC_API_MIGRATION_PLAN.md
Normal file
@@ -0,0 +1,477 @@
|
||||
# KiCAD IPC API Migration Plan
|
||||
|
||||
**Status:** 📋 Planning
|
||||
**Target Completion:** Week 2-3 (November 1-8, 2025)
|
||||
**Priority:** 🔴 **CRITICAL** - Current SWIG API deprecated
|
||||
|
||||
---
|
||||
|
||||
## Executive Summary
|
||||
|
||||
The current KiCAD MCP Server uses SWIG-based Python bindings (`import pcbnew`) which are **deprecated as of KiCAD 9.0** and will be **removed in KiCAD 10.0**. We must migrate to the official **KiCAD IPC API** to future-proof the project.
|
||||
|
||||
### Why Migrate?
|
||||
|
||||
| SWIG API (Current) | IPC API (Future) |
|
||||
|-------------------|------------------|
|
||||
| ❌ Deprecated | ✅ Official & Supported |
|
||||
| ❌ Will be removed in KiCAD 10.0 | ✅ Long-term stability |
|
||||
| ❌ Python-only | ✅ Multi-language (Python, JS, etc.) |
|
||||
| ❌ Direct linking | ✅ Inter-process communication |
|
||||
| ⚠️ Synchronous only | ✅ Async support |
|
||||
| ⚠️ No versioning | ✅ Protocol Buffers versioning |
|
||||
|
||||
**Decision: Migrate immediately to avoid technical debt**
|
||||
|
||||
---
|
||||
|
||||
## IPC API Overview
|
||||
|
||||
### Architecture
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ TypeScript MCP Server (Node.js) │
|
||||
└──────────────────────┬──────────────────────────────────────┘
|
||||
│ JSON over stdin/stdout
|
||||
┌──────────────────────▼──────────────────────────────────────┐
|
||||
│ Python Interface Layer │
|
||||
│ ┌────────────────────────────────────────────────────────┐ │
|
||||
│ │ KiCAD API Abstraction (NEW) │ │
|
||||
│ └────────────────────────────────────────────────────────┘ │
|
||||
└──────────────────────┬──────────────────────────────────────┘
|
||||
│ kicad-python library
|
||||
┌──────────────────────▼──────────────────────────────────────┐
|
||||
│ KiCAD IPC Server (Protocol Buffers) │
|
||||
│ Running inside KiCAD Process │
|
||||
└──────────────────────┬──────────────────────────────────────┘
|
||||
│ UNIX Sockets / Named Pipes
|
||||
┌──────────────────────▼──────────────────────────────────────┐
|
||||
│ KiCAD 9.0+ Application │
|
||||
└─────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### Key Differences
|
||||
|
||||
1. **KiCAD Must Be Running**
|
||||
- SWIG: Can run headless, no KiCAD GUI needed
|
||||
- IPC: Requires KiCAD running with IPC server enabled
|
||||
|
||||
2. **Communication Method**
|
||||
- SWIG: Direct Python module import
|
||||
- IPC: Socket-based RPC (Remote Procedure Call)
|
||||
|
||||
3. **API Structure**
|
||||
- SWIG: `board.SetSize(width, height)`
|
||||
- IPC: `kicad.get_board().set_size(width, height)`
|
||||
|
||||
---
|
||||
|
||||
## Migration Strategy
|
||||
|
||||
### Phase 1: Research & Preparation (Days 1-2)
|
||||
|
||||
**Goals:**
|
||||
- Understand kicad-python library
|
||||
- Test IPC connection
|
||||
- Document API differences
|
||||
|
||||
**Tasks:**
|
||||
```bash
|
||||
# Install kicad-python
|
||||
pip install kicad-python>=0.5.0
|
||||
|
||||
# Test basic connection
|
||||
python3 << EOF
|
||||
from kicad import KiCad
|
||||
kicad = KiCad()
|
||||
print(f"Connected to KiCAD: {kicad.check_version()}")
|
||||
EOF
|
||||
|
||||
# Read official documentation
|
||||
# https://docs.kicad.org/kicad-python-main
|
||||
```
|
||||
|
||||
**Deliverables:**
|
||||
- [ ] kicad-python installed and tested
|
||||
- [ ] Connection test script
|
||||
- [ ] API comparison document (SWIG vs IPC)
|
||||
|
||||
---
|
||||
|
||||
### Phase 2: Abstraction Layer (Days 3-4)
|
||||
|
||||
**Goal:** Create an abstraction layer to support both APIs during transition
|
||||
|
||||
**File Structure:**
|
||||
```
|
||||
python/kicad_api/
|
||||
├── __init__.py
|
||||
├── base.py # Abstract base class
|
||||
├── ipc_backend.py # NEW: IPC API implementation
|
||||
├── swig_backend.py # Legacy SWIG implementation
|
||||
└── factory.py # Backend selector
|
||||
```
|
||||
|
||||
**Abstract Interface:**
|
||||
```python
|
||||
# python/kicad_api/base.py
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import Optional
|
||||
from pathlib import Path
|
||||
|
||||
class KiCADBackend(ABC):
|
||||
"""Abstract base class for KiCAD API backends"""
|
||||
|
||||
@abstractmethod
|
||||
def connect(self) -> bool:
|
||||
"""Connect to KiCAD"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def disconnect(self) -> None:
|
||||
"""Disconnect from KiCAD"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def is_connected(self) -> bool:
|
||||
"""Check if connected"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def create_project(self, path: Path, name: str) -> dict:
|
||||
"""Create a new KiCAD project"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def open_project(self, path: Path) -> dict:
|
||||
"""Open existing project"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def get_board(self) -> 'BoardAPI':
|
||||
"""Get board API"""
|
||||
pass
|
||||
|
||||
# ... more abstract methods
|
||||
```
|
||||
|
||||
**IPC Implementation:**
|
||||
```python
|
||||
# python/kicad_api/ipc_backend.py
|
||||
from kicad import KiCad
|
||||
from kicad_api.base import KiCADBackend
|
||||
|
||||
class IPCBackend(KiCADBackend):
|
||||
"""KiCAD IPC API backend"""
|
||||
|
||||
def __init__(self):
|
||||
self.kicad = None
|
||||
|
||||
def connect(self) -> bool:
|
||||
"""Connect to running KiCAD instance"""
|
||||
try:
|
||||
self.kicad = KiCad()
|
||||
# Verify connection
|
||||
version = self.kicad.check_version()
|
||||
logger.info(f"Connected to KiCAD via IPC: {version}")
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to connect via IPC: {e}")
|
||||
return False
|
||||
|
||||
def create_project(self, path: Path, name: str) -> dict:
|
||||
"""Create project using IPC API"""
|
||||
# Implementation here
|
||||
pass
|
||||
```
|
||||
|
||||
**Backend Factory:**
|
||||
```python
|
||||
# python/kicad_api/factory.py
|
||||
from typing import Optional
|
||||
from kicad_api.base import KiCADBackend
|
||||
from kicad_api.ipc_backend import IPCBackend
|
||||
from kicad_api.swig_backend import SWIGBackend
|
||||
|
||||
def create_backend(backend_type: Optional[str] = None) -> KiCADBackend:
|
||||
"""
|
||||
Create appropriate KiCAD backend
|
||||
|
||||
Args:
|
||||
backend_type: 'ipc', 'swig', or None for auto-detect
|
||||
|
||||
Returns:
|
||||
KiCADBackend instance
|
||||
"""
|
||||
if backend_type == 'ipc':
|
||||
return IPCBackend()
|
||||
elif backend_type == 'swig':
|
||||
return SWIGBackend()
|
||||
else:
|
||||
# Auto-detect: Try IPC first, fall back to SWIG
|
||||
try:
|
||||
backend = IPCBackend()
|
||||
if backend.connect():
|
||||
return backend
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
# Fall back to SWIG
|
||||
return SWIGBackend()
|
||||
```
|
||||
|
||||
**Deliverables:**
|
||||
- [ ] Abstract base class defined
|
||||
- [ ] IPC backend implemented
|
||||
- [ ] SWIG backend (wrapper around existing code)
|
||||
- [ ] Factory with auto-detection
|
||||
|
||||
---
|
||||
|
||||
### Phase 3: Port Core Modules (Days 5-8)
|
||||
|
||||
**Migration Order** (by complexity):
|
||||
|
||||
1. **project.py** (Simple - good starting point)
|
||||
- Create, open, save projects
|
||||
- Estimated: 2 hours
|
||||
|
||||
2. **board.py** (Medium - board properties)
|
||||
- Set size, layers, outline
|
||||
- Estimated: 4 hours
|
||||
|
||||
3. **component.py** (Complex - many operations)
|
||||
- Place, move, rotate, delete
|
||||
- Component arrays and alignment
|
||||
- Estimated: 8 hours
|
||||
|
||||
4. **routing.py** (Complex - trace routing)
|
||||
- Nets, traces, vias
|
||||
- Copper pours, differential pairs
|
||||
- Estimated: 8 hours
|
||||
|
||||
5. **design_rules.py** (Medium - DRC)
|
||||
- Set rules, run DRC
|
||||
- Estimated: 4 hours
|
||||
|
||||
6. **export.py** (Medium - file exports)
|
||||
- Gerber, PDF, SVG, 3D
|
||||
- Estimated: 4 hours
|
||||
|
||||
**Total Estimated Time: 30 hours (~4 days)**
|
||||
|
||||
**Migration Template:**
|
||||
```python
|
||||
# OLD (SWIG)
|
||||
import pcbnew
|
||||
board = pcbnew.LoadBoard(filename)
|
||||
board.SetBoardSize(width, height)
|
||||
|
||||
# NEW (IPC via abstraction)
|
||||
from kicad_api import create_backend
|
||||
backend = create_backend('ipc')
|
||||
backend.connect()
|
||||
board_api = backend.get_board()
|
||||
board_api.set_size(width, height)
|
||||
```
|
||||
|
||||
**Deliverables:**
|
||||
- [ ] project.py migrated
|
||||
- [ ] board.py migrated
|
||||
- [ ] component.py migrated
|
||||
- [ ] routing.py migrated
|
||||
- [ ] design_rules.py migrated
|
||||
- [ ] export.py migrated
|
||||
|
||||
---
|
||||
|
||||
### Phase 4: Testing & Validation (Days 9-10)
|
||||
|
||||
**Testing Strategy:**
|
||||
|
||||
1. **Unit Tests**
|
||||
```python
|
||||
@pytest.mark.parametrize("backend_type", ["ipc", "swig"])
|
||||
def test_create_project(backend_type):
|
||||
backend = create_backend(backend_type)
|
||||
result = backend.create_project(Path("/tmp/test"), "TestProject")
|
||||
assert result["success"] is True
|
||||
```
|
||||
|
||||
2. **Integration Tests**
|
||||
- Run side-by-side: IPC vs SWIG
|
||||
- Compare outputs for identical operations
|
||||
- Verify file compatibility
|
||||
|
||||
3. **Performance Benchmarks**
|
||||
```python
|
||||
# Measure: operations/second for each backend
|
||||
# Expected: IPC slightly slower due to IPC overhead
|
||||
```
|
||||
|
||||
**Deliverables:**
|
||||
- [ ] 50+ unit tests passing for IPC backend
|
||||
- [ ] Side-by-side comparison tests
|
||||
- [ ] Performance benchmarks documented
|
||||
|
||||
---
|
||||
|
||||
## API Comparison Reference
|
||||
|
||||
### Project Operations
|
||||
|
||||
| Operation | SWIG | IPC |
|
||||
|-----------|------|-----|
|
||||
| Create project | Custom file creation | `kicad.create_project()` |
|
||||
| Open project | `pcbnew.LoadBoard()` | `kicad.open_project()` |
|
||||
| Save project | `board.Save()` | `board.save()` |
|
||||
|
||||
### Board Operations
|
||||
|
||||
| Operation | SWIG | IPC |
|
||||
|-----------|------|-----|
|
||||
| Get board | `pcbnew.LoadBoard()` | `kicad.get_board()` |
|
||||
| Set size | `board.SetBoardSize()` | `board.set_size()` |
|
||||
| Add layer | `board.GetLayerCount()` | `board.layers.add()` |
|
||||
|
||||
### Component Operations
|
||||
|
||||
| Operation | SWIG | IPC |
|
||||
|-----------|------|-----|
|
||||
| Place component | `pcbnew.FOOTPRINT()` | `board.add_footprint()` |
|
||||
| Move component | `fp.SetPosition()` | `footprint.set_position()` |
|
||||
| Rotate component | `fp.SetOrientation()` | `footprint.set_rotation()` |
|
||||
|
||||
### Routing Operations
|
||||
|
||||
| Operation | SWIG | IPC |
|
||||
|-----------|------|-----|
|
||||
| Add net | `board.GetNetCount()` | `board.nets.add()` |
|
||||
| Route trace | `pcbnew.PCB_TRACK()` | `board.add_track()` |
|
||||
| Add via | `pcbnew.PCB_VIA()` | `board.add_via()` |
|
||||
|
||||
---
|
||||
|
||||
## Configuration Changes
|
||||
|
||||
### Update requirements.txt
|
||||
|
||||
```diff
|
||||
+ # KiCAD IPC API (official Python bindings)
|
||||
+ kicad-python>=0.5.0
|
||||
|
||||
# Legacy SWIG support (for backward compatibility)
|
||||
kicad-skip>=0.1.0
|
||||
```
|
||||
|
||||
### Environment Variables
|
||||
|
||||
```bash
|
||||
# Enable IPC API in KiCAD preferences
|
||||
# Preferences > Plugins > Enable IPC API Server
|
||||
|
||||
# Set backend preference (optional)
|
||||
export KICAD_BACKEND=ipc # or 'swig' or 'auto'
|
||||
```
|
||||
|
||||
### User Migration Guide
|
||||
|
||||
Create `docs/MIGRATING_TO_IPC.md`:
|
||||
- How to enable IPC in KiCAD
|
||||
- What changes for users
|
||||
- Troubleshooting IPC connection issues
|
||||
|
||||
---
|
||||
|
||||
## Rollback Plan
|
||||
|
||||
If IPC migration fails:
|
||||
|
||||
1. **Keep SWIG backend** - Already abstracted
|
||||
2. **Default to SWIG** - Change factory auto-detection
|
||||
3. **Document limitations** - Note that SWIG will be removed eventually
|
||||
4. **Plan retry** - Schedule IPC migration for later
|
||||
|
||||
---
|
||||
|
||||
## Success Criteria
|
||||
|
||||
- [ ] ✅ All existing functionality works with IPC backend
|
||||
- [ ] ✅ Tests pass with both IPC and SWIG backends
|
||||
- [ ] ✅ Performance acceptable (< 20% slowdown vs SWIG)
|
||||
- [ ] ✅ Documentation updated
|
||||
- [ ] ✅ Migration guide created
|
||||
- [ ] ✅ User-facing tools work without changes
|
||||
|
||||
---
|
||||
|
||||
## Timeline
|
||||
|
||||
| Week | Days | Tasks |
|
||||
|------|------|-------|
|
||||
| **Week 2** | Mon-Tue | Research, install kicad-python, test connection |
|
||||
| | Wed-Thu | Build abstraction layer |
|
||||
| | Fri | Port project.py and board.py |
|
||||
| **Week 3** | Mon-Tue | Port component.py and routing.py |
|
||||
| | Wed | Port design_rules.py and export.py |
|
||||
| | Thu-Fri | Testing, validation, documentation |
|
||||
|
||||
---
|
||||
|
||||
## Resources
|
||||
|
||||
- **Official Docs:** https://docs.kicad.org/kicad-python-main
|
||||
- **kicad-python PyPI:** https://pypi.org/project/kicad-python/
|
||||
- **IPC API Spec:** https://dev-docs.kicad.org/en/apis-and-binding/ipc-api/
|
||||
- **Protocol Buffers:** Used by IPC for message format
|
||||
|
||||
---
|
||||
|
||||
## Open Questions
|
||||
|
||||
1. **How to handle KiCAD not running?**
|
||||
- Option A: Auto-launch KiCAD in background
|
||||
- Option B: Require user to launch KiCAD first
|
||||
- Option C: Fall back to SWIG if IPC unavailable
|
||||
- **Decision: Option C for now, A later**
|
||||
|
||||
2. **Connection management**
|
||||
- Should we keep connection open or connect per-operation?
|
||||
- **Decision: Keep alive with reconnect logic**
|
||||
|
||||
3. **Performance vs reliability**
|
||||
- IPC has overhead but more stable
|
||||
- **Decision: Reliability > performance**
|
||||
|
||||
---
|
||||
|
||||
## Next Steps (This Week)
|
||||
|
||||
1. **Install kicad-python**
|
||||
```bash
|
||||
pip install kicad-python
|
||||
```
|
||||
|
||||
2. **Test IPC connection**
|
||||
```bash
|
||||
# Launch KiCAD
|
||||
# Enable IPC in preferences
|
||||
python3 -c "from kicad import KiCad; k=KiCad(); print(k.check_version())"
|
||||
```
|
||||
|
||||
3. **Create abstraction layer structure**
|
||||
```bash
|
||||
mkdir -p python/kicad_api
|
||||
touch python/kicad_api/{__init__,base,ipc_backend,swig_backend,factory}.py
|
||||
```
|
||||
|
||||
4. **Begin project.py migration**
|
||||
- Start with simplest module
|
||||
- Establish patterns for others
|
||||
|
||||
---
|
||||
|
||||
**Prepared by:** Claude Code
|
||||
**Last Updated:** October 25, 2025
|
||||
**Status:** 📋 Ready to execute
|
||||
610
docs/archive/JLCPCB_INTEGRATION_PLAN.md
Normal file
610
docs/archive/JLCPCB_INTEGRATION_PLAN.md
Normal file
@@ -0,0 +1,610 @@
|
||||
# JLCPCB Parts Integration Plan
|
||||
|
||||
**Goal:** Enable AI-driven component selection using JLCPCB's assembly parts library with real pricing and availability
|
||||
|
||||
**Status:** Planning Phase
|
||||
**Estimated Effort:** 3-4 days
|
||||
**Priority:** Week 2 Priority 3 (after Component Libraries + Routing)
|
||||
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
Integrate JLCPCB's SMT assembly parts library (~100k+ parts) into the KiCAD MCP server, enabling:
|
||||
- Component search by specifications (e.g., "10k resistor 0603 1%")
|
||||
- Automatic part selection optimized for cost (prefer Basic parts)
|
||||
- Real stock and pricing information
|
||||
- Mapping JLCPCB parts to KiCAD footprints
|
||||
|
||||
---
|
||||
|
||||
## Architecture
|
||||
|
||||
### Data Flow
|
||||
|
||||
```
|
||||
┌──────────────────────────────────────────────────┐
|
||||
│ JLCPCB API (https://jlcpcb.com/external/...) │
|
||||
│ - Requires API key/secret │
|
||||
│ - Returns: ~100k parts with specs/pricing │
|
||||
└───────────────────┬──────────────────────────────┘
|
||||
│ Download (once, then updates)
|
||||
▼
|
||||
┌──────────────────────────────────────────────────┐
|
||||
│ SQLite Database (local cache) │
|
||||
│ - components table │
|
||||
│ - manufacturers table │
|
||||
│ - categories table │
|
||||
│ - Fast parametric search │
|
||||
└───────────────────┬──────────────────────────────┘
|
||||
│ Search/query
|
||||
▼
|
||||
┌──────────────────────────────────────────────────┐
|
||||
│ JLCPCB Parts Manager (Python) │
|
||||
│ - search_parts(specs) │
|
||||
│ - get_part_info(lcsc_number) │
|
||||
│ - map_to_footprint(package) │
|
||||
│ - suggest_alternatives(part) │
|
||||
└───────────────────┬──────────────────────────────┘
|
||||
│ MCP Tools
|
||||
▼
|
||||
┌──────────────────────────────────────────────────┐
|
||||
│ MCP Tools (TypeScript) │
|
||||
│ - search_jlcpcb_parts │
|
||||
│ - get_jlcpcb_part │
|
||||
│ - place_component (enhanced) │
|
||||
└──────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### File Structure
|
||||
|
||||
```
|
||||
python/commands/
|
||||
├── jlcpcb.py # JLCPCB API client
|
||||
└── jlcpcb_parts.py # Parts database manager
|
||||
|
||||
data/
|
||||
├── jlcpcb_parts.db # SQLite cache (gitignored)
|
||||
└── footprint_mappings.json # Package → KiCAD footprint mapping
|
||||
|
||||
src/tools/
|
||||
└── jlcpcb.ts # MCP tool definitions
|
||||
|
||||
docs/
|
||||
└── JLCPCB_INTEGRATION.md # User documentation
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Implementation Phases
|
||||
|
||||
### Phase 1: JLCPCB API Client (Day 1)
|
||||
|
||||
**File:** `python/commands/jlcpcb.py`
|
||||
|
||||
**Features:**
|
||||
- Authenticate with JLCPCB API (requires user-provided key/secret)
|
||||
- Download parts database (paginated, ~100k parts)
|
||||
- Handle rate limiting and retries
|
||||
- Save to SQLite database
|
||||
|
||||
**API Endpoints:**
|
||||
```python
|
||||
# Get auth token
|
||||
POST https://jlcpcb.com/external/genToken
|
||||
{
|
||||
"appKey": "YOUR_KEY",
|
||||
"appSecret": "YOUR_SECRET"
|
||||
}
|
||||
|
||||
# Fetch parts (paginated)
|
||||
POST https://jlcpcb.com/external/component/getComponentInfos
|
||||
Headers: { "externalApiToken": "TOKEN" }
|
||||
Body: { "lastKey": "PAGINATION_KEY" } # Optional, for next page
|
||||
```
|
||||
|
||||
**Database Schema:**
|
||||
```sql
|
||||
CREATE TABLE components (
|
||||
lcsc TEXT PRIMARY KEY, -- "C12345"
|
||||
category TEXT, -- "Resistors"
|
||||
subcategory TEXT, -- "Chip Resistor - Surface Mount"
|
||||
mfr_part TEXT, -- "RC0603FR-0710KL"
|
||||
package TEXT, -- "0603"
|
||||
solder_joints INTEGER, -- 2
|
||||
manufacturer TEXT, -- "YAGEO"
|
||||
library_type TEXT, -- "Basic" or "Extended"
|
||||
description TEXT, -- "10kΩ ±1% 0.1W"
|
||||
datasheet TEXT, -- URL
|
||||
stock INTEGER, -- 15000
|
||||
price_json TEXT, -- JSON array of price breaks
|
||||
last_updated INTEGER -- Unix timestamp
|
||||
);
|
||||
|
||||
CREATE INDEX idx_category ON components(category, subcategory);
|
||||
CREATE INDEX idx_package ON components(package);
|
||||
CREATE INDEX idx_manufacturer ON components(manufacturer);
|
||||
CREATE INDEX idx_library_type ON components(library_type);
|
||||
```
|
||||
|
||||
**Environment Variables:**
|
||||
```bash
|
||||
# ~/.bashrc or .env
|
||||
export JLCPCB_API_KEY="your_key_here"
|
||||
export JLCPCB_API_SECRET="your_secret_here"
|
||||
```
|
||||
|
||||
**Python Implementation Outline:**
|
||||
```python
|
||||
class JLCPCBClient:
|
||||
def __init__(self, api_key: str, api_secret: str):
|
||||
self.api_key = api_key
|
||||
self.api_secret = api_secret
|
||||
self.token = None
|
||||
|
||||
def authenticate(self) -> str:
|
||||
"""Get auth token from JLCPCB API"""
|
||||
|
||||
def fetch_parts_page(self, last_key: Optional[str] = None) -> dict:
|
||||
"""Fetch one page of parts (paginated)"""
|
||||
|
||||
def download_full_database(self, db_path: str, progress_callback=None):
|
||||
"""Download entire parts library to SQLite"""
|
||||
|
||||
def update_database(self, db_path: str):
|
||||
"""Incremental update (fetch only new/changed parts)"""
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Phase 2: Parts Database Manager (Day 2)
|
||||
|
||||
**File:** `python/commands/jlcpcb_parts.py`
|
||||
|
||||
**Features:**
|
||||
- Initialize/load SQLite database
|
||||
- Parametric search (resistance, capacitance, voltage, etc.)
|
||||
- Filter by library type (Basic/Extended)
|
||||
- Sort by price, stock, or popularity
|
||||
- Map package names to KiCAD footprints
|
||||
|
||||
**Python Implementation Outline:**
|
||||
```python
|
||||
class JLCPCBPartsManager:
|
||||
def __init__(self, db_path: str = "data/jlcpcb_parts.db"):
|
||||
self.conn = sqlite3.connect(db_path)
|
||||
|
||||
def search_parts(
|
||||
self,
|
||||
query: str = None, # Free-text search
|
||||
category: str = None, # "Resistors"
|
||||
package: str = None, # "0603"
|
||||
library_type: str = None, # "Basic" only
|
||||
manufacturer: str = None, # "YAGEO"
|
||||
in_stock: bool = True, # Only parts with stock > 0
|
||||
limit: int = 20
|
||||
) -> List[dict]:
|
||||
"""Search parts with filters"""
|
||||
|
||||
def get_part_info(self, lcsc_number: str) -> dict:
|
||||
"""Get detailed info for specific part"""
|
||||
|
||||
def map_package_to_footprint(self, package: str) -> List[str]:
|
||||
"""Map JLCPCB package name to KiCAD footprint(s)"""
|
||||
# Example: "0603" → ["Resistor_SMD:R_0603_1608Metric",
|
||||
# "Capacitor_SMD:C_0603_1608Metric"]
|
||||
|
||||
def parse_description(self, description: str, category: str) -> dict:
|
||||
"""Extract parameters from description text"""
|
||||
# Example: "10kΩ ±1% 0.1W" → {resistance: "10k", tolerance: "1%", power: "0.1W"}
|
||||
|
||||
def suggest_alternatives(self, lcsc_number: str, limit: int = 5) -> List[dict]:
|
||||
"""Find similar parts (cheaper, more stock, Basic instead of Extended)"""
|
||||
```
|
||||
|
||||
**Package to Footprint Mapping:**
|
||||
```json
|
||||
{
|
||||
"0402": [
|
||||
"Resistor_SMD:R_0402_1005Metric",
|
||||
"Capacitor_SMD:C_0402_1005Metric",
|
||||
"LED_SMD:LED_0402_1005Metric"
|
||||
],
|
||||
"0603": [
|
||||
"Resistor_SMD:R_0603_1608Metric",
|
||||
"Capacitor_SMD:C_0603_1608Metric",
|
||||
"LED_SMD:LED_0603_1608Metric"
|
||||
],
|
||||
"0805": [
|
||||
"Resistor_SMD:R_0805_2012Metric",
|
||||
"Capacitor_SMD:C_0805_2012Metric"
|
||||
],
|
||||
"SOT-23": [
|
||||
"Package_TO_SOT_SMD:SOT-23",
|
||||
"Package_TO_SOT_SMD:SOT-23-3"
|
||||
],
|
||||
"SOIC-8": [
|
||||
"Package_SO:SOIC-8_3.9x4.9mm_P1.27mm"
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Phase 3: MCP Tools Integration (Day 3)
|
||||
|
||||
**File:** `src/tools/jlcpcb.ts`
|
||||
|
||||
**New MCP Tools:**
|
||||
|
||||
#### 1. `search_jlcpcb_parts`
|
||||
Search JLCPCB parts library by specifications.
|
||||
|
||||
```typescript
|
||||
{
|
||||
name: "search_jlcpcb_parts",
|
||||
description: "Search JLCPCB assembly parts by specifications",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
query: {
|
||||
type: "string",
|
||||
description: "Free-text search (e.g., '10k resistor 0603')"
|
||||
},
|
||||
category: {
|
||||
type: "string",
|
||||
description: "Category filter (e.g., 'Resistors', 'Capacitors')"
|
||||
},
|
||||
package: {
|
||||
type: "string",
|
||||
description: "Package filter (e.g., '0603', 'SOT-23')"
|
||||
},
|
||||
library_type: {
|
||||
type: "string",
|
||||
enum: ["Basic", "Extended", "All"],
|
||||
description: "Filter by library type (Basic = free assembly)"
|
||||
},
|
||||
in_stock: {
|
||||
type: "boolean",
|
||||
default: true,
|
||||
description: "Only show parts with available stock"
|
||||
},
|
||||
limit: {
|
||||
type: "number",
|
||||
default: 20,
|
||||
description: "Maximum results to return"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Example Usage:**
|
||||
```
|
||||
User: "Find me a 10k resistor, 0603 package, JLCPCB basic part"
|
||||
Claude: [uses search_jlcpcb_parts]
|
||||
Found 15 parts:
|
||||
1. C25804 - YAGEO RC0603FR-0710KL - 10kΩ ±1% 0.1W - Basic - $0.002 (15k in stock)
|
||||
2. C58972 - UNI-ROYAL 0603WAF1002T5E - 10kΩ ±1% 0.1W - Basic - $0.001 (50k in stock)
|
||||
...
|
||||
Recommended: C58972 (cheapest Basic part with high stock)
|
||||
```
|
||||
|
||||
#### 2. `get_jlcpcb_part`
|
||||
Get detailed information about a specific JLCPCB part.
|
||||
|
||||
```typescript
|
||||
{
|
||||
name: "get_jlcpcb_part",
|
||||
description: "Get detailed info for a specific JLCPCB part",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
lcsc_number: {
|
||||
type: "string",
|
||||
description: "LCSC part number (e.g., 'C25804')"
|
||||
}
|
||||
},
|
||||
required: ["lcsc_number"]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Returns:**
|
||||
```json
|
||||
{
|
||||
"lcsc": "C25804",
|
||||
"mfr_part": "RC0603FR-0710KL",
|
||||
"manufacturer": "YAGEO",
|
||||
"category": "Resistors / Chip Resistor - Surface Mount",
|
||||
"package": "0603",
|
||||
"description": "10kΩ ±1% 0.1W Thick Film Resistors",
|
||||
"library_type": "Basic",
|
||||
"stock": 15000,
|
||||
"price_breaks": [
|
||||
{"qty": 1, "price": "$0.002"},
|
||||
{"qty": 10, "price": "$0.0018"},
|
||||
{"qty": 100, "price": "$0.0015"}
|
||||
],
|
||||
"datasheet": "https://datasheet.lcsc.com/...",
|
||||
"kicad_footprints": [
|
||||
"Resistor_SMD:R_0603_1608Metric"
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
#### 3. Enhanced `place_component`
|
||||
Add JLCPCB integration to existing component placement.
|
||||
|
||||
```typescript
|
||||
// Add new optional parameter to place_component:
|
||||
{
|
||||
jlcpcb_part: {
|
||||
type: "string",
|
||||
description: "JLCPCB LCSC part number (e.g., 'C25804'). If provided, will use JLCPCB specs."
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Example:**
|
||||
```
|
||||
User: "Place a 10k resistor at 50, 40mm using JLCPCB part C25804"
|
||||
Claude: [uses place_component with jlcpcb_part="C25804"]
|
||||
- Looks up C25804 → finds package "0603"
|
||||
- Maps "0603" → "Resistor_SMD:R_0603_1608Metric"
|
||||
- Places component with:
|
||||
- Reference: R1
|
||||
- Value: 10k (C25804)
|
||||
- Footprint: Resistor_SMD:R_0603_1608Metric
|
||||
- Attribute: LCSC part C25804 stored in component properties
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Phase 4: Testing & Documentation (Day 4)
|
||||
|
||||
**Testing:**
|
||||
1. Download JLCPCB database (verify ~100k parts loaded)
|
||||
2. Test parametric search (resistors, capacitors, ICs)
|
||||
3. Test package mapping (0603 → correct footprints)
|
||||
4. Test component placement with JLCPCB parts
|
||||
5. Verify BOM export includes LCSC part numbers
|
||||
|
||||
**Documentation:**
|
||||
- User guide: How to get JLCPCB API key
|
||||
- Usage examples for each MCP tool
|
||||
- Best practices (prefer Basic parts, check stock)
|
||||
- BOM generation for JLCPCB assembly
|
||||
|
||||
---
|
||||
|
||||
## User Workflow Examples
|
||||
|
||||
### Example 1: Find and Place a Resistor
|
||||
```
|
||||
User: "I need a 10k pull-up resistor, 0603 size, cheapest JLCPCB basic part"
|
||||
|
||||
Claude: [uses search_jlcpcb_parts]
|
||||
query: "10k resistor"
|
||||
package: "0603"
|
||||
library_type: "Basic"
|
||||
|
||||
Found: C58972 - UNI-ROYAL 0603WAF1002T5E
|
||||
- 10kΩ ±1% 0.1W
|
||||
- Basic part (free assembly!)
|
||||
- $0.001 each
|
||||
- 50,000 in stock
|
||||
|
||||
User: "Perfect, place it at position 45, 30mm"
|
||||
|
||||
Claude: [uses place_component]
|
||||
componentId: "Resistor_SMD:R_0603_1608Metric"
|
||||
position: {x: 45, y: 30}
|
||||
reference: "R1"
|
||||
value: "10k (C58972)"
|
||||
jlcpcb_part: "C58972"
|
||||
|
||||
✅ Placed R1: 10k at (45, 30) mm
|
||||
JLCPCB: C58972 (Basic part, $0.001)
|
||||
```
|
||||
|
||||
### Example 2: Design a Cost-Optimized LED Circuit
|
||||
```
|
||||
User: "Design an LED circuit with current-limiting resistor, use only JLCPCB basic parts"
|
||||
|
||||
Claude: [searches for LED]
|
||||
Found: C2286 - Everlight 19-217/BHC-ZL1M2RY/3T (Red LED, 0603) - Basic - $0.015
|
||||
|
||||
[searches for resistor]
|
||||
Calculated: 330Ω for 5V → 20mA
|
||||
Found: C23138 - UNI-ROYAL 0603WAF3300T5E (330Ω, 0603) - Basic - $0.001
|
||||
|
||||
[places components]
|
||||
R1: 330Ω (C23138) at (40, 30) mm
|
||||
D1: Red LED (C2286) at (50, 30) mm
|
||||
|
||||
Total BOM cost: $0.016
|
||||
Both are Basic parts → Free assembly! 🎉
|
||||
```
|
||||
|
||||
### Example 3: Check Stock Before Ordering
|
||||
```
|
||||
User: "I need 100 of part C25804, is there enough stock?"
|
||||
|
||||
Claude: [uses get_jlcpcb_part lcsc_number="C25804"]
|
||||
Stock: 15,000 units
|
||||
✅ Plenty of stock for 100 units
|
||||
|
||||
Price for 100: $0.0015 each = $0.15 total
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## API Key Setup
|
||||
|
||||
**How to Get JLCPCB API Key:**
|
||||
|
||||
1. Visit JLCPCB website: https://jlcpcb.com/
|
||||
2. Log in to your account
|
||||
3. Go to: Account → API Management
|
||||
4. Click "Create API Key"
|
||||
5. Save your `appKey` and `appSecret`
|
||||
|
||||
**Configure in MCP:**
|
||||
|
||||
Option A: Environment variables (recommended)
|
||||
```bash
|
||||
export JLCPCB_API_KEY="your_app_key"
|
||||
export JLCPCB_API_SECRET="your_app_secret"
|
||||
```
|
||||
|
||||
Option B: Config file
|
||||
```json
|
||||
{
|
||||
"jlcpcb": {
|
||||
"api_key": "your_app_key",
|
||||
"api_secret": "your_app_secret",
|
||||
"cache_db": "~/.kicad-mcp/jlcpcb_parts.db"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Initial Setup:**
|
||||
```
|
||||
User: "Download the JLCPCB parts database"
|
||||
|
||||
Claude: [runs JLCPCB database download]
|
||||
Authenticating... ✅
|
||||
Fetching parts... (page 1/500)
|
||||
Fetching parts... (page 2/500)
|
||||
...
|
||||
✅ Downloaded 108,523 parts
|
||||
✅ Saved to ~/.kicad-mcp/jlcpcb_parts.db (42 MB)
|
||||
|
||||
Database ready! You can now search JLCPCB parts.
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Cost Optimization Features
|
||||
|
||||
### Prefer Basic Parts
|
||||
|
||||
```python
|
||||
def search_parts_optimized(self, specs: dict) -> List[dict]:
|
||||
"""
|
||||
Search with automatic Basic part preference.
|
||||
Returns Basic parts first, Extended parts only if no Basic match.
|
||||
"""
|
||||
basic_parts = self.search_parts(**specs, library_type="Basic")
|
||||
if basic_parts:
|
||||
return basic_parts
|
||||
return self.search_parts(**specs, library_type="Extended")
|
||||
```
|
||||
|
||||
### Calculate BOM Cost
|
||||
|
||||
```python
|
||||
def calculate_bom_cost(self, board: pcbnew.BOARD) -> dict:
|
||||
"""
|
||||
Calculate total cost for JLCPCB assembly.
|
||||
|
||||
Returns:
|
||||
{
|
||||
"total_parts_cost": 12.50,
|
||||
"basic_parts_count": 15,
|
||||
"extended_parts_count": 2,
|
||||
"extended_setup_fee": 6.00, # $3 per unique extended part
|
||||
"total_assembly_cost": 18.50
|
||||
}
|
||||
"""
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Integration with Existing Features
|
||||
|
||||
### BOM Export Enhancement
|
||||
|
||||
Update `export_bom` to include JLCPCB columns:
|
||||
|
||||
```csv
|
||||
Reference,Value,Footprint,LCSC Part,Library Type,Manufacturer,MFR Part,Stock
|
||||
R1,10k,Resistor_SMD:R_0603_1608Metric,C58972,Basic,UNI-ROYAL,0603WAF1002T5E,50000
|
||||
D1,Red,LED_SMD:LED_0603_1608Metric,C2286,Basic,Everlight,19-217/BHC-ZL1M2RY/3T,8000
|
||||
```
|
||||
|
||||
This BOM can be directly uploaded to JLCPCB for assembly!
|
||||
|
||||
---
|
||||
|
||||
## Database Update Strategy
|
||||
|
||||
**Initial Download:** ~5-10 minutes (108k parts)
|
||||
|
||||
**Incremental Updates:**
|
||||
- Run daily via cron/scheduled task
|
||||
- Only fetch parts modified since last update
|
||||
- Much faster (~30 seconds)
|
||||
|
||||
**Update Command:**
|
||||
```python
|
||||
# In Python
|
||||
jlcpcb_client.update_database(db_path)
|
||||
|
||||
# Via MCP tool
|
||||
update_jlcpcb_database(force=False) # Incremental
|
||||
update_jlcpcb_database(force=True) # Full re-download
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Success Metrics
|
||||
|
||||
**Implementation Complete When:**
|
||||
- ✅ Can download/cache full JLCPCB parts database
|
||||
- ✅ Parametric search works (resistors, capacitors, ICs)
|
||||
- ✅ Package → footprint mapping covers 90%+ of common parts
|
||||
- ✅ MCP tools integrated and tested end-to-end
|
||||
- ✅ BOM export includes LCSC part numbers
|
||||
- ✅ Documentation complete with examples
|
||||
|
||||
**User Experience Goal:**
|
||||
```
|
||||
User: "Design a board with an ESP32, USB-C connector, and LED,
|
||||
use only JLCPCB basic parts under $10 BOM"
|
||||
|
||||
Claude: [searches JLCPCB database]
|
||||
[places all components with real parts]
|
||||
[exports BOM ready for manufacturing]
|
||||
|
||||
✅ Board designed with 23 components
|
||||
💰 Total cost: $8.45
|
||||
🎉 All Basic parts (free assembly!)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Future Enhancements
|
||||
|
||||
**Post-MVP (v2.1+):**
|
||||
- LCSC API integration for extended parametric data
|
||||
- Digikey/Mouser fallback for non-JLCPCB parts
|
||||
- Part substitution suggestions (out of stock → alternatives)
|
||||
- Price history and trend analysis
|
||||
- Community-contributed package mappings
|
||||
- Visual part selection UI (if web interface added)
|
||||
|
||||
---
|
||||
|
||||
## Related Documentation
|
||||
|
||||
- [LIBRARY_INTEGRATION.md](./LIBRARY_INTEGRATION.md) - KiCAD footprint libraries
|
||||
- [REALTIME_WORKFLOW.md](./REALTIME_WORKFLOW.md) - MCP ↔ UI collaboration
|
||||
- [ROADMAP.md](./ROADMAP.md) - Overall project plan
|
||||
- [API.md](./API.md) - MCP API reference
|
||||
|
||||
---
|
||||
|
||||
**Status:** Ready to implement! 🚀
|
||||
**Next Step:** Get JLCPCB API credentials and start Phase 1
|
||||
18
docs/archive/README.md
Normal file
18
docs/archive/README.md
Normal file
@@ -0,0 +1,18 @@
|
||||
# Archived Documentation
|
||||
|
||||
This directory contains historical planning and session documents from the KiCAD MCP Server development. These documents record the design decisions and implementation progress for features that are now complete.
|
||||
|
||||
They are preserved for historical reference but are no longer maintained. For current documentation, see the [Documentation Index](../INDEX.md).
|
||||
|
||||
## Contents
|
||||
|
||||
- **SCHEMATIC_WIRING_PLAN.md** - Original plan for the intelligent wiring system (completed v2.1.0)
|
||||
- **SCHEMATIC_WORKFLOW_FIX.md** - Fix for broken schematic workflow, Issue #26 (completed v2.1.0)
|
||||
- **DYNAMIC_LIBRARY_LOADING_PLAN.md** - Plan for dynamic symbol loading (completed v2.1.0)
|
||||
- **DYNAMIC_LOADING_STATUS.md** - Status tracking for dynamic symbol loader (completed v2.1.0)
|
||||
- **JLCPCB_INTEGRATION_PLAN.md** - Original JLCPCB integration plan (completed v2.1.0)
|
||||
- **ROUTER_IMPLEMENTATION_STATUS.md** - Router pattern implementation progress (completed v2.0.0)
|
||||
- **IPC_API_MIGRATION_PLAN.md** - IPC backend migration plan (completed v2.0.0)
|
||||
- **BUILD_AND_TEST_SESSION.md** - Early build and test session notes
|
||||
- **WEEK1_SESSION1_SUMMARY.md** - Week 1 development session 1 notes
|
||||
- **WEEK1_SESSION2_SUMMARY.md** - Week 1 development session 2 notes
|
||||
222
docs/archive/ROUTER_IMPLEMENTATION_STATUS.md
Normal file
222
docs/archive/ROUTER_IMPLEMENTATION_STATUS.md
Normal file
@@ -0,0 +1,222 @@
|
||||
# Router Implementation Status
|
||||
|
||||
## ✅ Phase 1 Complete: Foundation & Infrastructure
|
||||
|
||||
**Date:** December 28, 2025
|
||||
|
||||
### What Was Implemented
|
||||
|
||||
#### 1. Tool Registry (`src/tools/registry.ts`)
|
||||
- ✅ Complete tool categorization (59 tools → 7 categories)
|
||||
- ✅ Direct tools list (12 high-frequency tools)
|
||||
- ✅ Category lookup maps for O(1) access
|
||||
- ✅ Tool search functionality
|
||||
- ✅ Registry statistics and metadata
|
||||
|
||||
#### 2. Router Tools (`src/tools/router.ts`)
|
||||
- ✅ `list_tool_categories` - Browse all categories
|
||||
- ✅ `get_category_tools` - View tools in a category
|
||||
- ✅ `execute_tool` - Execute any routed tool
|
||||
- ✅ `search_tools` - Search tools by keyword
|
||||
|
||||
#### 3. Server Integration (`src/server.ts`)
|
||||
- ✅ Router tools registered at server startup
|
||||
- ✅ All tools remain functional (backwards compatible)
|
||||
- ✅ Logging added for router pattern status
|
||||
|
||||
#### 4. Documentation
|
||||
- ✅ `TOOL_INVENTORY.md` - Complete tool catalog
|
||||
- ✅ `ROUTER_ARCHITECTURE.md` - Design specification
|
||||
- ✅ `ROUTER_IMPLEMENTATION_STATUS.md` - This file
|
||||
|
||||
### Current State
|
||||
|
||||
**Status:** ✅ **Router Infrastructure Complete**
|
||||
|
||||
**Build:** ✅ Compiles successfully (`npm run build`)
|
||||
|
||||
**Tool Count:**
|
||||
- Total Tools: 59 (ALL still registered and visible)
|
||||
- Direct Tools: 12
|
||||
- Routed Tools: 47
|
||||
- Router Tools: 4
|
||||
- **Currently Visible to Claude:** 63 tools (59 + 4 router)
|
||||
|
||||
**Token Impact:**
|
||||
- **Current:** ~42K tokens (still showing all tools)
|
||||
- **Target:** ~12K tokens (Phase 2 optimization)
|
||||
- **Potential Savings:** ~30K tokens (71% reduction)
|
||||
|
||||
## 🔄 Phase 2: Token Optimization (Next Step)
|
||||
|
||||
### Objective
|
||||
Hide routed tools from Claude's context while keeping them accessible via `execute_tool`.
|
||||
|
||||
### Two Approaches
|
||||
|
||||
#### Option A: Registration Filtering (Recommended)
|
||||
Modify tool registration to conditionally register tools based on whether they're in the direct list.
|
||||
|
||||
**Changes needed:**
|
||||
1. Update each `register*Tools` function to check `isDirectTool()`
|
||||
2. Only call `server.tool()` for direct tools
|
||||
3. Routed tools remain accessible via `execute_tool` calling `callKicadScript`
|
||||
|
||||
**Pros:**
|
||||
- Clean separation
|
||||
- True token savings
|
||||
- No behavior changes
|
||||
|
||||
**Cons:**
|
||||
- Requires modifying 9 tool files
|
||||
|
||||
#### Option B: MCP Filter (If Supported)
|
||||
If MCP SDK supports tool filtering/hiding, use that instead.
|
||||
|
||||
**Pros:**
|
||||
- No tool file changes
|
||||
- Centralized control
|
||||
|
||||
**Cons:**
|
||||
- May not be supported by SDK
|
||||
- Needs investigation
|
||||
|
||||
### Implementation Plan for Phase 2
|
||||
|
||||
1. **Create Helper Function** (`src/tools/conditional-register.ts`)
|
||||
```typescript
|
||||
export function registerToolConditionally(
|
||||
server: McpServer,
|
||||
toolName: string,
|
||||
definition: ToolDefinition,
|
||||
handler: Function
|
||||
) {
|
||||
if (isDirectTool(toolName)) {
|
||||
// Register with MCP (visible to Claude)
|
||||
server.tool(toolName, definition, handler);
|
||||
} else {
|
||||
// Register handler for execute_tool (hidden from Claude)
|
||||
registerToolHandler(toolName, handler);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
2. **Update Tool Registration Functions**
|
||||
Modify each `register*Tools` function to use conditional registration.
|
||||
|
||||
3. **Test**
|
||||
- Verify direct tools work normally
|
||||
- Verify routed tools work via `execute_tool`
|
||||
- Verify token count reduction
|
||||
|
||||
4. **Measure Impact**
|
||||
Count tools visible to Claude before/after.
|
||||
|
||||
## 📊 Categories & Distribution
|
||||
|
||||
| Category | Tools | Description |
|
||||
|----------|-------|-------------|
|
||||
| **board** | 9 | Board configuration, layers, zones, visualization |
|
||||
| **component** | 8 | Advanced component operations |
|
||||
| **export** | 8 | Manufacturing file generation |
|
||||
| **drc** | 9 | Design rule checking & validation |
|
||||
| **schematic** | 9 | Schematic editor operations |
|
||||
| **library** | 4 | Footprint library access |
|
||||
| **routing** | 3 | Advanced routing (vias, copper pours) |
|
||||
| **TOTAL** | **47** | **Routed tools** |
|
||||
| **direct** | **12** | **Always visible tools** |
|
||||
| **router** | **4** | **Discovery tools** |
|
||||
|
||||
## 🧪 Testing the Router
|
||||
|
||||
### Test 1: List Categories
|
||||
```
|
||||
User: "What tool categories are available?"
|
||||
|
||||
Expected: Claude calls list_tool_categories
|
||||
Result: Returns 7 categories with descriptions
|
||||
```
|
||||
|
||||
### Test 2: Browse Category
|
||||
```
|
||||
User: "What export tools are available?"
|
||||
|
||||
Expected: Claude calls get_category_tools({ category: "export" })
|
||||
Result: Returns 8 export tools
|
||||
```
|
||||
|
||||
### Test 3: Search Tools
|
||||
```
|
||||
User: "How do I export gerber files?"
|
||||
|
||||
Expected: Claude calls search_tools({ query: "gerber" })
|
||||
Result: Finds export_gerber in export category
|
||||
```
|
||||
|
||||
### Test 4: Execute Tool
|
||||
```
|
||||
User: "Export gerbers to ./output"
|
||||
|
||||
Expected: Claude calls execute_tool({
|
||||
tool_name: "export_gerber",
|
||||
params: { outputDir: "./output" }
|
||||
})
|
||||
Result: Executes via router, returns gerber export result
|
||||
```
|
||||
|
||||
## 📝 Benefits Achieved (Phase 1)
|
||||
|
||||
1. ✅ **Foundation Ready**: All infrastructure in place
|
||||
2. ✅ **Organized**: 59 tools categorized into logical groups
|
||||
3. ✅ **Discoverable**: Tools easily found via search/browse
|
||||
4. ✅ **Backwards Compatible**: All existing tools still work
|
||||
5. ✅ **Extensible**: Easy to add new tools and categories
|
||||
6. ✅ **Documented**: Complete architecture and usage docs
|
||||
|
||||
## 🚀 Next Actions
|
||||
|
||||
1. **Optional: Complete Phase 2** (Token Optimization)
|
||||
- Implement conditional registration
|
||||
- Hide routed tools from context
|
||||
- Achieve 71% token reduction
|
||||
|
||||
2. **Or: Ship Phase 1 As-Is**
|
||||
- Router tools work perfectly now
|
||||
- Users can discover and execute tools
|
||||
- Optimization can be done later
|
||||
- No breaking changes
|
||||
|
||||
## 📚 Related Files
|
||||
|
||||
- `src/tools/registry.ts` - Tool registry and categories
|
||||
- `src/tools/router.ts` - Router tool implementations
|
||||
- `src/server.ts` - Server integration
|
||||
- `docs/TOOL_INVENTORY.md` - Complete tool list
|
||||
- `docs/ROUTER_ARCHITECTURE.md` - Design specification
|
||||
- `docs/mcp-router-guide.md` - Original implementation guide
|
||||
|
||||
## 💡 Usage Example
|
||||
|
||||
```typescript
|
||||
// User: "I need to export gerber files"
|
||||
|
||||
// Claude's interaction:
|
||||
// 1. Sees "export" and "gerber" keywords
|
||||
// 2. Calls search_tools({ query: "gerber" })
|
||||
// → Returns: { category: "export", tool: "export_gerber", ... }
|
||||
// 3. Calls execute_tool({
|
||||
// tool_name: "export_gerber",
|
||||
// params: { outputDir: "./gerbers" }
|
||||
// })
|
||||
// → Executes and returns result
|
||||
// 4. "I've exported your Gerber files to ./gerbers/"
|
||||
```
|
||||
|
||||
## Status Summary
|
||||
|
||||
✅ **Router Pattern: IMPLEMENTED**
|
||||
✅ **Build: PASSING**
|
||||
✅ **Backwards Compatible: YES**
|
||||
⏳ **Token Optimization: PENDING (Phase 2)**
|
||||
|
||||
The router infrastructure is complete and functional. The system now supports tool discovery and organized access to all 59 tools. Phase 2 optimization (hiding routed tools) can be implemented when ready for maximum token savings.
|
||||
670
docs/archive/SCHEMATIC_WIRING_PLAN.md
Normal file
670
docs/archive/SCHEMATIC_WIRING_PLAN.md
Normal file
@@ -0,0 +1,670 @@
|
||||
# Schematic Wiring Implementation Plan
|
||||
|
||||
**Date:** 2026-01-10
|
||||
**Status:** Planning Phase
|
||||
**Priority:** HIGH (User-requested feature for Issue #26)
|
||||
|
||||
---
|
||||
|
||||
## Executive Summary
|
||||
|
||||
This plan outlines the implementation of complete schematic wiring functionality for the KiCAD MCP Server. Currently, component placement works perfectly with dynamic symbol loading, but wire/connection tools are incomplete or non-functional.
|
||||
|
||||
**Goal:** Enable users to create complete, functional schematics with wired connections between components through the MCP interface.
|
||||
|
||||
---
|
||||
|
||||
## Current State Analysis
|
||||
|
||||
### What Exists ✅
|
||||
|
||||
**Files:**
|
||||
- `python/commands/connection_schematic.py` - ConnectionManager class with wire/label methods
|
||||
- MCP handlers in `kicad_interface.py` for 6 connection-related tools
|
||||
|
||||
**MCP Tools (Registered):**
|
||||
1. `add_schematic_wire` - Add wire between two points
|
||||
2. `add_schematic_connection` - Connect two component pins
|
||||
3. `add_schematic_net_label` - Add net label
|
||||
4. `connect_to_net` - Connect pin to named net
|
||||
5. `get_net_connections` - Query net connections
|
||||
6. `generate_netlist` - Generate netlist from schematic
|
||||
|
||||
**ConnectionManager Methods:**
|
||||
- `add_wire(schematic, start_point, end_point)` - Add wire between coordinates
|
||||
- `add_connection(schematic, source_ref, source_pin, target_ref, target_pin)` - Connect pins
|
||||
- `add_net_label(schematic, net_name, position)` - Add label
|
||||
- `connect_to_net(schematic, component_ref, pin_name, net_name)` - Pin to net
|
||||
- `get_pin_location(symbol, pin_name)` - Get pin coordinates
|
||||
- `get_net_connections(schematic, net_name)` - Query connections
|
||||
- `generate_netlist(schematic)` - Generate netlist
|
||||
|
||||
### What's Broken/Missing ❌
|
||||
|
||||
**Problem 1: kicad-skip API Uncertainty**
|
||||
- Code assumes `schematic.wire.append()` exists
|
||||
- Code assumes `schematic.label.append()` exists
|
||||
- Code assumes pins have `.name` and `.location` attributes
|
||||
- **Need to verify what kicad-skip actually supports**
|
||||
|
||||
**Problem 2: Pin Location Calculation**
|
||||
- Current implementation tries to calculate absolute pin positions
|
||||
- May not account for symbol rotation
|
||||
- May not work with multi-unit symbols
|
||||
- Pin numbering vs pin naming confusion
|
||||
|
||||
**Problem 3: No Visual Feedback**
|
||||
- No way to verify wires were created correctly
|
||||
- No validation of wire endpoints
|
||||
- No checks for overlapping wires or junctions
|
||||
|
||||
**Problem 4: Limited Testing**
|
||||
- No integration tests for wiring functionality
|
||||
- No validation with real KiCad schematics
|
||||
- User reported `add_schematic_wire` fails
|
||||
|
||||
**Problem 5: Missing Features**
|
||||
- No junction (wire intersection) support
|
||||
- No bus support (multi-bit signals)
|
||||
- No no-connect flags
|
||||
- No power symbols (VCC, GND graphical symbols)
|
||||
- No hierarchical labels
|
||||
|
||||
---
|
||||
|
||||
## Technical Challenges
|
||||
|
||||
### Challenge 1: kicad-skip Wire API
|
||||
|
||||
**Issue:** The kicad-skip library documentation is sparse. We need to determine:
|
||||
- Does `schematic.wire` exist?
|
||||
- What's the correct API to add wires?
|
||||
- How are wires stored in .kicad_sch files?
|
||||
|
||||
**S-Expression Format (KiCad 8/9):**
|
||||
```lisp
|
||||
(wire (pts (xy 100 100) (xy 200 100))
|
||||
(stroke (width 0) (type default))
|
||||
(uuid "12345678-1234-1234-1234-123456789012")
|
||||
)
|
||||
```
|
||||
|
||||
**Approach:**
|
||||
1. Examine kicad-skip source code
|
||||
2. Test wire creation manually with kicad-skip
|
||||
3. Fall back to S-expression manipulation if necessary (similar to dynamic symbol loading)
|
||||
|
||||
### Challenge 2: Pin Location Discovery
|
||||
|
||||
**Issue:** Need to find exact pin coordinates for automatic wiring.
|
||||
|
||||
**Pin Data in Symbols:**
|
||||
Pins are defined within symbol definitions in lib_symbols, with coordinates relative to symbol origin. When symbol is placed, pins move with it.
|
||||
|
||||
**Required Information:**
|
||||
- Symbol position (x, y)
|
||||
- Symbol rotation angle
|
||||
- Pin offset from symbol origin
|
||||
- Pin number/name mapping
|
||||
|
||||
**Solution:**
|
||||
1. Parse symbol definition to find pin definitions
|
||||
2. Apply transformation matrix (position + rotation) to pin coordinates
|
||||
3. Return absolute pin position in schematic space
|
||||
|
||||
### Challenge 3: Smart Wire Routing
|
||||
|
||||
**Issue:** Users don't want to manually specify every wire segment.
|
||||
|
||||
**Desired Behavior:**
|
||||
```
|
||||
User: "Connect R1 pin 1 to C1 pin 1"
|
||||
System:
|
||||
- Calculate R1 pin 1 location: (100, 100)
|
||||
- Calculate C1 pin 1 location: (150, 120)
|
||||
- Create wire path (orthogonal routing preferred):
|
||||
- (100, 100) → (100, 120) → (150, 120)
|
||||
- Or simple direct: (100, 100) → (150, 120)
|
||||
```
|
||||
|
||||
**Auto-Routing Options:**
|
||||
1. **Direct** - Single wire segment (diagonal if needed)
|
||||
2. **Orthogonal** - Only horizontal/vertical segments (2 segments)
|
||||
3. **Manhattan** - Complex path avoiding components (3+ segments)
|
||||
|
||||
**Phase 1 Approach:** Start with direct wiring, add orthogonal later.
|
||||
|
||||
### Challenge 4: Net Label Integration
|
||||
|
||||
**Issue:** Labels need to attach to wires, not float in space.
|
||||
|
||||
**KiCad Behavior:**
|
||||
- Labels must touch a wire or pin
|
||||
- Labels create electrical connections at their attachment point
|
||||
- Multiple labels with same name = connected net
|
||||
|
||||
**Implementation:**
|
||||
- When adding label, find nearest wire endpoint
|
||||
- Attach label to that coordinate
|
||||
- Or create short wire stub for label attachment
|
||||
|
||||
---
|
||||
|
||||
## Implementation Phases
|
||||
|
||||
### Phase 1: Core Wire Functionality (Week 1)
|
||||
|
||||
**Goal:** Get basic wiring working with kicad-skip API
|
||||
|
||||
**Tasks:**
|
||||
|
||||
1. **Research kicad-skip Wire API** (4 hours)
|
||||
- Read kicad-skip source code
|
||||
- Test wire creation with Python REPL
|
||||
- Document actual API methods
|
||||
- Create test schematic with manual wires
|
||||
|
||||
2. **Fix Wire Creation** (6 hours)
|
||||
- Update ConnectionManager.add_wire() with correct API
|
||||
- Handle S-expression manipulation if needed
|
||||
- Add UUID generation for wires
|
||||
- Test with simple wire (100,100) → (200,100)
|
||||
|
||||
3. **Implement Pin Discovery** (8 hours)
|
||||
- Parse symbol definitions to extract pin data
|
||||
- Handle pin coordinates relative to symbol
|
||||
- Apply rotation transformation
|
||||
- Test with R, C, LED from dynamic symbols
|
||||
|
||||
4. **Fix add_schematic_connection** (4 hours)
|
||||
- Use correct pin discovery
|
||||
- Create direct wire between pins
|
||||
- Handle error cases (pin not found, etc.)
|
||||
- Test with R1 pin 2 → C1 pin 1
|
||||
|
||||
5. **Integration Testing** (4 hours)
|
||||
- Create test schematic with R, C, LED
|
||||
- Wire R to C
|
||||
- Wire C to LED
|
||||
- Verify schematic opens in KiCad
|
||||
- Verify electrical connectivity
|
||||
|
||||
**Deliverables:**
|
||||
- Working `add_schematic_wire` tool
|
||||
- Working `add_schematic_connection` tool
|
||||
- Pin location discovery working
|
||||
- Integration test passing
|
||||
- Documentation updated
|
||||
|
||||
**Success Criteria:**
|
||||
- User can connect two resistor pins with MCP command
|
||||
- Wire appears in KiCad schematic viewer
|
||||
- Netlist shows electrical connection
|
||||
|
||||
---
|
||||
|
||||
### Phase 2: Net Labels & Named Nets (Week 1-2)
|
||||
|
||||
**Goal:** Enable named net connections (VCC, GND, etc.)
|
||||
|
||||
**Tasks:**
|
||||
|
||||
1. **Fix Net Label Creation** (4 hours)
|
||||
- Update ConnectionManager.add_net_label()
|
||||
- Use correct kicad-skip API or S-expression
|
||||
- Position labels correctly
|
||||
- Test label creation
|
||||
|
||||
2. **Implement connect_to_net** (6 hours)
|
||||
- Create wire stub from pin
|
||||
- Attach label to wire endpoint
|
||||
- Support common nets (VCC, GND, 3V3, etc.)
|
||||
- Test with multiple components on same net
|
||||
|
||||
3. **Net Connection Discovery** (6 hours)
|
||||
- Parse wires and labels in schematic
|
||||
- Build connectivity graph
|
||||
- Implement get_net_connections()
|
||||
- Return all pins on a net
|
||||
|
||||
4. **Power Symbol Support** (8 hours)
|
||||
- Add power symbols to templates (VCC, GND, 3V3, 5V)
|
||||
- Or dynamically load from power library
|
||||
- Connect power pins to power nets
|
||||
- Test complete circuit with power
|
||||
|
||||
5. **Testing** (4 hours)
|
||||
- Create circuit with VCC, GND nets
|
||||
- Connect multiple components to each net
|
||||
- Verify net connectivity
|
||||
- Generate and validate netlist
|
||||
|
||||
**Deliverables:**
|
||||
- Working `add_schematic_net_label` tool
|
||||
- Working `connect_to_net` tool
|
||||
- Working `get_net_connections` tool
|
||||
- Power symbol support
|
||||
- Netlist generation working
|
||||
|
||||
**Success Criteria:**
|
||||
- User can label nets VCC, GND
|
||||
- Multiple components connect to same net
|
||||
- Netlist correctly shows net membership
|
||||
|
||||
---
|
||||
|
||||
### Phase 3: Advanced Features (Week 2-3)
|
||||
|
||||
**Goal:** Professional schematic features
|
||||
|
||||
**Tasks:**
|
||||
|
||||
1. **Junction Support** (4 hours)
|
||||
- Detect wire intersections
|
||||
- Add junction dots at T-junctions
|
||||
- S-expression: `(junction (at x y) (diameter 0) (uuid ...))`
|
||||
|
||||
2. **No-Connect Flags** (2 hours)
|
||||
- Add "X" marks on unused pins
|
||||
- S-expression: `(no_connect (at x y) (uuid ...))`
|
||||
|
||||
3. **Orthogonal Routing** (6 hours)
|
||||
- Implement 2-segment wire routing
|
||||
- Horizontal-then-vertical or vertical-then-horizontal
|
||||
- Choose best path based on pin positions
|
||||
|
||||
4. **Bus Support** (8 hours)
|
||||
- Multi-bit signal buses
|
||||
- Bus labels (e.g., "D[0..7]")
|
||||
- Bus entries for individual signals
|
||||
|
||||
5. **Hierarchical Labels** (8 hours)
|
||||
- Labels for hierarchical sheets
|
||||
- Input/Output/Bidirectional types
|
||||
- Sheet connections
|
||||
|
||||
**Deliverables:**
|
||||
- Junction creation
|
||||
- No-connect support
|
||||
- Smart orthogonal routing
|
||||
- Bus and hierarchical label support
|
||||
|
||||
**Success Criteria:**
|
||||
- Wires route cleanly around components
|
||||
- Junctions appear at wire intersections
|
||||
- Unused pins marked with no-connect
|
||||
|
||||
---
|
||||
|
||||
### Phase 4: Validation & Polish (Week 3-4)
|
||||
|
||||
**Goal:** Production-ready reliability
|
||||
|
||||
**Tasks:**
|
||||
|
||||
1. **ERC Integration** (6 hours)
|
||||
- Electrical Rule Check
|
||||
- Detect floating nets
|
||||
- Detect unconnected pins
|
||||
- Detect short circuits
|
||||
|
||||
2. **Visual Validation** (4 hours)
|
||||
- Export schematic to PDF after wiring
|
||||
- Verify wire appearance
|
||||
- Check net label placement
|
||||
|
||||
3. **Comprehensive Testing** (8 hours)
|
||||
- Test with Device library components
|
||||
- Test with IC components (multi-pin)
|
||||
- Test with connectors
|
||||
- Test complex circuits (10+ components)
|
||||
|
||||
4. **Error Handling** (4 hours)
|
||||
- Graceful failures
|
||||
- Clear error messages
|
||||
- Validation of coordinates
|
||||
- Duplicate net label detection
|
||||
|
||||
5. **Documentation** (6 hours)
|
||||
- Update MCP tool descriptions
|
||||
- Add usage examples to README
|
||||
- Create wiring tutorial
|
||||
- Add to CHANGELOG
|
||||
|
||||
**Deliverables:**
|
||||
- ERC validation
|
||||
- Comprehensive test suite
|
||||
- Error handling
|
||||
- Complete documentation
|
||||
|
||||
**Success Criteria:**
|
||||
- 95%+ test pass rate
|
||||
- Users can create functional circuits
|
||||
- Clear error messages on failures
|
||||
|
||||
---
|
||||
|
||||
## Technical Approach
|
||||
|
||||
### Option A: Use kicad-skip Native API (Preferred)
|
||||
|
||||
**If kicad-skip supports wires natively:**
|
||||
|
||||
```python
|
||||
# Add wire using native API
|
||||
wire = schematic.wire.new(
|
||||
start=[100, 100],
|
||||
end=[200, 100]
|
||||
)
|
||||
|
||||
# Add label
|
||||
label = schematic.label.new(
|
||||
text="VCC",
|
||||
at=[150, 100]
|
||||
)
|
||||
```
|
||||
|
||||
**Pros:**
|
||||
- Clean, maintainable code
|
||||
- Follows library patterns
|
||||
- Less likely to break
|
||||
|
||||
**Cons:**
|
||||
- Depends on kicad-skip having these features
|
||||
- May be limited in functionality
|
||||
|
||||
### Option B: S-Expression Manipulation (Fallback)
|
||||
|
||||
**If kicad-skip doesn't support wires:**
|
||||
|
||||
Use the same approach as dynamic symbol loading:
|
||||
|
||||
```python
|
||||
import sexpdata
|
||||
from sexpdata import Symbol
|
||||
|
||||
# Read schematic
|
||||
with open(schematic_path, 'r') as f:
|
||||
sch_data = sexpdata.loads(f.read())
|
||||
|
||||
# Create wire S-expression
|
||||
wire_sexp = [
|
||||
Symbol('wire'),
|
||||
[Symbol('pts'),
|
||||
[Symbol('xy'), 100, 100],
|
||||
[Symbol('xy'), 200, 100]
|
||||
],
|
||||
[Symbol('stroke'), [Symbol('width'), 0], [Symbol('type'), Symbol('default')]],
|
||||
[Symbol('uuid'), str(uuid.uuid4())]
|
||||
]
|
||||
|
||||
# Insert into schematic
|
||||
sch_data.append(wire_sexp)
|
||||
|
||||
# Write back
|
||||
with open(schematic_path, 'w') as f:
|
||||
f.write(sexpdata.dumps(sch_data))
|
||||
```
|
||||
|
||||
**Pros:**
|
||||
- Complete control
|
||||
- Can implement any feature
|
||||
- Works around library limitations
|
||||
|
||||
**Cons:**
|
||||
- More complex
|
||||
- Requires deep KiCad format knowledge
|
||||
- More maintenance
|
||||
|
||||
### Hybrid Approach (Recommended)
|
||||
|
||||
1. Try kicad-skip native API first
|
||||
2. Fall back to S-expression if needed
|
||||
3. Use S-expression for advanced features (junctions, buses)
|
||||
|
||||
---
|
||||
|
||||
## Pin Discovery Algorithm
|
||||
|
||||
### Step 1: Get Symbol Definition
|
||||
|
||||
Symbols are stored in `lib_symbols` section:
|
||||
|
||||
```lisp
|
||||
(lib_symbols
|
||||
(symbol "Device:R"
|
||||
(symbol "R_0_1"
|
||||
(rectangle (start -1 -2.54) (end 1 2.54) ...))
|
||||
(symbol "R_1_1"
|
||||
(pin passive line (at 0 3.81 270) (length 1.27)
|
||||
(name "~" (effects (font (size 1.27 1.27))))
|
||||
(number "1" (effects (font (size 1.27 1.27)))))
|
||||
(pin passive line (at 0 -3.81 90) (length 1.27)
|
||||
(name "~" (effects (font (size 1.27 1.27))))
|
||||
(number "2" (effects (font (size 1.27 1.27)))))))
|
||||
```
|
||||
|
||||
### Step 2: Extract Pin Information
|
||||
|
||||
For each pin:
|
||||
- Number (e.g., "1", "2")
|
||||
- Name (e.g., "GND", "VCC", "~" for unnamed)
|
||||
- Position relative to symbol origin: `(at x y angle)`
|
||||
- Length (distance from symbol body to connection point)
|
||||
|
||||
### Step 3: Get Symbol Instance Position
|
||||
|
||||
From symbol instance in schematic:
|
||||
|
||||
```lisp
|
||||
(symbol (lib_id "Device:R") (at 100 100 0) (unit 1)
|
||||
(property "Reference" "R1" ...))
|
||||
```
|
||||
|
||||
Extract:
|
||||
- Position: `(at 100 100 0)` = x=100, y=100, rotation=0°
|
||||
- Reference: "R1"
|
||||
|
||||
### Step 4: Calculate Absolute Pin Position
|
||||
|
||||
```python
|
||||
def get_absolute_pin_position(symbol_instance, pin_definition):
|
||||
# Symbol position
|
||||
symbol_x, symbol_y, symbol_rotation = symbol_instance.at.value
|
||||
|
||||
# Pin position relative to symbol
|
||||
pin_x, pin_y, pin_angle = pin_definition.at.value
|
||||
|
||||
# Apply rotation transformation
|
||||
if symbol_rotation != 0:
|
||||
# Rotate pin coordinates around origin
|
||||
rad = math.radians(symbol_rotation)
|
||||
rotated_x = pin_x * math.cos(rad) - pin_y * math.sin(rad)
|
||||
rotated_y = pin_x * math.sin(rad) + pin_y * math.cos(rad)
|
||||
pin_x, pin_y = rotated_x, rotated_y
|
||||
|
||||
# Translate to absolute position
|
||||
abs_x = symbol_x + pin_x
|
||||
abs_y = symbol_y + pin_y
|
||||
|
||||
return [abs_x, abs_y]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Wire Routing Strategies
|
||||
|
||||
### Strategy 1: Direct Wire (Phase 1)
|
||||
|
||||
Simplest: single wire segment from pin A to pin B.
|
||||
|
||||
```
|
||||
R1 pin 2 C1 pin 1
|
||||
o-------------o
|
||||
```
|
||||
|
||||
**Pros:** Simple, fast
|
||||
**Cons:** Diagonal wires (not standard practice)
|
||||
|
||||
### Strategy 2: Orthogonal 2-Segment (Phase 3)
|
||||
|
||||
Two segments: horizontal then vertical, or vertical then horizontal.
|
||||
|
||||
```
|
||||
R1 pin 2 C1 pin 1
|
||||
o-----┐
|
||||
│
|
||||
└------o
|
||||
```
|
||||
|
||||
**Algorithm:**
|
||||
1. Calculate midpoint
|
||||
2. Route horizontal to midpoint
|
||||
3. Route vertical to target
|
||||
4. Or vice versa based on direction
|
||||
|
||||
**Pros:** Standard practice, cleaner schematics
|
||||
**Cons:** Slightly more complex
|
||||
|
||||
### Strategy 3: Manhattan Routing (Future)
|
||||
|
||||
Complex multi-segment paths avoiding components.
|
||||
|
||||
**Pros:** Professional appearance
|
||||
**Cons:** Requires collision detection, path planning
|
||||
|
||||
---
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
### Unit Tests
|
||||
|
||||
Test individual functions:
|
||||
- `test_add_wire()` - Wire creation
|
||||
- `test_get_pin_location()` - Pin discovery
|
||||
- `test_add_net_label()` - Label creation
|
||||
- `test_calculate_pin_position()` - Coordinate math
|
||||
|
||||
### Integration Tests
|
||||
|
||||
Test complete workflows:
|
||||
- `test_connect_two_resistors()` - Wire R1 to R2
|
||||
- `test_connect_to_vcc_net()` - Multiple components to VCC
|
||||
- `test_generate_netlist()` - Netlist accuracy
|
||||
- `test_schematic_opens_in_kicad()` - File validity
|
||||
|
||||
### Manual Validation
|
||||
|
||||
- Create test schematic in KiCad manually
|
||||
- Add same connections via MCP
|
||||
- Compare results
|
||||
- Verify electrical connectivity in KiCad
|
||||
|
||||
---
|
||||
|
||||
## Success Metrics
|
||||
|
||||
### Phase 1 Success:
|
||||
- [ ] `add_schematic_wire` works (coordinates)
|
||||
- [ ] `add_schematic_connection` works (pin to pin)
|
||||
- [ ] Wires appear in KiCad schematic
|
||||
- [ ] Netlist shows connections
|
||||
- [ ] 3+ integration tests passing
|
||||
|
||||
### Phase 2 Success:
|
||||
- [ ] Net labels work (VCC, GND, etc.)
|
||||
- [ ] Multiple components on same net
|
||||
- [ ] `get_net_connections` returns correct results
|
||||
- [ ] Netlist includes named nets
|
||||
- [ ] 5+ integration tests passing
|
||||
|
||||
### Phase 3 Success:
|
||||
- [ ] Junctions at wire intersections
|
||||
- [ ] Orthogonal routing preferred
|
||||
- [ ] No-connect flags on unused pins
|
||||
- [ ] 10+ integration tests passing
|
||||
|
||||
### Phase 4 Success:
|
||||
- [ ] ERC detects errors
|
||||
- [ ] 95%+ test coverage
|
||||
- [ ] Complete documentation
|
||||
- [ ] User can create functional circuits without errors
|
||||
|
||||
---
|
||||
|
||||
## Risk Assessment
|
||||
|
||||
| Risk | Probability | Impact | Mitigation |
|
||||
|------|------------|--------|------------|
|
||||
| kicad-skip lacks wire API | High | High | Use S-expression fallback |
|
||||
| Pin discovery complex | Medium | Medium | Test with multiple symbol types |
|
||||
| Rotation math errors | Medium | High | Extensive testing, validation |
|
||||
| Performance issues | Low | Medium | Optimize S-expression parsing |
|
||||
| KiCad format changes | Low | High | Version detection, compatibility |
|
||||
|
||||
---
|
||||
|
||||
## Dependencies
|
||||
|
||||
**Required:**
|
||||
- kicad-skip >= 0.1.0 (or compatible)
|
||||
- sexpdata (already dependency for dynamic loading)
|
||||
- Python 3.8+
|
||||
|
||||
**Optional:**
|
||||
- KiCad CLI for validation (`kicad-cli sch export netlist`)
|
||||
|
||||
---
|
||||
|
||||
## Timeline Estimate
|
||||
|
||||
**Phase 1:** 1 week (26 hours)
|
||||
**Phase 2:** 1 week (28 hours)
|
||||
**Phase 3:** 1.5 weeks (28 hours)
|
||||
**Phase 4:** 1.5 weeks (28 hours)
|
||||
|
||||
**Total:** 5 weeks (110 hours)
|
||||
|
||||
**Accelerated path (core features only):** 2-3 weeks (Phases 1-2)
|
||||
|
||||
---
|
||||
|
||||
## Next Immediate Steps
|
||||
|
||||
1. **Research kicad-skip Wire API** (TODAY)
|
||||
- Test with Python REPL
|
||||
- Document findings
|
||||
- Choose implementation approach
|
||||
|
||||
2. **Create Test Environment** (TOMORROW)
|
||||
- Set up test schematic
|
||||
- Manual wire creation in KiCad
|
||||
- Export for comparison
|
||||
|
||||
3. **Implement Basic Wire** (THIS WEEK)
|
||||
- Update ConnectionManager.add_wire()
|
||||
- Test with simple coordinates
|
||||
- Verify in KiCad
|
||||
|
||||
4. **Fix Pin Discovery** (THIS WEEK)
|
||||
- Parse symbol definitions
|
||||
- Calculate absolute positions
|
||||
- Test with rotated symbols
|
||||
|
||||
---
|
||||
|
||||
## User Communication
|
||||
|
||||
**For Issue #26:**
|
||||
|
||||
Update users that:
|
||||
- ✅ Component placement is DONE (with 10,000+ symbols)
|
||||
- ⏳ Wire/connection tools are IN PROGRESS
|
||||
- 📅 Estimated completion: 2-3 weeks for core functionality
|
||||
- 🎯 Goal: Complete functional schematics with wiring
|
||||
|
||||
---
|
||||
|
||||
**Status:** Ready for implementation
|
||||
**Owner:** TBD
|
||||
**Priority:** HIGH (user-blocking feature)
|
||||
125
docs/archive/SCHEMATIC_WORKFLOW_FIX.md
Normal file
125
docs/archive/SCHEMATIC_WORKFLOW_FIX.md
Normal file
@@ -0,0 +1,125 @@
|
||||
# Schematic Workflow Fix - Issue #26
|
||||
|
||||
## Problem Summary
|
||||
|
||||
The schematic workflow was completely broken due to incorrect usage of the kicad-skip library:
|
||||
|
||||
1. **`create_project`** only created PCB files, no schematic
|
||||
2. **`create_schematic`** created orphaned schematic files not linked to projects
|
||||
3. **`add_schematic_component`** called non-existent `schematic.add_symbol()` method
|
||||
4. Project files didn't reference schematics in their structure
|
||||
|
||||
## Root Cause
|
||||
|
||||
The kicad-skip library **does not support creating symbols from scratch**. The only way to add symbols is by **cloning existing symbol instances**.
|
||||
|
||||
From kicad-skip documentation:
|
||||
> "symbols: these don't have a new()" because they require complex mappings to library elements, pins, and properties.
|
||||
|
||||
## Solution
|
||||
|
||||
### 1. Template-Based Approach
|
||||
|
||||
Created a template schematic (`python/templates/template_with_symbols.kicad_sch`) with:
|
||||
- Complete `lib_symbols` section defining R, C, LED symbols
|
||||
- Three template symbol instances placed off-screen at (-100, -110, -120)
|
||||
- Template symbols marked as `dnp yes`, `in_bom no`, `on_board no` so they don't interfere
|
||||
|
||||
### 2. Updated Files
|
||||
|
||||
**python/commands/project.py:**
|
||||
- Now creates both `.kicad_pcb` AND `.kicad_sch` files
|
||||
- Project file includes schematic reference in `sheets` array
|
||||
- Copies template schematic with cloneable symbols
|
||||
|
||||
**python/commands/schematic.py:**
|
||||
- Uses template file instead of creating from scratch
|
||||
- Proper minimal schematic structure when template unavailable
|
||||
|
||||
**python/commands/component_schematic.py:**
|
||||
- Completely rewritten to use `clone()` API
|
||||
- Maps component types to template symbols
|
||||
- Proper UUID generation for each cloned symbol
|
||||
- Correct position setting: `symbol.at.value = [x, y, rotation]`
|
||||
|
||||
### 3. Correct Workflow
|
||||
|
||||
```python
|
||||
from commands.project import ProjectCommands
|
||||
from commands.schematic import SchematicManager
|
||||
from commands.component_schematic import ComponentManager
|
||||
|
||||
# Step 1: Create project (creates both PCB and schematic)
|
||||
project_cmd = ProjectCommands()
|
||||
result = project_cmd.create_project({
|
||||
"name": "MyProject",
|
||||
"path": "/path/to/project"
|
||||
})
|
||||
|
||||
# Step 2: Load the schematic
|
||||
sch = SchematicManager.load_schematic(result['project']['schematicPath'])
|
||||
|
||||
# Step 3: Add components by cloning templates
|
||||
component_def = {
|
||||
"type": "R", # Maps to _TEMPLATE_R
|
||||
"reference": "R1", # Component reference
|
||||
"value": "10k", # Component value
|
||||
"footprint": "Resistor_SMD:R_0603_1608Metric",
|
||||
"x": 50.8, # Position in mm
|
||||
"y": 50.8, # Position in mm
|
||||
"rotation": 0 # Rotation in degrees
|
||||
}
|
||||
symbol = ComponentManager.add_component(sch, component_def)
|
||||
|
||||
# Step 4: Save the schematic
|
||||
SchematicManager.save_schematic(sch, result['project']['schematicPath'])
|
||||
```
|
||||
|
||||
## Supported Component Types
|
||||
|
||||
Currently supported template symbols:
|
||||
- `R` - Resistor (maps to `_TEMPLATE_R`)
|
||||
- `C` - Capacitor (maps to `_TEMPLATE_C`)
|
||||
- `D` or `LED` - LED (maps to `_TEMPLATE_D`)
|
||||
|
||||
To add more component types, update:
|
||||
1. `python/templates/template_with_symbols.kicad_sch` - Add lib_symbol definition and template instance
|
||||
2. `python/commands/component_schematic.py` - Add mapping in `TEMPLATE_MAP`
|
||||
|
||||
## Testing
|
||||
|
||||
Comprehensive test created at `/tmp/test_schematic_workflow.py`:
|
||||
- Creates project with schematic
|
||||
- Loads schematic
|
||||
- Adds R, C, LED components
|
||||
- Saves schematic
|
||||
- Validates with `kicad-cli sch export pdf`
|
||||
|
||||
All tests passing ✓
|
||||
|
||||
## Files Modified
|
||||
|
||||
- `python/commands/project.py` - Added schematic creation
|
||||
- `python/commands/schematic.py` - Fixed template usage
|
||||
- `python/commands/component_schematic.py` - Rewritten to use clone() API
|
||||
- `python/templates/empty.kicad_sch` - Minimal template (created)
|
||||
- `python/templates/template_with_symbols.kicad_sch` - Template with cloneable symbols (created)
|
||||
|
||||
## Limitations
|
||||
|
||||
1. Can only add components that have templates defined
|
||||
2. Template symbols remain in schematic (but marked as DNP/not in BOM)
|
||||
3. Complex symbols (multi-unit, hierarchical) may need custom templates
|
||||
|
||||
## Future Improvements
|
||||
|
||||
1. Add more component templates (transistors, connectors, ICs)
|
||||
2. Dynamic template generation from KiCad symbol libraries
|
||||
3. Auto-hide template symbols in schematic
|
||||
4. Support for custom user templates
|
||||
|
||||
## References
|
||||
|
||||
- GitHub Issue: #26
|
||||
- kicad-skip documentation: https://github.com/psychogenic/kicad-skip
|
||||
- Test results: `/tmp/test_schematic_workflow/`
|
||||
505
docs/archive/WEEK1_SESSION1_SUMMARY.md
Normal file
505
docs/archive/WEEK1_SESSION1_SUMMARY.md
Normal file
@@ -0,0 +1,505 @@
|
||||
# Week 1 - Session 1 Summary
|
||||
**Date:** October 25, 2025
|
||||
**Status:** ✅ **EXCELLENT PROGRESS**
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Mission
|
||||
|
||||
Resurrect the KiCAD MCP Server and transform it from a Windows-only "KiCAD automation wrapper" into a **true AI-assisted PCB design companion** for hobbyist users (novice to intermediate).
|
||||
|
||||
**Strategic Focus:**
|
||||
- Linux-first platform support
|
||||
- JLCPCB & Digikey integration
|
||||
- End-to-end PCB design workflow
|
||||
- Migrate to KiCAD IPC API (future-proof)
|
||||
|
||||
---
|
||||
|
||||
## ✅ What We Accomplished Today
|
||||
|
||||
### 1. **Complete Project Analysis** 📊
|
||||
|
||||
Created comprehensive documentation:
|
||||
- ✅ Full codebase exploration (6 tool categories, 9 Python command modules)
|
||||
- ✅ Identified critical issues (deprecated SWIG API, Windows-only paths)
|
||||
- ✅ Researched KiCAD IPC API, JLCPCB API, Digikey API
|
||||
- ✅ Researched MCP best practices
|
||||
|
||||
**Key Findings:**
|
||||
- SWIG Python bindings are DEPRECATED (will be removed in KiCAD 10.0)
|
||||
- Current architecture works but is Windows-centric
|
||||
- Missing core AI-assisted features (part selection, BOM management)
|
||||
|
||||
---
|
||||
|
||||
### 2. **12-Week Rebuild Plan Created** 🗺️
|
||||
|
||||
Designed comprehensive roadmap in 4 phases:
|
||||
|
||||
#### **Phase 1: Foundation & Migration (Weeks 1-4)**
|
||||
- Linux compatibility
|
||||
- KiCAD IPC API migration
|
||||
- Performance improvements (caching, async)
|
||||
|
||||
#### **Phase 2: Core AI Features (Weeks 5-8)**
|
||||
- JLCPCB integration (parts library + pricing)
|
||||
- Digikey integration (parametric search)
|
||||
- Smart BOM management
|
||||
- Design pattern library
|
||||
|
||||
#### **Phase 3: Novice-Friendly Workflows (Weeks 9-11)**
|
||||
- Guided step-by-step workflows
|
||||
- Visual feedback system
|
||||
- Intelligent error recovery
|
||||
|
||||
#### **Phase 4: Polish & Launch (Week 12)**
|
||||
- Testing, documentation, community building
|
||||
|
||||
---
|
||||
|
||||
### 3. **Linux Compatibility Infrastructure** 🐧
|
||||
|
||||
Created complete cross-platform support:
|
||||
|
||||
**Files Created:**
|
||||
- ✅ `docs/LINUX_COMPATIBILITY_AUDIT.md` - Comprehensive audit report
|
||||
- ✅ `python/utils/platform_helper.py` - Cross-platform path detection
|
||||
- ✅ `config/linux-config.example.json` - Linux configuration template
|
||||
- ✅ `config/windows-config.example.json` - Windows configuration template
|
||||
- ✅ `config/macos-config.example.json` - macOS configuration template
|
||||
|
||||
**Platform Helper Features:**
|
||||
```python
|
||||
PlatformHelper.get_config_dir() # ~/.config/kicad-mcp on Linux
|
||||
PlatformHelper.get_log_dir() # ~/.config/kicad-mcp/logs
|
||||
PlatformHelper.get_cache_dir() # ~/.cache/kicad-mcp
|
||||
PlatformHelper.get_kicad_python_paths() # Auto-detects KiCAD install
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 4. **CI/CD Pipeline** 🚀
|
||||
|
||||
Created GitHub Actions workflow:
|
||||
|
||||
**File:** `.github/workflows/ci.yml`
|
||||
|
||||
**Testing Matrix:**
|
||||
- TypeScript build on Ubuntu 24.04, 22.04, Windows, macOS
|
||||
- Python tests on Python 3.10, 3.11, 3.12
|
||||
- Integration tests with KiCAD 9.0 installation
|
||||
- Code quality checks (ESLint, Prettier, Black, MyPy)
|
||||
- Docker build test (future)
|
||||
- Coverage reporting to Codecov
|
||||
|
||||
**Status:** Ready to run on next git push
|
||||
|
||||
---
|
||||
|
||||
### 5. **Python Testing Framework** 🧪
|
||||
|
||||
Set up comprehensive testing infrastructure:
|
||||
|
||||
**Files Created:**
|
||||
- ✅ `pytest.ini` - Pytest configuration
|
||||
- ✅ `requirements.txt` - Production dependencies
|
||||
- ✅ `requirements-dev.txt` - Development dependencies
|
||||
- ✅ `tests/test_platform_helper.py` - 20+ unit tests
|
||||
|
||||
**Test Categories:**
|
||||
```python
|
||||
@pytest.mark.unit # Fast, no external dependencies
|
||||
@pytest.mark.integration # Requires KiCAD
|
||||
@pytest.mark.linux # Linux-specific tests
|
||||
@pytest.mark.windows # Windows-specific tests
|
||||
```
|
||||
|
||||
**Test Results:**
|
||||
```
|
||||
✅ Platform detection works correctly
|
||||
✅ Config directories follow XDG spec on Linux
|
||||
✅ Python 3.12.3 detected correctly
|
||||
✅ Paths created automatically
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 6. **Developer Documentation** 📚
|
||||
|
||||
Created contributor guide:
|
||||
|
||||
**File:** `CONTRIBUTING.md`
|
||||
|
||||
**Includes:**
|
||||
- Platform-specific setup instructions (Linux/Windows/macOS)
|
||||
- Project structure overview
|
||||
- Development workflow
|
||||
- Testing guide
|
||||
- Code style guidelines (Black, MyPy, ESLint)
|
||||
- Pull request process
|
||||
|
||||
---
|
||||
|
||||
### 7. **Dependencies Management** 📦
|
||||
|
||||
**Production Dependencies (requirements.txt):**
|
||||
```
|
||||
kicad-skip>=0.1.0 # Schematic manipulation
|
||||
Pillow>=9.0.0 # Image processing
|
||||
cairosvg>=2.7.0 # SVG rendering
|
||||
pydantic>=2.5.0 # Data validation
|
||||
requests>=2.31.0 # API clients
|
||||
python-dotenv>=1.0.0 # Config management
|
||||
```
|
||||
|
||||
**Development Dependencies:**
|
||||
```
|
||||
pytest>=7.4.0 # Testing
|
||||
black>=23.7.0 # Code formatting
|
||||
mypy>=1.5.0 # Type checking
|
||||
pylint>=2.17.0 # Linting
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Week 1 Progress Tracking
|
||||
|
||||
### ✅ Completed Tasks (8/9)
|
||||
|
||||
1. ✅ **Audit codebase for Linux compatibility**
|
||||
- Created comprehensive audit document
|
||||
- Identified all platform-specific issues
|
||||
- Prioritized fixes (P0, P1, P2, P3)
|
||||
|
||||
2. ✅ **Create GitHub Actions CI/CD**
|
||||
- Multi-platform testing matrix
|
||||
- Python + TypeScript testing
|
||||
- Code quality checks
|
||||
- Coverage reporting
|
||||
|
||||
3. ✅ **Fix path handling**
|
||||
- Created PlatformHelper utility
|
||||
- Follows XDG Base Directory spec on Linux
|
||||
- Auto-detects KiCAD installation paths
|
||||
|
||||
4. ✅ **Update logging paths**
|
||||
- Linux: ~/.config/kicad-mcp/logs
|
||||
- Windows: ~\.kicad-mcp\logs
|
||||
- macOS: ~/Library/Application Support/kicad-mcp/logs
|
||||
|
||||
5. ✅ **Create CONTRIBUTING.md**
|
||||
- Complete developer guide
|
||||
- Platform-specific setup
|
||||
- Testing instructions
|
||||
|
||||
6. ✅ **Set up pytest framework**
|
||||
- pytest.ini with coverage
|
||||
- Test markers for organization
|
||||
- Sample tests passing
|
||||
|
||||
7. ✅ **Create platform config templates**
|
||||
- linux-config.example.json
|
||||
- windows-config.example.json
|
||||
- macos-config.example.json
|
||||
|
||||
8. ✅ **Create development infrastructure**
|
||||
- requirements.txt + requirements-dev.txt
|
||||
- Platform helper utilities
|
||||
- Test framework
|
||||
|
||||
### ⏳ Remaining Week 1 Tasks (1/9)
|
||||
|
||||
9. ⏳ **Docker container for testing** (Optional for Week 1)
|
||||
- Will create in Week 2 for consistent testing environment
|
||||
|
||||
---
|
||||
|
||||
## 📁 Files Created/Modified Today
|
||||
|
||||
### New Files (17)
|
||||
|
||||
```
|
||||
.github/workflows/ci.yml # CI/CD pipeline
|
||||
config/linux-config.example.json # Linux config
|
||||
config/windows-config.example.json # Windows config
|
||||
config/macos-config.example.json # macOS config
|
||||
docs/LINUX_COMPATIBILITY_AUDIT.md # Audit report
|
||||
docs/WEEK1_SESSION1_SUMMARY.md # This file
|
||||
python/utils/__init__.py # Utils package
|
||||
python/utils/platform_helper.py # Platform detection (300 lines)
|
||||
tests/__init__.py # Tests package
|
||||
tests/test_platform_helper.py # Platform tests (150 lines)
|
||||
pytest.ini # Pytest config
|
||||
requirements.txt # Python deps
|
||||
requirements-dev.txt # Python dev deps
|
||||
CONTRIBUTING.md # Developer guide
|
||||
```
|
||||
|
||||
### Modified Files (1)
|
||||
|
||||
```
|
||||
python/utils/platform_helper.py # Fixed docstring warnings
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🧪 Testing Status
|
||||
|
||||
### Unit Tests
|
||||
|
||||
```bash
|
||||
$ python3 python/utils/platform_helper.py
|
||||
✅ Platform detection works
|
||||
✅ Linux detected correctly
|
||||
✅ Python 3.12.3 found
|
||||
✅ Config dir: /home/chris/.config/kicad-mcp
|
||||
✅ Log dir: /home/chris/.config/kicad-mcp/logs
|
||||
✅ Cache dir: /home/chris/.cache/kicad-mcp
|
||||
⚠️ KiCAD not installed (expected on dev machine)
|
||||
```
|
||||
|
||||
### CI/CD Pipeline
|
||||
|
||||
```
|
||||
Status: Ready to run
|
||||
Triggers: Push to main/develop, Pull Requests
|
||||
Platforms: Ubuntu 24.04, 22.04, Windows, macOS
|
||||
Python: 3.10, 3.11, 3.12
|
||||
Node: 18.x, 20.x, 22.x
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Next Steps (Week 1 Remaining)
|
||||
|
||||
### Week 1 - Days 2-5
|
||||
|
||||
1. **Update README.md with Linux installation**
|
||||
- Add Linux-specific setup instructions
|
||||
- Link to platform-specific configs
|
||||
- Add troubleshooting section
|
||||
|
||||
2. **Test on actual Ubuntu 24.04 LTS**
|
||||
- Install KiCAD 9.0
|
||||
- Run full test suite
|
||||
- Document any issues found
|
||||
|
||||
3. **Begin IPC API research** (Week 2 prep)
|
||||
- Install `kicad-python` package
|
||||
- Test IPC API connection
|
||||
- Compare with SWIG API
|
||||
|
||||
4. **Start JLCPCB API research** (Week 5 prep)
|
||||
- Apply for API access
|
||||
- Review API documentation
|
||||
- Plan integration architecture
|
||||
|
||||
---
|
||||
|
||||
## 📊 Metrics
|
||||
|
||||
### Code Quality
|
||||
|
||||
- **Python Code Style:** Black formatting ready
|
||||
- **Type Hints:** 100% in new code (platform_helper.py)
|
||||
- **Documentation:** Comprehensive docstrings
|
||||
- **Test Coverage:** 20+ unit tests for platform_helper
|
||||
|
||||
### Platform Support
|
||||
|
||||
- **Windows:** ✅ Original support maintained
|
||||
- **Linux:** ✅ Full support added
|
||||
- **macOS:** ✅ Partial support (untested)
|
||||
|
||||
### Dependencies
|
||||
|
||||
- **Python Packages:** 7 production, 10 development
|
||||
- **Node.js Packages:** Existing (no changes yet)
|
||||
- **External APIs:** 0 (planned: JLCPCB, Digikey)
|
||||
|
||||
---
|
||||
|
||||
## 🚀 Impact Assessment
|
||||
|
||||
### Before Today
|
||||
- ❌ Windows-only
|
||||
- ❌ No CI/CD
|
||||
- ❌ No tests
|
||||
- ❌ Hardcoded paths
|
||||
- ❌ No developer documentation
|
||||
|
||||
### After Today
|
||||
- ✅ Cross-platform (Linux/Windows/macOS)
|
||||
- ✅ GitHub Actions CI/CD
|
||||
- ✅ 20+ unit tests with pytest
|
||||
- ✅ Platform-agnostic paths (XDG spec)
|
||||
- ✅ Complete developer guide
|
||||
|
||||
**Developer Experience:** Massively improved
|
||||
**Contributor Onboarding:** Now takes minutes instead of hours
|
||||
**Code Maintainability:** Significantly better
|
||||
**Future-Proofing:** Foundation laid for IPC API migration
|
||||
|
||||
---
|
||||
|
||||
## 💡 Key Decisions Made
|
||||
|
||||
### 1. **IPC API Migration: Proceed Immediately** ✅
|
||||
- SWIG is deprecated, will be removed in KiCAD 10.0
|
||||
- IPC API is stable, officially supported
|
||||
- Better performance and cross-language support
|
||||
- Decision: Migrate in Week 2-3
|
||||
|
||||
### 2. **Linux-First Approach** ✅
|
||||
- Hobbyists often use Linux
|
||||
- Better for open-source development
|
||||
- Easier CI/CD with GitHub Actions
|
||||
- Decision: Linux is primary development platform
|
||||
|
||||
### 3. **JLCPCB Integration Priority** ✅
|
||||
- Hobbyists love JLCPCB for cheap assembly
|
||||
- "Basic parts" filter is critical
|
||||
- Better stock than Digikey for hobbyists
|
||||
- Decision: JLCPCB before Digikey
|
||||
|
||||
### 4. **Pytest over unittest** ✅
|
||||
- More Pythonic
|
||||
- Better fixtures and parametrization
|
||||
- Industry standard
|
||||
- Decision: Use pytest for all tests
|
||||
|
||||
---
|
||||
|
||||
## 🎓 Lessons Learned
|
||||
|
||||
### Technical Insights
|
||||
|
||||
1. **XDG Base Directory Spec** - Linux has clear standards for config/cache/data
|
||||
2. **pathlib > os.path** - More readable, cross-platform by default
|
||||
3. **Platform detection** - Check environment variables before hardcoding paths
|
||||
4. **Type hints** - Make code self-documenting and catch bugs early
|
||||
|
||||
### Process Insights
|
||||
|
||||
1. **Audit first, code second** - Understanding the problem space saves time
|
||||
2. **Infrastructure before features** - CI/CD and testing pay dividends
|
||||
3. **Documentation is code** - Good docs prevent future confusion
|
||||
4. **Cross-platform from day 1** - Retrofitting is painful
|
||||
|
||||
---
|
||||
|
||||
## 🎉 Highlights
|
||||
|
||||
### Biggest Win
|
||||
✨ **Complete cross-platform infrastructure in one session**
|
||||
|
||||
### Most Valuable Addition
|
||||
🔧 **PlatformHelper utility** - Solves path issues elegantly
|
||||
|
||||
### Best Decision
|
||||
🎯 **Creating comprehensive plan first** - Clear roadmap for 12 weeks
|
||||
|
||||
### Unexpected Discovery
|
||||
⚠️ **SWIG deprecation** - Would have been a nasty surprise later!
|
||||
|
||||
---
|
||||
|
||||
## 🤝 Collaboration Notes
|
||||
|
||||
### What Went Well
|
||||
- Clear requirements from user
|
||||
- Good research phase before coding
|
||||
- Incremental progress with testing
|
||||
|
||||
### What to Improve
|
||||
- Need actual Ubuntu 24.04 testing
|
||||
- Should run pytest suite
|
||||
- Need to test KiCAD 9.0 integration
|
||||
|
||||
---
|
||||
|
||||
## 📅 Schedule Status
|
||||
|
||||
### Week 1 Goals
|
||||
- [x] Linux compatibility audit (**100% complete**)
|
||||
- [x] CI/CD setup (**100% complete**)
|
||||
- [x] Development infrastructure (**100% complete**)
|
||||
- [ ] Linux installation testing (**0% complete** - needs Ubuntu 24.04)
|
||||
|
||||
**Overall Week 1 Progress: ~80% complete**
|
||||
|
||||
**Status: 🟢 ON TRACK**
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Next Session Goals
|
||||
|
||||
1. Update README.md with Linux instructions
|
||||
2. Test on actual Ubuntu 24.04 LTS with KiCAD 9.0
|
||||
3. Run full pytest suite
|
||||
4. Fix any issues found during testing
|
||||
5. Begin IPC API research (install kicad-python)
|
||||
|
||||
**Estimated Time: 2-3 hours**
|
||||
|
||||
---
|
||||
|
||||
## 📝 Notes for Future
|
||||
|
||||
### Architecture Decisions to Make
|
||||
- [ ] Redis vs in-memory cache?
|
||||
- [ ] Session storage approach?
|
||||
- [ ] WebSocket vs STDIO for future scaling?
|
||||
|
||||
### Dependencies to Research
|
||||
- [ ] JLCPCB API client library (exists?)
|
||||
- [ ] Digikey API v3 (issus/DigiKeyApi looks good)
|
||||
- [ ] kicad-python 0.5.0 compatibility
|
||||
|
||||
### Questions to Answer
|
||||
- [ ] How to handle KiCAD running vs not running (IPC requirement)?
|
||||
- [ ] Should we support both SWIG and IPC during migration?
|
||||
- [ ] BOM format standardization?
|
||||
|
||||
---
|
||||
|
||||
## 🏆 Success Metrics Achieved Today
|
||||
|
||||
| Metric | Target | Achieved | Status |
|
||||
|--------|--------|----------|--------|
|
||||
| Platform support | Linux primary | ✅ Linux ready | ✅ |
|
||||
| CI/CD pipeline | GitHub Actions | ✅ Complete | ✅ |
|
||||
| Test coverage | Setup pytest | ✅ 20+ tests | ✅ |
|
||||
| Documentation | CONTRIBUTING.md | ✅ Complete | ✅ |
|
||||
| Config templates | 3 platforms | ✅ 3 created | ✅ |
|
||||
| Platform helper | Path utilities | ✅ 300 lines | ✅ |
|
||||
|
||||
**Overall Session Rating: 🌟🌟🌟🌟🌟 (5/5)**
|
||||
|
||||
---
|
||||
|
||||
## 🙏 Acknowledgments
|
||||
|
||||
- **KiCAD Team** - For the excellent IPC API documentation
|
||||
- **Anthropic** - For MCP specification and best practices
|
||||
- **JLCPCB/Digikey** - For API availability
|
||||
|
||||
---
|
||||
|
||||
**Session End Time:** October 25, 2025
|
||||
**Duration:** ~2 hours
|
||||
**Files Created:** 17
|
||||
**Lines of Code:** ~1000+
|
||||
**Tests Written:** 20+
|
||||
**Documentation Pages:** 5
|
||||
|
||||
---
|
||||
|
||||
## 🚀 Ready for Week 1, Day 2!
|
||||
|
||||
**Next Session Focus:** Linux testing + README updates
|
||||
**Energy Level:** 🔋🔋🔋🔋🔋 (High)
|
||||
**Confidence Level:** 💪💪💪💪💪 (Very High)
|
||||
|
||||
Let's keep this momentum going! 🎉
|
||||
422
docs/archive/WEEK1_SESSION2_SUMMARY.md
Normal file
422
docs/archive/WEEK1_SESSION2_SUMMARY.md
Normal file
@@ -0,0 +1,422 @@
|
||||
# Week 1 - Session 2 Summary
|
||||
**Date:** October 25, 2025 (Afternoon)
|
||||
**Status:** 🚀 **OUTSTANDING PROGRESS**
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Session Goals
|
||||
|
||||
Continue Week 1 implementation while user installs KiCAD:
|
||||
1. Update README with comprehensive Linux guide
|
||||
2. Create installation scripts
|
||||
3. Begin IPC API preparation
|
||||
4. Set up development infrastructure
|
||||
|
||||
---
|
||||
|
||||
## ✅ Completed Work
|
||||
|
||||
### 1. **README.md Major Update** 📚
|
||||
|
||||
**File:** `README.md`
|
||||
|
||||
**Changes:**
|
||||
- ✅ Updated project status to reflect v2.0 rebuild
|
||||
- ✅ Added collapsible platform-specific installation sections:
|
||||
- 🐧 **Linux (Ubuntu/Debian)** - Primary, detailed
|
||||
- 🪟 **Windows 10/11** - Fully supported
|
||||
- 🍎 **macOS** - Experimental
|
||||
- ✅ Updated system requirements (Linux primary platform)
|
||||
- ✅ Added Quick Start section with test commands
|
||||
- ✅ Better visual organization with emojis and status indicators
|
||||
|
||||
**Impact:** New users can now install on Linux in < 10 minutes!
|
||||
|
||||
---
|
||||
|
||||
### 2. **Linux Installation Script** 🛠️
|
||||
|
||||
**File:** `scripts/install-linux.sh`
|
||||
|
||||
**Features:**
|
||||
- ✅ Fully automated Ubuntu/Debian installation
|
||||
- ✅ Color-coded output (info/success/warning/error)
|
||||
- ✅ Safety checks (platform detection, command validation)
|
||||
- ✅ Installs:
|
||||
- KiCAD 9.0 from PPA
|
||||
- Node.js 20.x
|
||||
- Python dependencies
|
||||
- Builds TypeScript
|
||||
- ✅ Verification checks after installation
|
||||
- ✅ Helpful next-steps guidance
|
||||
|
||||
**Usage:**
|
||||
```bash
|
||||
cd kicad-mcp-server
|
||||
./scripts/install-linux.sh
|
||||
```
|
||||
|
||||
**Lines of Code:** ~200 lines of robust shell script
|
||||
|
||||
---
|
||||
|
||||
### 3. **Pre-Commit Hooks Configuration** 🔧
|
||||
|
||||
**File:** `.pre-commit-config.yaml`
|
||||
|
||||
**Hooks Added:**
|
||||
- ✅ **Python:**
|
||||
- Black (code formatting)
|
||||
- isort (import sorting)
|
||||
- MyPy (type checking)
|
||||
- Flake8 (linting)
|
||||
- Bandit (security checks)
|
||||
- ✅ **TypeScript/JavaScript:**
|
||||
- Prettier (formatting)
|
||||
- ✅ **General:**
|
||||
- Trailing whitespace removal
|
||||
- End-of-file fixer
|
||||
- YAML/JSON validation
|
||||
- Large file detection
|
||||
- Merge conflict detection
|
||||
- Private key detection
|
||||
- ✅ **Markdown:**
|
||||
- Markdownlint (formatting)
|
||||
|
||||
**Setup:**
|
||||
```bash
|
||||
pip install pre-commit
|
||||
pre-commit install
|
||||
```
|
||||
|
||||
**Impact:** Automatic code quality enforcement on every commit!
|
||||
|
||||
---
|
||||
|
||||
### 4. **IPC API Migration Plan** 📋
|
||||
|
||||
**File:** `docs/IPC_API_MIGRATION_PLAN.md`
|
||||
|
||||
**Comprehensive 30-page migration guide:**
|
||||
- ✅ Why migrate (SWIG deprecation analysis)
|
||||
- ✅ IPC API architecture overview
|
||||
- ✅ 4-phase migration strategy (10 days)
|
||||
- ✅ API comparison tables (SWIG vs IPC)
|
||||
- ✅ Testing strategy
|
||||
- ✅ Rollback plan
|
||||
- ✅ Success criteria
|
||||
- ✅ Timeline with day-by-day tasks
|
||||
|
||||
**Key Insights:**
|
||||
- SWIG will be removed in KiCAD 10.0
|
||||
- IPC is faster for some operations
|
||||
- Protocol Buffers ensure API stability
|
||||
- Multi-language support opens future possibilities
|
||||
|
||||
---
|
||||
|
||||
### 5. **IPC API Abstraction Layer** 🏗️
|
||||
|
||||
**New Module:** `python/kicad_api/`
|
||||
|
||||
**Files Created (5):**
|
||||
|
||||
1. **`__init__.py`** (20 lines)
|
||||
- Package exports
|
||||
- Version info
|
||||
- Usage examples
|
||||
|
||||
2. **`base.py`** (180 lines)
|
||||
- `KiCADBackend` abstract base class
|
||||
- `BoardAPI` abstract interface
|
||||
- Custom exceptions (`BackendError`, `ConnectionError`, etc.)
|
||||
- Defines contract for all backends
|
||||
|
||||
3. **`factory.py`** (160 lines)
|
||||
- `create_backend()` - Smart backend selection
|
||||
- Auto-detection (try IPC, fall back to SWIG)
|
||||
- Environment variable support (`KICAD_BACKEND`)
|
||||
- `get_available_backends()` - Diagnostic function
|
||||
- Comprehensive error handling
|
||||
|
||||
4. **`ipc_backend.py`** (210 lines)
|
||||
- `IPCBackend` class (kicad-python wrapper)
|
||||
- `IPCBoardAPI` class
|
||||
- Connection management
|
||||
- Skeleton methods (to be implemented in Week 2-3)
|
||||
- Clear TODO markers for migration
|
||||
|
||||
5. **`swig_backend.py`** (220 lines)
|
||||
- `SWIGBackend` class (wraps existing code)
|
||||
- `SWIGBoardAPI` class
|
||||
- Backward compatibility layer
|
||||
- Deprecation warnings
|
||||
- Bridges old commands to new interface
|
||||
|
||||
**Total Lines of Code:** ~800 lines
|
||||
|
||||
**Architecture:**
|
||||
```python
|
||||
from kicad_api import create_backend
|
||||
|
||||
# Auto-detect best backend
|
||||
backend = create_backend()
|
||||
|
||||
# Or specify explicitly
|
||||
backend = create_backend('ipc') # Use IPC
|
||||
backend = create_backend('swig') # Use SWIG (deprecated)
|
||||
|
||||
# Use unified interface
|
||||
if backend.connect():
|
||||
board = backend.get_board()
|
||||
board.set_size(100, 80)
|
||||
```
|
||||
|
||||
**Key Features:**
|
||||
- ✅ Abstraction allows painless migration
|
||||
- ✅ Both backends can coexist during transition
|
||||
- ✅ Easy testing (compare SWIG vs IPC outputs)
|
||||
- ✅ Future-proof (add new backends easily)
|
||||
- ✅ Type hints throughout
|
||||
- ✅ Comprehensive error handling
|
||||
|
||||
---
|
||||
|
||||
### 6. **Enhanced package.json** 📦
|
||||
|
||||
**File:** `package.json`
|
||||
|
||||
**Improvements:**
|
||||
- ✅ Version bumped to `2.0.0-alpha.1`
|
||||
- ✅ Better description
|
||||
- ✅ Enhanced npm scripts:
|
||||
```json
|
||||
"build:watch": "tsc --watch"
|
||||
"clean": "rm -rf dist"
|
||||
"rebuild": "npm run clean && npm run build"
|
||||
"test": "npm run test:ts && npm run test:py"
|
||||
"test:py": "pytest tests/ -v"
|
||||
"test:coverage": "pytest with coverage"
|
||||
"lint": "npm run lint:ts && npm run lint:py"
|
||||
"lint:py": "black + mypy + flake8"
|
||||
"format": "prettier + black"
|
||||
```
|
||||
|
||||
**Impact:** Better developer experience, easier workflows
|
||||
|
||||
---
|
||||
|
||||
## 📊 Statistics
|
||||
|
||||
### Files Created/Modified (Session 2)
|
||||
|
||||
**New Files (10):**
|
||||
```
|
||||
docs/IPC_API_MIGRATION_PLAN.md # 500+ lines
|
||||
docs/WEEK1_SESSION2_SUMMARY.md # This file
|
||||
scripts/install-linux.sh # 200 lines
|
||||
.pre-commit-config.yaml # 60 lines
|
||||
python/kicad_api/__init__.py # 20 lines
|
||||
python/kicad_api/base.py # 180 lines
|
||||
python/kicad_api/factory.py # 160 lines
|
||||
python/kicad_api/ipc_backend.py # 210 lines
|
||||
python/kicad_api/swig_backend.py # 220 lines
|
||||
```
|
||||
|
||||
**Modified Files (2):**
|
||||
```
|
||||
README.md # Major rewrite
|
||||
package.json # Enhanced scripts
|
||||
```
|
||||
|
||||
**Total New Lines:** ~1,600+ lines of code/documentation
|
||||
|
||||
---
|
||||
|
||||
### Combined Sessions 1+2 Today
|
||||
|
||||
**Files Created:** 27
|
||||
**Lines Written:** ~3,000+
|
||||
**Documentation Pages:** 8
|
||||
**Tests Created:** 20+
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Week 1 Status
|
||||
|
||||
### Progress: **95% Complete** ████████████░
|
||||
|
||||
| Task | Status |
|
||||
|------|--------|
|
||||
| Linux compatibility | ✅ Complete |
|
||||
| CI/CD pipeline | ✅ Complete |
|
||||
| Cross-platform paths | ✅ Complete |
|
||||
| Developer docs | ✅ Complete |
|
||||
| pytest framework | ✅ Complete |
|
||||
| Config templates | ✅ Complete |
|
||||
| Installation scripts | ✅ Complete |
|
||||
| Pre-commit hooks | ✅ Complete |
|
||||
| IPC migration plan | ✅ Complete |
|
||||
| IPC abstraction layer | ✅ Complete |
|
||||
| README updates | ✅ Complete |
|
||||
| Testing on Ubuntu | ⏳ Pending (needs KiCAD install) |
|
||||
|
||||
**Only Remaining:** Test with actual KiCAD 9.0 installation!
|
||||
|
||||
---
|
||||
|
||||
## 🚀 Ready for Week 2
|
||||
|
||||
### IPC API Migration Prep ✅
|
||||
|
||||
Everything is in place to begin migration:
|
||||
- ✅ Abstraction layer architecture defined
|
||||
- ✅ Base classes and interfaces ready
|
||||
- ✅ Factory pattern for backend selection
|
||||
- ✅ SWIG wrapper for backward compatibility
|
||||
- ✅ IPC skeleton awaiting implementation
|
||||
- ✅ Comprehensive migration plan documented
|
||||
|
||||
**Week 2 kickoff tasks:**
|
||||
1. Install `kicad-python` package
|
||||
2. Test IPC connection to running KiCAD
|
||||
3. Begin porting `project.py` module
|
||||
4. Create side-by-side tests (SWIG vs IPC)
|
||||
|
||||
---
|
||||
|
||||
## 💡 Key Insights from Session 2
|
||||
|
||||
### 1. **Installation Automation**
|
||||
The bash script reduces setup time from 30+ minutes to < 10 minutes with zero manual intervention.
|
||||
|
||||
### 2. **Pre-Commit Hooks**
|
||||
Automatic code quality checks prevent bugs before they're committed. This will save hours in code review.
|
||||
|
||||
### 3. **Abstraction Pattern**
|
||||
The backend abstraction is elegant - allows gradual migration without breaking existing functionality. Users won't notice the transition.
|
||||
|
||||
### 4. **Documentation Quality**
|
||||
The IPC migration plan is thorough enough that another developer could execute it independently.
|
||||
|
||||
---
|
||||
|
||||
## 🧪 Testing Readiness
|
||||
|
||||
### When KiCAD is Installed
|
||||
|
||||
You can immediately test:
|
||||
|
||||
**1. Platform Helper:**
|
||||
```bash
|
||||
python3 python/utils/platform_helper.py
|
||||
```
|
||||
|
||||
**2. Backend Detection:**
|
||||
```bash
|
||||
python3 python/kicad_api/factory.py
|
||||
```
|
||||
|
||||
**3. Installation Script:**
|
||||
```bash
|
||||
./scripts/install-linux.sh
|
||||
```
|
||||
|
||||
**4. Pytest Suite:**
|
||||
```bash
|
||||
pytest tests/ -v
|
||||
```
|
||||
|
||||
**5. Pre-commit Hooks:**
|
||||
```bash
|
||||
pre-commit run --all-files
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📈 Impact Assessment
|
||||
|
||||
### Developer Onboarding
|
||||
- **Before:** 2-3 hours setup, Windows-only, manual steps
|
||||
- **After:** 10 minutes automated, cross-platform, one script
|
||||
|
||||
### Code Quality
|
||||
- **Before:** No automated checks, inconsistent style
|
||||
- **After:** Pre-commit hooks, 100% type hints, Black formatting
|
||||
|
||||
### Future-Proofing
|
||||
- **Before:** Deprecated SWIG API, no migration path
|
||||
- **After:** IPC API ready, abstraction layer in place
|
||||
|
||||
### Documentation
|
||||
- **Before:** README only, Windows-focused
|
||||
- **After:** 8 comprehensive docs, Linux-primary, migration guides
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Next Actions
|
||||
|
||||
### Immediate (Tonight/Tomorrow)
|
||||
1. Install KiCAD 9.0 on your system
|
||||
2. Run `./scripts/install-linux.sh`
|
||||
3. Test backend detection
|
||||
4. Verify pytest suite passes
|
||||
|
||||
### Week 2 Start (Monday)
|
||||
1. Install `kicad-python` package
|
||||
2. Test IPC connection
|
||||
3. Begin project.py migration
|
||||
4. Create first IPC API tests
|
||||
|
||||
---
|
||||
|
||||
## 🏆 Session 2 Achievements
|
||||
|
||||
### Infrastructure
|
||||
- ✅ Automated Linux installation
|
||||
- ✅ Pre-commit hooks for code quality
|
||||
- ✅ Enhanced npm scripts
|
||||
- ✅ IPC API abstraction layer (800+ lines)
|
||||
|
||||
### Documentation
|
||||
- ✅ Updated README (Linux-primary)
|
||||
- ✅ 30-page IPC migration plan
|
||||
- ✅ Session summaries
|
||||
|
||||
### Architecture
|
||||
- ✅ Backend abstraction pattern
|
||||
- ✅ Factory with auto-detection
|
||||
- ✅ SWIG backward compatibility
|
||||
- ✅ IPC skeleton ready for implementation
|
||||
|
||||
---
|
||||
|
||||
## 🎉 Overall Day Summary
|
||||
|
||||
**Sessions 1+2 Combined:**
|
||||
- ⏱️ **Time:** ~4-5 hours total
|
||||
- 📝 **Files:** 27 created
|
||||
- 💻 **Code:** ~3,000+ lines
|
||||
- 📚 **Docs:** 8 comprehensive pages
|
||||
- 🧪 **Tests:** 20+ unit tests
|
||||
- ✅ **Week 1:** 95% complete
|
||||
|
||||
**Status:** 🟢 **AHEAD OF SCHEDULE**
|
||||
|
||||
---
|
||||
|
||||
## 🚀 Momentum Check
|
||||
|
||||
**Energy Level:** 🔋🔋🔋🔋🔋 (Maximum)
|
||||
**Code Quality:** ⭐⭐⭐⭐⭐ (Excellent)
|
||||
**Documentation:** 📖📖📖📖📖 (Comprehensive)
|
||||
**Architecture:** 🏗️🏗️🏗️🏗️🏗️ (Solid)
|
||||
|
||||
**Ready for Week 2 IPC Migration:** ✅ YES!
|
||||
|
||||
---
|
||||
|
||||
**End of Session 2**
|
||||
**Next:** KiCAD installation + testing + Week 2 kickoff
|
||||
|
||||
Let's keep this incredible momentum going! 🎉🚀
|
||||
Reference in New Issue
Block a user