# Development Guide ## Getting Started ### Prerequisites Before contributing to ClaudeCode MCP Manager, ensure you have: 1. **Go 1.21 or higher** ```bash go version # Should show: go version go1.21.x or higher ``` 2. **Claude Code CLI** installed and configured ```bash claude --version claude mcp list # Should work without errors ``` 3. **Git** for version control ```bash git --version ``` 4. **A text editor** (VS Code, Vim, GoLand, etc.) ### Setting Up Development Environment 1. **Clone the repository** ```bash git clone https://github.com/donmecca/claudecode-mcp-manager cd claudecode-mcp-manager ``` 2. **Install dependencies** ```bash go mod download go mod verify ``` 3. **Build the project** ```bash go build -o mcp-manager ``` 4. **Run the application** ```bash ./mcp-manager ``` 5. **Optional: Set up test profiles** ```bash # Create test profile directories mkdir -p ~/.claude-test cp ~/.claude/.claude.json ~/.claude-test/ # Run with test profile CLAUDE_CONFIG_DIR=~/.claude-test ./mcp-manager ``` ## CRITICAL: Development Best Practices ### Lessons Learned from Production Issues **⚠️ NEVER use `jq` or direct JSON editing to modify `.claude.json` files!** #### Why This is Critical 1. **File Size**: `.claude.json` files can be 100-200MB (contains conversation history in `projects` field) 2. **State Corruption**: Direct editing can create invalid states where MCPs exist in both enabled AND disabled lists simultaneously 3. **Lost Backups**: Bypasses mcp-manager's automatic backup system 4. **Field Loss**: Can lose important config fields during merge operations 5. **No Atomic Writes**: Risk of corruption if interrupted #### The Safe Way **Always use the internal `config` package:** ```go import "github.com/donmecca/claudecode-mcp-manager/internal/config" // Create backup first config.CreateBackup() // Read config (preserves all fields via RawData) cfg, err := config.ReadConfig() // Modify only MCP fields cfg.McpServers["new-mcp"] = &config.McpServer{ Type: "stdio", Command: "npx", Args: []string{"-y", "package"}, } // Write atomically (temp file + rename) config.WriteConfig(cfg) ``` **The config package provides:** - ✅ Automatic backups before changes - ✅ Atomic writes (temp file + rename) - ✅ Field preservation via RawData map - ✅ Validation and error handling - ✅ Profile-aware operations ### macOS Development Gotchas **Gatekeeper Quarantine Issue:** After building on macOS, the binary may be killed by Gatekeeper: ```bash $ ./mcp-manager [1] 12345 killed mcp-manager ``` **Solution 1: Use build script (automatic)** ```bash ./scripts/build.sh --platform darwin # Script automatically removes quarantine ``` **Solution 2: Manual fix** ```bash go build -o mcp-manager xattr -d com.apple.quarantine ./mcp-manager ``` **For install script:** ```bash ./scripts/install.sh --build --local # Automatically handles quarantine removal ``` ### Testing Changes Safely 1. **Always test with backup profile first:** ```bash # Create test profile mkdir -p ~/.claude-test cp ~/.claude/.claude.json ~/.claude-test/ # Test changes CLAUDE_CONFIG_DIR=~/.claude-test go run main.go ``` 2. **Verify no corruption:** ```bash # Check for duplicates jq '.mcpServers | keys' ~/.claude-test/.claude.json > /tmp/enabled jq '._mcpManagerDisabledServers | keys' ~/.claude-test/.claude.json > /tmp/disabled comm -12 <(sort /tmp/enabled) <(sort /tmp/disabled) # Should output nothing ``` 3. **Validate JSON integrity:** ```bash jq empty ~/.claude-test/.claude.json && echo "✓ Valid" || echo "✗ Invalid" ``` ### Config File Architecture **What Claude Code Actually Uses:** - Default profile: `~/.claude.json` (NOT `settings.local.json`) - GLM profile: `~/.claude-glm/.claude.json` - Custom: `~/.claude-/.claude.json` **Config Structure:** ```json { "mcpServers": { "enabled-mcp": { "type": "stdio", "command": "...", "args": [...] } }, "_mcpManagerDisabledServers": { "disabled-mcp": { "type": "stdio", "command": "...", "args": [...] } }, "projects": { /* 100MB+ of conversation history */ }, "userID": "...", "theme": "...", /* 40+ other Claude Code fields */ } ``` **Valid States:** - ✅ MCP in `mcpServers` only (enabled) - ✅ MCP in `_mcpManagerDisabledServers` only (disabled) - ❌ MCP in BOTH lists (corrupted state - breaks mcp-manager) ## Project Structure Deep Dive ``` claudecode-mcp-manager/ ├── main.go # Application entry point │ ├── internal/ │ ├── config/ # Configuration management layer │ │ ├── config.go # Settings.local.json operations │ │ ├── backup.go # Backup/restore system │ │ └── profiles.go # Profile discovery and management │ │ │ ├── mcp/ # MCP integration layer │ │ ├── server.go # MCPServer struct and utilities │ │ └── mcp.go # Claude CLI command wrappers │ │ │ └── ui/ # User interface layer │ ├── model.go # Main Bubble Tea model │ ├── view.go # View rendering logic │ ├── styles.go # Lip Gloss styling definitions │ ├── keys.go # Keyboard shortcut bindings │ │ │ ├── components/ # Reusable UI components │ │ ├── statusbar.go # Bottom status bar │ │ └── help.go # Help screen │ │ │ └── views/ # Full-screen views │ ├── add.go # Add MCP form │ ├── delete.go # Delete confirmation │ ├── restore.go # Backup restore │ └── profiles.go # Profile switcher │ ├── docs/ # Documentation │ ├── architecture.md # System design │ ├── development.md # This file │ ├── user-guide.md # User documentation │ └── profiles.md # Profile guide │ ├── scripts/ # Build and installation scripts │ ├── build.sh # Cross-platform builds │ └── install.sh # Installation script │ ├── TASKS.md # Master task tracker ├── CLAUDE.md # Claude Code project guide ├── README.md # Main documentation ├── LICENSE # MIT License ├── .gitignore # Git ignore rules ├── go.mod # Go module definition └── go.sum # Go dependency checksums ``` ## Development Workflow ### 1. Task-Driven Development We use `TASKS.md` as the single source of truth: ```bash # Before starting work cat TASKS.md | grep "⬜\|⏳" # Find incomplete tasks # While working # Mark tasks complete with [x] as you finish them # After completing work # Update TASKS.md with progress notes and percentages ``` ### 2. Branch Strategy ```bash # Create feature branch git checkout -b feature/your-feature-name # Make changes, commit often git add . git commit -m "feat: add feature description" # When ready, push and create PR git push origin feature/your-feature-name ``` ### 3. Commit Message Format ``` : [optional body explaining what and why] Phase X task: ``` **Types:** - `feat`: New feature - `fix`: Bug fix - `docs`: Documentation changes - `refactor`: Code refactoring - `test`: Adding tests - `chore`: Maintenance tasks **Examples:** ``` feat: add MCP health check indicator - Added status polling for connected MCPs - Display green/red indicator in list view - Poll every 30 seconds in background Phase 3 task: Add server status indicators --- fix: prevent crash on empty server list Fixed nil pointer dereference when no MCPs configured. Added empty state check in viewList(). Phase 4 task: Error handling improvements ``` ## Code Style Guide ### Go Style Follow standard Go conventions: ```go // Good: Exported functions have doc comments // ListServers executes 'claude mcp list' and parses the output func ListServers() (ServerList, error) { // ... } // Good: Error handling with context if err != nil { return nil, fmt.Errorf("failed to list servers: %w", err) } // Good: Early returns for error cases func processServer(s MCPServer) error { if s.Name == "" { return errors.New("server name cannot be empty") } // Main logic here return nil } // Bad: Don't panic in library code func getConfig() Config { cfg, err := ReadConfig() if err != nil { panic(err) // ❌ Don't do this } return cfg } // Good: Return errors instead func getConfig() (Config, error) { cfg, err := ReadConfig() if err != nil { return Config{}, err // ✅ Let caller decide } return cfg, nil } ``` ### Formatting ```bash # Format all Go files go fmt ./... # Check for common issues go vet ./... # Install and use staticcheck go install honnef.co/go/tools/cmd/staticcheck@latest staticcheck ./... ``` ### Naming Conventions - **Packages**: lowercase, single word (`config`, `mcp`, `ui`) - **Files**: lowercase with underscores (`status_bar.go`) - **Types**: PascalCase (`MCPServer`, `StatusBar`) - **Functions**: PascalCase for exported, camelCase for private - **Constants**: PascalCase or SCREAMING_SNAKE_CASE for public ## Architecture Patterns ### Bubble Tea Model-Update-View ```go // Model: Application state type Model struct { servers []mcp.MCPServer cursor int err error } // Init: Initial command func (m Model) Init() tea.Cmd { return fetchServers // Returns a command to execute } // Update: Event handler func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { switch msg := msg.(type) { case tea.KeyMsg: // Handle keyboard input return m, nil case serverListMsg: // Handle custom message m.servers = msg.servers return m, nil } return m, nil } // View: Renderer func (m Model) View() string { // Return string to display return lipgloss.JoinVertical( lipgloss.Left, "Title", renderServers(m.servers), renderStatusBar(m), ) } ``` ### View Models Each complex view has its own model: ```go // views/add.go type AddModel struct { inputs []textinput.Model focusIndex int submitted bool cancelled bool } func NewAddModel() AddModel { // Initialize with defaults } func (m AddModel) Update(msg tea.Msg) (AddModel, tea.Cmd) { // Handle view-specific logic } func (m AddModel) View() string { // Render view } ``` ### Configuration Management Pattern **Always follow this pattern when modifying config:** ```go // 1. Create backup FIRST if err := config.CreateBackup(); err != nil { return fmt.Errorf("backup failed: %w", err) } // 2. Read current config cfg, err := config.ReadConfig() if err != nil { return fmt.Errorf("read config failed: %w", err) } // 3. Modify config cfg.EnableServer(serverName) // 4. Write atomically if err := config.WriteConfig(cfg); err != nil { return fmt.Errorf("write config failed: %w", err) } // 5. Success! return nil ``` ## Testing Guidelines ### Manual Testing Checklist Before committing changes, verify: - [ ] Application builds without errors (`go build`) - [ ] Application runs without crashing - [ ] Main list view displays correctly - [ ] Navigation works (up/down/j/k) - [ ] Toggle functionality works (space/enter) - [ ] Add MCP form accepts input - [ ] Delete confirmation shows and works - [ ] Help screen displays (h or ?) - [ ] Quit works (q or Ctrl+C) - [ ] Works with default profile - [ ] Works with test profile (`CLAUDE_CONFIG_DIR=~/.claude-test`) ### Testing with Real MCPs ```bash # 1. Create a test profile mkdir -p ~/.claude-test cp ~/.claude/settings.local.json ~/.claude-test/ # 2. Run with test profile CLAUDE_CONFIG_DIR=~/.claude-test ./mcp-manager # 3. Try all operations: # - Toggle an MCP on/off # - Add a new MCP # - Delete an MCP # - Restore from backup # - Switch profiles view # 4. Verify changes in config file cat ~/.claude-test/settings.local.json # 5. Verify backup was created ls -la ~/.claude-test/*.bak ``` ### Testing Profile Switching ```bash # Test with default profile ./mcp-manager # Test with custom profile CLAUDE_CONFIG_DIR=~/.claude-glm ./mcp-manager # Test profile discovery (should show all profiles) # Press 'p' in the app to see profile list ``` ### Testing Backup/Restore ```bash # 1. Make a change (toggle an MCP) # 2. Check backup was created: ls -la ~/.claude/*.bak | head -1 # 3. Make another change # 4. Press 'r' to restore # 5. Select most recent backup # 6. Verify config was restored cat ~/.claude/settings.local.json ``` ## Adding New Features ### Example: Adding a New View 1. **Create view file** ```bash touch internal/ui/views/mynewview.go ``` 2. **Define view model** ```go package views import ( tea "github.com/charmbracelet/bubbletea" "github.com/charmbracelet/lipgloss" ) type MyNewViewModel struct { // View state data string styles MyNewViewStyles } type MyNewViewStyles struct { Title lipgloss.Style Content lipgloss.Style } func NewMyNewViewModel(styles MyNewViewStyles) MyNewViewModel { return MyNewViewModel{ styles: styles, } } func (m MyNewViewModel) Update(msg tea.Msg) (MyNewViewModel, tea.Cmd) { switch msg := msg.(type) { case tea.KeyMsg: // Handle keys } return m, nil } func (m MyNewViewModel) View() string { return lipgloss.JoinVertical( lipgloss.Left, m.styles.Title.Render("My New View"), m.styles.Content.Render(m.data), ) } ``` 3. **Add view mode to model.go** ```go // In internal/ui/model.go const ( ViewList ViewMode = iota ViewHelp ViewAdd ViewDelete ViewRestore ViewProfiles ViewMyNew // Add this ) type Model struct { // ... existing fields myNewView views.MyNewViewModel // Add this } ``` 4. **Initialize in New() function** ```go func New() (Model, error) { // ... existing code myNewView: views.NewMyNewViewModel(views.MyNewViewStyles{ Title: styles.Title, Content: styles.ListItem, }), } ``` 5. **Handle in Update()** ```go func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { if m.mode == ViewMyNew { var cmd tea.Cmd m.myNewView, cmd = m.myNewView.Update(msg) return m, cmd } // ... rest of update logic } ``` 6. **Render in View()** ```go func (m Model) View() string { switch m.mode { case ViewMyNew: return m.myNewView.View() // ... other cases } } ``` 7. **Add keyboard shortcut in keys.go** ```go type KeyMap struct { // ... existing keys MyNew key.Binding } func DefaultKeyMap() KeyMap { return KeyMap{ // ... existing bindings MyNew: key.NewBinding( key.WithKeys("n"), key.WithHelp("n", "my new view"), ), } } ``` 8. **Update TASKS.md** ```markdown ### Phase X: New Features - [x] Add MyNewView - Created views/mynewview.go - Integrated with main model - Added keyboard shortcut 'n' ``` ## Debugging Tips ### Enable Debug Logging Add this to `main.go`: ```go func main() { if len(os.Getenv("DEBUG")) > 0 { f, err := tea.LogToFile("debug.log", "debug") if err != nil { fmt.Println("fatal:", err) os.Exit(1) } defer f.Close() } // ... rest of main } ``` Run with: ```bash DEBUG=1 ./mcp-manager # Check debug.log for output tail -f debug.log ``` ### Common Issues **Build Error: "package X is not in GOROOT"** ```bash # Solution: Install missing dependency go mod download go mod tidy ``` **Runtime Error: "claude mcp list: command not found"** ```bash # Solution: Verify Claude Code CLI is installed which claude # If not found, reinstall Claude Code ``` **UI Glitches or Rendering Issues** ```bash # Solution: Try different terminal # Bubble Tea works best with modern terminals: # - iTerm2 (macOS) # - Alacritty # - Windows Terminal # - GNOME Terminal ``` ## Performance Optimization ### Best Practices 1. **Minimize Config Reads** ```go // Bad: Reading config on every render func (m Model) View() string { cfg, _ := config.ReadConfig() // ❌ Slow! // ... } // Good: Cache config in model type Model struct { config *config.Config } func (m Model) refreshConfig() tea.Cmd { return func() tea.Msg { cfg, err := config.ReadConfig() return configLoadedMsg{cfg, err} } } ``` 2. **Use Commands for I/O** ```go // Good: Run I/O in commands, not Update() func refreshServers() tea.Msg { servers, err := mcp.ListServers() return serverListMsg{servers, err} } func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { switch msg := msg.(type) { case tea.KeyMsg: if key.Matches(msg, m.keys.Refresh) { return m, refreshServers // Command runs async } } return m, nil } ``` 3. **Efficient String Building** ```go // Good: Use strings.Builder for concatenation var s strings.Builder s.WriteString("Line 1\n") s.WriteString("Line 2\n") return s.String() // Bad: String concatenation in loop result := "" for _, item := range items { result += item + "\n" // ❌ Slow for large lists } ``` ## Contributing Guidelines ### Pull Request Process 1. **Fork the repository** 2. **Create a feature branch** ```bash git checkout -b feature/my-feature ``` 3. **Make your changes** - Follow code style guide - Update TASKS.md - Test thoroughly 4. **Commit with clear messages** ```bash git commit -m "feat: add feature description" ``` 5. **Push to your fork** ```bash git push origin feature/my-feature ``` 6. **Open a Pull Request** - Describe what changed and why - Reference any related issues - Include screenshots for UI changes ### Code Review Checklist Before requesting review: - [ ] Code follows Go conventions - [ ] All functions have doc comments - [ ] Error handling is comprehensive - [ ] TASKS.md is updated - [ ] Manual testing completed - [ ] No TODO comments left in code - [ ] Commit messages are clear ## Troubleshooting Development Issues ### "undefined: tea.Model" ```bash # Solution: Install Bubble Tea go get github.com/charmbracelet/bubbletea go mod tidy ``` ### "cannot find package" ```bash # Solution: Download dependencies go mod download ``` ### "permission denied" when building ```bash # Solution: Check file permissions chmod +x mcp-manager ``` ### Changes not reflecting ```bash # Solution: Rebuild go build -o mcp-manager ./mcp-manager ``` ## Resources ### Bubble Tea - [Official Tutorial](https://github.com/charmbracelet/bubbletea/tree/master/tutorials) - [Examples](https://github.com/charmbracelet/bubbletea/tree/master/examples) - [API Docs](https://pkg.go.dev/github.com/charmbracelet/bubbletea) ### Lip Gloss - [README](https://github.com/charmbracelet/lipgloss) - [Examples](https://github.com/charmbracelet/lipgloss/tree/master/examples) ### Go - [Effective Go](https://go.dev/doc/effective_go) - [Go Style Guide](https://google.github.io/styleguide/go/) ## Questions? - Open an issue on GitHub - Check existing documentation in `docs/` - Read the code - it's well-commented! Happy developing! 🚀