# CLAUDE.md - ClaudeCode MCP Manager Project Guide This file provides comprehensive guidance for Claude Code when working on this project. ## Project Overview **ClaudeCode MCP Manager** is a terminal user interface (TUI) application for managing Model Context Protocol (MCP) servers in Claude Code. It enables users to: - Toggle MCPs on/off to save context tokens - Manage different MCP profiles (e.g., `default` vs `glm` instances) - Create automatic backups before changes - Restore configurations from backups - Add/remove MCP servers with an intuitive interface **Important:** This tool modifies `.claude.json` files (not `settings.local.json`) to manage MCPs. Each profile has its own `.claude.json` file with isolated MCP configurations. ## CRITICAL: Safe MCP Addition Process **⚠️ NEVER use `jq` or direct JSON editing to add/modify MCPs in `.claude.json` files!** ### Why Direct Editing is Dangerous 1. **File Bloat**: `.claude.json` files can be 100-200MB (contains conversation history in `projects` field) 2. **State Corruption**: Can create invalid states where MCPs exist in both enabled AND disabled lists simultaneously 3. **No Backups**: Bypasses mcp-manager's automatic backup system 4. **Lost Fields**: Can lose important config fields during merge operations 5. **No Atomic Writes**: Risk of file corruption if interrupted ### The ONLY Safe Ways to Add MCPs #### Method 1: Use mcp-manager TUI (Recommended) ```bash # For default profile mcp-manager # For specific profile mcp-manager --profile glm # Then press 'a' to add a new MCP ``` #### Method 2: Use Claude CLI Commands ```bash # For default profile claude mcp add [args...] # For specific profile CLAUDE_CONFIG_DIR=~/.claude-glm claude mcp add [args...] ``` #### Method 3: Ask User to Use mcp-manager When a user asks to add an MCP via conversation: ``` To safely add this MCP, please run: mcp-manager --profile Then press 'a' to add a new MCP and fill in: - Name: - Command: npx - Args: -y @package/name This ensures proper backups and atomic writes. ``` ### macOS Gatekeeper Issue **Problem:** macOS blocks unsigned binaries with `[1] killed mcp-manager` **CRITICAL: Check for Running Instances First!** Before building or modifying the binary, **always** check for running instances: ```bash # Check for running instances pgrep -fl mcp-manager # If found, you MUST close all terminal windows running mcp-manager # Running instances prevent file modifications and quarantine removal! ``` **Prevention (Built into Scripts):** Our `scripts/build.sh` and `scripts/install.sh` automatically handle this: ```bash # After building on macOS if [ "$OSTYPE" = "darwin"* ]; then xattr -d com.apple.quarantine ./mcp-manager 2>/dev/null || true fi ``` **Manual Build & Install Process:** ```bash # 1. Close any running mcp-manager instances first! # 2. Remove old binary rm -f ~/.local/bin/mcp-manager # 3. Build fresh cd /path/to/claudecode-mcp-manager go build -o ~/.local/bin/mcp-manager # 4. Clear ALL extended attributes (this includes quarantine if present) xattr -cr ~/.local/bin/mcp-manager # 5. Set executable permission chmod +x ~/.local/bin/mcp-manager # 6. Verify no quarantine attribute xattr -p com.apple.quarantine ~/.local/bin/mcp-manager 2>&1 || echo "✓ Clean" # 7. Test it works mcp-manager --version ``` **Understanding macOS Extended Attributes:** - `com.apple.quarantine` - **THE PROBLEM** - Causes "[1] killed" error - `com.apple.provenance` - Harmless metadata, safe to ignore - Use `xattr -cr` to clear ALL attributes safely **If Still Getting Killed:** 1. Verify no running instances: `pgrep -fl mcp-manager` 2. Check for quarantine: `xattr -p com.apple.quarantine ~/.local/bin/mcp-manager` 3. If quarantine found: `xattr -d com.apple.quarantine ~/.local/bin/mcp-manager` 4. Test again: `mcp-manager --version` **Always test after build:** ```bash mcp-manager --version # Should output: mcp-manager v1.0.1 # If killed, check for running instances first! ``` ### Valid MCP States An MCP can be in ONE of these states: 1. **Enabled**: Exists in `.mcpServers` object only 2. **Disabled**: Exists in `._mcpManagerDisabledServers` object only 3. **INVALID**: Being in both lists simultaneously - this breaks mcp-manager! **Checking for invalid state:** ```bash # These should have NO overlap jq '.mcpServers | keys' ~/.claude.json jq '._mcpManagerDisabledServers | keys' ~/.claude.json ``` ## CRITICAL: Task Tracking System ### TASKS.md is the Single Source of Truth **ALWAYS** read and update `TASKS.md` when working on this project: 1. **Before starting ANY work**: Read `TASKS.md` to understand current progress 2. **When completing tasks**: Update checkboxes from `[ ]` to `[x]` 3. **When finding issues**: Add to "Issues & Blockers" section 4. **When making decisions**: Add to "Active Notes" section 5. **After each session**: Update "Current Work" and progress percentages ### How to Update TASKS.md ```markdown # When completing a task: - [ ] Task description → - [x] Task description # When updating progress: **Overall Progress**: X/89 tasks completed (Y%) # When changing phase: **Current Phase**: Phase N - Description # When adding notes: **Phase N Notes:** - Added note about decision/issue/solution ``` ### Task Completion Workflow 1. Mark task as `[x]` in the checklist 2. Update phase completion percentage 3. Update overall progress counter 4. Move completed items to "Completed Tasks Archive" when phase done 5. Add notes about implementation decisions/issues 6. Commit changes to Git with task reference ## Project Structure ``` claudecode-mcp-manager/ ├── CLAUDE.md # THIS FILE - your guide ├── TASKS.md # MASTER TASK TRACKER - always check this! ├── README.md # User documentation ├── main.go # Application entry point ├── go.mod / go.sum # Go dependencies ├── internal/ │ ├── config/ # Configuration management │ │ ├── config.go # .claude.json operations │ │ ├── backup.go # Backup/restore system │ │ └── profiles.go # Profile management │ ├── mcp/ # MCP integration │ │ ├── server.go # MCP server structs │ │ └── mcp.go # Claude MCP command wrapper │ └── ui/ # TUI implementation │ ├── model.go # Bubble Tea model │ ├── update.go # Event handlers │ ├── view.go # UI rendering │ ├── styles.go # Lip Gloss styles │ ├── keys.go # Key bindings │ ├── views/ # Different UI views │ └── components/ # Reusable UI components └── docs/ # Documentation ``` ## Key Technologies - **Language**: Go 1.21+ - **TUI Framework**: [Bubble Tea](https://github.com/charmbracelet/bubbletea) - The Elm Architecture for Go - **Styling**: [Lip Gloss](https://github.com/charmbracelet/lipgloss) - Terminal styling - **Components**: [Bubbles](https://github.com/charmbracelet/bubbles) - Common TUI components ## Architecture Patterns ### Bubble Tea Pattern (Model-Update-View) ```go type Model struct { // Application state } func (m Model) Init() tea.Cmd { // Initialize and return initial command } func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { // Handle events and update state } func (m Model) View() string { // Render UI based on current state } ``` ### Config Management Pattern ```go // ALWAYS create backup before modifying config config.CreateBackup() // Read config cfg, err := config.ReadConfig() // Modify config cfg.EnableServer("server-name") // Write atomically config.WriteConfig(cfg) ``` ## Development Guidelines ### When Adding New Features 1. **Check TASKS.md first** - Is this feature planned? 2. Add new tasks to TASKS.md if needed 3. Implement the feature 4. Update TASKS.md checkboxes 5. Test thoroughly 6. Commit with descriptive message referencing task 7. Update "Active Notes" in TASKS.md ### When Fixing Bugs 1. Add to "Issues & Blockers" in TASKS.md 2. Describe the bug and proposed solution 3. Implement fix 4. Test fix 5. Move issue to "Resolved Issues" 6. Commit with reference to issue ### Code Style - **Errors**: Always return errors, don't panic - **Comments**: Document exported functions and complex logic - **Naming**: Use clear, descriptive names - **Testing**: Test with real `claude mcp` commands - **Validation**: Validate inputs before using them ### Profile Awareness This tool must work with **multiple Claude Code instances**: ```bash # Default Claude instance mcp-manager # GLM instance (different profile) export CLAUDE_CONFIG_DIR=~/.claude-glm mcp-manager ``` **Always test with both profiles!** ## Testing Workflow ### Manual Testing Checklist - [ ] Test with default profile (`~/.claude/`) - [ ] Test with GLM profile (`~/.claude-glm/`) - [ ] Verify backups are created before changes - [ ] Test restore from backup - [ ] Test toggle on/off (check settings.local.json) - [ ] Test add new MCP - [ ] Test delete MCP - [ ] Verify `claude mcp list` parsing works - [ ] Test navigation (up/down/j/k) - [ ] Test all keyboard shortcuts ### Testing MCP Operations ```bash # Test listing servers go run main.go # Verify it parses this correctly: claude mcp list # Should show: # fetch-mcp: node /path/to/server.js - ✓ Connected # brave-search: npx -y @server - ✓ Connected ``` ## Common Tasks ### Building the Application **Quick Development Build:** ```bash go build -o mcp-manager ./mcp-manager ``` **Production Build & Install (Recommended):** ```bash # STEP 1: Check for running instances FIRST! pgrep -fl mcp-manager # If found, close all mcp-manager terminal windows # STEP 2: Remove old binary rm -f ~/.local/bin/mcp-manager # STEP 3: Build fresh to install location go build -o ~/.local/bin/mcp-manager # STEP 4: Clear extended attributes (removes quarantine) xattr -cr ~/.local/bin/mcp-manager # STEP 5: Ensure executable chmod +x ~/.local/bin/mcp-manager # STEP 6: Verify it works mcp-manager --version ``` **Important Notes:** - **Always** check for running instances before rebuilding - Running instances prevent file modifications on macOS - Use `xattr -cr` to clear ALL extended attributes (safer than `-d`) - The `@` symbol in `ls -l` output is normal (just metadata) - Only `com.apple.quarantine` attribute causes issues ### Running Tests ```bash go test ./... ``` ### Checking Dependencies ```bash go mod tidy go mod verify ``` ### Updating TASKS.md After Work Session ```markdown ## Active Notes ### Current Work - Updated to reflect what was just completed - Next steps clearly outlined ### Decisions Made - Add any architectural decisions made - Explain why choices were made ## Progress Tracking - Update task counts - Update percentages - Mark phase status (⬜ ⏳ ✅) ``` ## Important Files to Maintain ### TASKS.md - **Purpose**: Track all development tasks and progress - **Update**: Every time you complete a task - **Format**: Markdown with checkboxes ### README.md - **Purpose**: User-facing documentation - **Update**: When adding user-visible features - **Format**: GitHub-flavored Markdown ### Go Files - **Purpose**: Application code - **Update**: When implementing features - **Format**: Standard Go formatting (`go fmt`) ## Git Workflow ### Commit Message Format ``` : [optional body] Phase X task: ``` **Types**: `feat`, `fix`, `docs`, `refactor`, `test`, `chore` **Examples**: ``` feat: implement backup restore UI - Add restore view with backup selection - Show backup timestamp and MCP count - Create safety backup before restore Phase 4 task: Implement backup/restore UI ``` ### When to Commit - After completing a logical unit of work - After completing a phase - Before switching tasks - When TASKS.md shows significant progress ## Phase-Specific Guidelines ### Phase 0 & 1: ✅ COMPLETE No work needed - infrastructure is done! ### Phase 2: TUI Foundation (Current) Focus on: - Basic Bubble Tea structure - Main list view with navigation - Status bar component - Styling with Lip Gloss **Key files**: `internal/ui/model.go`, `styles.go`, `view.go` ### Phase 3: Main Features Focus on: - Toggle functionality (already implemented in backend) - Add MCP form - Delete confirmation - Wire up backend to UI ### Phase 4: Advanced Features Focus on: - Backup/restore UI - Profile switcher - Error handling ### Phase 5: Polish Focus on: - Testing - Documentation - Installation scripts ## Error Handling Principles 1. **Never panic** - Return errors up the stack 2. **Wrap errors** - Add context: `fmt.Errorf("context: %w", err)` 3. **Validate early** - Check inputs before operations 4. **Backup first** - Always backup before destructive operations 5. **User-friendly** - Show clear error messages in UI ## Profile System Details ### How Profiles Work ```go // Default profile CLAUDE_CONFIG_DIR="" → ~/.claude.json // GLM profile CLAUDE_CONFIG_DIR=~/.claude-glm → ~/.claude-glm/.claude.json ``` ### Profile Discovery The `config.ListProfiles()` function finds all `~/.claude*` directories: - `~/.claude` → "default" profile - `~/.claude-glm` → "glm" profile - `~/.claude-staging` → "staging" profile ## MCP Command Integration ### Expected Output Format ```bash $ claude mcp list Checking MCP server health... fetch-mcp: node /Users/user/path/index.js - ✓ Connected brave-search: npx -y @modelcontextprotocol/server-brave-search - ✓ Connected ``` ### Parsing Logic The `mcp.parseServerLine()` function expects: ``` : - ``` **If format changes**, update the parser! ## UI/UX Principles 1. **Vim-style navigation** - hjkl + arrow keys 2. **Clear status indicators** - ✓ □ ● ○ 3. **Instant feedback** - Show changes immediately 4. **Safe operations** - Confirm destructive actions 5. **Help available** - Press `h` or `?` for help ## Performance Considerations - **Fast startup** - < 1 second to launch - **Responsive UI** - No blocking operations - **Efficient parsing** - Parse `claude mcp list` once - **Minimal writes** - Only write config when changed ## Security Considerations - **Atomic writes** - Use temp file + rename - **Backup before changes** - Always create backup - **Validate JSON** - Check JSON integrity before restore - **No secrets in code** - Config files may contain tokens ## Debugging Tips ### Enable Debug Logging ```go 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() } ``` ### Common Issues **"claude mcp list not found"** - User doesn't have Claude Code CLI installed - Show helpful error message **"Failed to parse config"** - settings.local.json has invalid JSON - Show error, offer to create backup and reset **"Permission denied"** - Can't write to ~/.claude/ - Check directory permissions ## Future Enhancements (Ideas) - [ ] MCP marketplace integration (browse available MCPs) - [ ] Configuration diff viewer - [ ] Export/import configs - [ ] Multi-profile bulk operations - [ ] MCP usage analytics - [ ] Custom MCP groups/tags ## Questions to Ask Yourself Before making changes: 1. Is this aligned with TASKS.md? 2. Have I created a backup if modifying config? 3. Will this work with multiple profiles? 4. Have I tested with real `claude mcp` commands? 5. Have I updated TASKS.md? 6. Is the code clear and well-commented? 7. Does this follow the established patterns? ## Getting Help - **Bubble Tea Docs**: https://github.com/charmbracelet/bubbletea/tree/master/tutorials - **Lip Gloss Docs**: https://github.com/charmbracelet/lipgloss - **Go Docs**: https://pkg.go.dev/ ## Remember 🎯 **TASKS.md is king** - Always read it, always update it 💾 **Backup before changes** - Safety first ✅ **Test with both profiles** - Default and GLM 📝 **Document decisions** - Update "Active Notes" 🚀 **Commit often** - Small, logical commits --- **Happy Coding! 🎨**