# Architecture ## System Overview ClaudeCode MCP Manager is built using the Elm Architecture pattern via Bubble Tea, providing a clean separation of concerns and predictable state management. ``` ┌─────────────────────────────────────────────────────────┐ │ User Interface (TUI) │ │ Bubble Tea + Lip Gloss │ └────────────────────┬────────────────────────────────────┘ │ ┌──────────┴──────────┐ │ │ ┌─────────▼─────────┐ ┌────────▼────────┐ │ UI Components │ │ View Models │ │ - StatusBar │ │ - AddModel │ │ - Help │ │ - DeleteModel │ │ │ │ - RestoreModel │ │ │ │ - ProfileModel │ └─────────┬─────────┘ └────────┬────────┘ │ │ └──────────┬──────────┘ │ ┌──────────▼──────────┐ │ Main Model │ │ (App State) │ └──────────┬──────────┘ │ ┌─────────────┼─────────────┐ │ │ │ ┌──────▼──────┐ ┌───▼───────┐ ┌──▼────────┐ │ Config │ │ MCP │ │ Backup │ │ Management │ │ Commands │ │ System │ └─────────────┘ └───────────┘ └───────────┘ │ │ │ └─────────────┼─────────────┘ │ ┌──────────▼──────────┐ │ settings.local.json │ └─────────────────────┘ ``` ## Core Components ### 1. Model (State Management) **Location**: `internal/ui/model.go` The Model struct holds all application state: ```go type Model struct { mode ViewMode // Current view (List, Add, Delete, etc.) servers mcp.ServerList // List of MCP servers cursor int // Current selection profile *config.Profile // Active profile statusBar *components.StatusBar help *components.Help // View models for different screens addView views.AddModel deleteView views.DeleteModel restoreView views.RestoreModel profileView views.ProfileModel } ``` ### 2. Update (Event Handling) The Update function processes all events: 1. **Window resize** → Update dimensions 2. **Key presses** → Route to appropriate handler 3. **View-specific updates** → Delegate to view models 4. **State changes** → Update model, return commands ```go func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) ``` ### 3. View (Rendering) The View function renders based on current mode: ```go func (m Model) View() string { switch m.mode { case ViewList: return m.viewList() case ViewAdd: return m.addView.View() case ViewDelete: return m.deleteView.View() case ViewRestore: return m.restoreView.View() case ViewProfiles: return m.profileView.View() case ViewHelp: return m.help.Render() } } ``` ## Data Flow ### Toggle MCP Server ``` User presses Space ↓ handleListKeys() ↓ toggleCurrentServer() ↓ mcp.ToggleServer(name) ↓ config.CreateBackup() # Safety backup ↓ config.ReadConfig() ↓ config.EnableServer() or DisableServer() ↓ config.WriteConfig() # Atomic write ↓ refreshServers() ↓ Update UI ``` ### Add MCP Server ``` User presses 'a' ↓ Initialize AddModel with text inputs ↓ User fills form (Tab to navigate) ↓ User presses Enter ↓ Validate inputs ↓ mcp.AddServer(name, command, args) ↓ Execute: claude mcp add [name] [command] [args] ↓ config.CreateBackup() ↓ Update config ↓ refreshServers() ↓ Return to list view ``` ### Restore Backup ``` User presses 'r' ↓ config.ListBackups() ↓ Show backup list (timestamp, size) ↓ User navigates and selects backup ↓ User presses Enter ↓ config.CreateBackup() # Safety backup! ↓ config.RestoreBackup(path) ↓ Validate JSON integrity ↓ Atomic file replacement ↓ refreshServers() ↓ Show success message ``` ## File Structure ``` claudecode-mcp-manager/ ├── main.go # Entry point ├── internal/ │ ├── config/ # Configuration management │ │ ├── config.go # Read/write settings.local.json │ │ ├── backup.go # Backup/restore operations │ │ └── profiles.go # Profile discovery and management │ ├── mcp/ # MCP integration │ │ ├── server.go # MCP server data structures │ │ └── mcp.go # Claude CLI command wrappers │ └── ui/ # User interface │ ├── model.go # Main Bubble Tea model │ ├── view.go # View rendering │ ├── styles.go # Lip Gloss styles │ ├── keys.go # Keyboard shortcuts │ ├── components/ # Reusable UI components │ │ ├── statusbar.go │ │ └── help.go │ └── views/ # Full-screen views │ ├── add.go # Add MCP form │ ├── delete.go # Delete confirmation │ ├── restore.go # Backup restore │ └── profiles.go # Profile switcher └── docs/ # Documentation ``` ## Configuration Management ### Profile Resolution 1. Check `CLAUDE_CONFIG_DIR` environment variable 2. If set → Use that directory 3. If not set → Use `~/.claude` 4. Append `/settings.local.json` ### Config File Structure ```json { "permissions": { ... }, "enableAllProjectMcpServers": true, "enabledMcpjsonServers": [ "server-name-1", "server-name-2" ] } ``` ### Atomic Writes All config changes use atomic writes to prevent corruption: 1. Write to `settings.local.json.tmp` 2. Rename to `settings.local.json` (atomic operation) 3. Old file is replaced atomically ### Backup System - **Trigger**: Before every config write - **Format**: `settings.local.json.YYYY-MM-DD-HHMMSS.bak` - **Retention**: Keep last 10 backups, auto-cleanup older ones - **Location**: Same directory as config file ## MCP Integration ### Command Execution Wraps `claude mcp` CLI commands: ```go // List all MCPs cmd := exec.Command("claude", "mcp", "list") // Add MCP cmd := exec.Command("claude", "mcp", "add", name, command, args...) // Remove MCP cmd := exec.Command("claude", "mcp", "remove", name) ``` ### Output Parsing Parses `claude mcp list` output: ``` Checking MCP server health... fetch-mcp: node /path/to/server.js - ✓ Connected brave-search: npx -y @org/package - ✓ Connected ``` Extracted data: - Server name - Command + arguments - Connection status (Connected, Failed, etc.) ## Error Handling ### Principles 1. **Never panic** - Always return errors 2. **Wrap errors** - Add context with `fmt.Errorf` 3. **User-friendly messages** - Show clear error text in UI 4. **Graceful degradation** - Continue working when possible ### Error Display ```go if m.err != nil { errorText := styles.Error.Render(fmt.Sprintf("Error: %v", m.err)) // Show in status area } ``` ### Backup Before Destructive Operations Every operation that modifies config creates a backup first: - Toggle server - Add server (via claude mcp add) - Delete server (via claude mcp remove) - Restore backup (creates backup of current state) ## Performance Considerations ### Fast Startup - Lazy initialization of views - Views only created when needed - Config parsed once at startup ### Efficient Rendering - Only re-render on state changes - Bubble Tea handles smart diffing - Lip Gloss caches style calculations ### Minimal System Calls - Parse `claude mcp list` once - Cache server list in memory - Only refresh when explicitly requested or after changes ## Security Considerations 1. **Atomic writes** - Prevent partial file corruption 2. **Backup before changes** - Easy rollback on failure 3. **JSON validation** - Verify integrity before restore 4. **No hardcoded secrets** - Config files may contain tokens 5. **Read-only by default** - Only write when user initiates change ## Testing Strategy ### Manual Testing - Test with real `claude` command - Verify with multiple profiles (default, glm) - Test all CRUD operations (Create, Read, Update, Delete) - Verify backup/restore cycle - Check navigation and keyboard shortcuts ### Integration Points - Claude CLI must be installed - Config directory must exist - Valid JSON in settings.local.json ## Future Enhancements Potential improvements: - Unit tests for core logic - Integration tests with mock Claude CLI - Direct config editing (without Claude CLI dependency) - Batch operations (enable/disable multiple MCPs) - Import/export configurations - MCP marketplace integration