|
| 1 | +# CLI Architecture |
| 2 | + |
| 3 | +This article documents the architectural design of Hatch's command-line interface, which underwent a significant refactoring from a monolithic structure to a modular, handler-based architecture. |
| 4 | + |
| 5 | +## Overview |
| 6 | + |
| 7 | +The Hatch CLI provides a comprehensive interface for managing MCP server packages, environments, and host configurations. The architecture emphasizes: |
| 8 | + |
| 9 | +- **Modularity**: Commands organized into focused handler modules |
| 10 | +- **Consistency**: Unified output formatting across all commands |
| 11 | +- **Extensibility**: Easy addition of new commands and features |
| 12 | +- **Testability**: Clear separation of concerns for unit testing |
| 13 | + |
| 14 | +## Architecture Components |
| 15 | + |
| 16 | +### Entry Point (`hatch/cli/__main__.py`) |
| 17 | + |
| 18 | +The entry point module serves as the routing layer: |
| 19 | + |
| 20 | +1. **Argument Parsing**: Uses `argparse` with custom `HatchArgumentParser` for formatted error messages |
| 21 | +2. **Manager Initialization**: Creates shared `HatchEnvironmentManager` and `MCPHostConfigurationManager` instances |
| 22 | +3. **Manager Attachment**: Attaches managers to the `args` namespace for handler access |
| 23 | +4. **Command Routing**: Routes parsed commands to appropriate handler modules |
| 24 | + |
| 25 | +**Key Pattern**: |
| 26 | +```python |
| 27 | +# Managers initialized once and shared across handlers |
| 28 | +env_manager = HatchEnvironmentManager(...) |
| 29 | +mcp_manager = MCPHostConfigurationManager() |
| 30 | + |
| 31 | +# Attached to args for handler access |
| 32 | +args.env_manager = env_manager |
| 33 | +args.mcp_manager = mcp_manager |
| 34 | + |
| 35 | +# Routed to handlers |
| 36 | +return _route_env_command(args) |
| 37 | +``` |
| 38 | + |
| 39 | +### Handler Modules |
| 40 | + |
| 41 | +Commands are organized into four domain-specific handler modules: |
| 42 | + |
| 43 | +#### `cli_env.py` - Environment Management |
| 44 | +Handles environment lifecycle and Python environment operations: |
| 45 | +- `handle_env_create()`: Create new environments |
| 46 | +- `handle_env_remove()`: Remove environments with confirmation |
| 47 | +- `handle_env_list()`: List environments with table output |
| 48 | +- `handle_env_use()`: Set current environment |
| 49 | +- `handle_env_current()`: Show current environment |
| 50 | +- `handle_env_show()`: Detailed hierarchical environment view |
| 51 | +- `handle_env_list_hosts()`: Environment/host/server deployments |
| 52 | +- `handle_env_list_servers()`: Environment/server/host deployments |
| 53 | +- `handle_env_python_*()`: Python environment operations |
| 54 | + |
| 55 | +#### `cli_package.py` - Package Management |
| 56 | +Handles package installation and synchronization: |
| 57 | +- `handle_package_add()`: Add packages to environments |
| 58 | +- `handle_package_remove()`: Remove packages with confirmation |
| 59 | +- `handle_package_list()`: List packages (deprecated - use `env list`) |
| 60 | +- `handle_package_sync()`: Synchronize package MCP servers to hosts |
| 61 | +- `_configure_packages_on_hosts()`: Shared configuration logic |
| 62 | + |
| 63 | +#### `cli_mcp.py` - MCP Host Configuration |
| 64 | +Handles MCP host platform configuration and backup: |
| 65 | +- `handle_mcp_discover_hosts()`: Detect available host platforms |
| 66 | +- `handle_mcp_list_hosts()`: Host-centric server listing |
| 67 | +- `handle_mcp_list_servers()`: Server-centric host listing |
| 68 | +- `handle_mcp_show_hosts()`: Detailed host configurations |
| 69 | +- `handle_mcp_show_servers()`: Detailed server configurations |
| 70 | +- `handle_mcp_configure()`: Configure servers on hosts |
| 71 | +- `handle_mcp_backup_*()`: Backup management operations |
| 72 | +- `handle_mcp_remove_*()`: Server and host removal |
| 73 | +- `handle_mcp_sync()`: Synchronize configurations |
| 74 | + |
| 75 | +#### `cli_system.py` - System Operations |
| 76 | +Handles package creation and validation: |
| 77 | +- `handle_create()`: Generate package templates |
| 78 | +- `handle_validate()`: Validate package structure |
| 79 | + |
| 80 | +### Shared Utilities (`cli_utils.py`) |
| 81 | + |
| 82 | +The utilities module provides infrastructure used across all handlers: |
| 83 | + |
| 84 | +#### Color System |
| 85 | +- **`Color` enum**: HCL color palette with true color support and 16-color fallback |
| 86 | +- **Dual-tense colors**: Dim colors for prompts (present tense), bright colors for results (past tense) |
| 87 | +- **Semantic mapping**: Colors mapped to action categories (green=constructive, red=destructive, etc.) |
| 88 | +- **`_colors_enabled()`**: Respects `NO_COLOR` environment variable and TTY detection |
| 89 | + |
| 90 | +#### ConsequenceType System |
| 91 | +- **`ConsequenceType` enum**: Action types with dual-tense labels |
| 92 | +- **Prompt labels**: Present tense for confirmation (e.g., "CREATE") |
| 93 | +- **Result labels**: Past tense for execution (e.g., "CREATED") |
| 94 | +- **Color association**: Each type has prompt and result colors |
| 95 | +- **Categories**: Constructive, Recovery, Destructive, Modification, Transfer, Informational, No-op |
| 96 | + |
| 97 | +#### ResultReporter |
| 98 | +Unified rendering system for all CLI output: |
| 99 | + |
| 100 | +**Key Features**: |
| 101 | +- Tracks consequences (actions to be performed) |
| 102 | +- Generates confirmation prompts (present tense, dim colors) |
| 103 | +- Reports execution results (past tense, bright colors) |
| 104 | +- Supports nested consequences (resource → field level) |
| 105 | +- Handles dry-run mode with suffix labels |
| 106 | +- Provides error and partial success reporting |
| 107 | + |
| 108 | +**Usage Pattern**: |
| 109 | +```python |
| 110 | +reporter = ResultReporter("hatch env create", dry_run=False) |
| 111 | +reporter.add(ConsequenceType.CREATE, "Environment 'dev'") |
| 112 | +reporter.add(ConsequenceType.CREATE, "Python environment (3.11)") |
| 113 | + |
| 114 | +# Show prompt and get confirmation |
| 115 | +prompt = reporter.report_prompt() |
| 116 | +if prompt: |
| 117 | + print(prompt) |
| 118 | +if not request_confirmation("Proceed?"): |
| 119 | + return EXIT_SUCCESS |
| 120 | + |
| 121 | +# Execute operation... |
| 122 | + |
| 123 | +# Report results |
| 124 | +reporter.report_result() |
| 125 | +``` |
| 126 | + |
| 127 | +#### TableFormatter |
| 128 | +Aligned table output for list commands: |
| 129 | + |
| 130 | +**Features**: |
| 131 | +- Fixed and auto-calculated column widths |
| 132 | +- Left/right/center alignment support |
| 133 | +- Automatic truncation with ellipsis |
| 134 | +- Consistent header and separator rendering |
| 135 | + |
| 136 | +**Usage Pattern**: |
| 137 | +```python |
| 138 | +columns = [ |
| 139 | + ColumnDef(name="Name", width=20), |
| 140 | + ColumnDef(name="Status", width=10), |
| 141 | + ColumnDef(name="Count", width="auto", align="right"), |
| 142 | +] |
| 143 | +formatter = TableFormatter(columns) |
| 144 | +formatter.add_row(["my-env", "active", "5"]) |
| 145 | +print(formatter.render()) |
| 146 | +``` |
| 147 | + |
| 148 | +#### Error Formatting |
| 149 | +- **`ValidationError`**: Structured validation errors with field and suggestion |
| 150 | +- **`format_validation_error()`**: Formatted error output with color |
| 151 | +- **`format_info()`**: Info messages with [INFO] prefix |
| 152 | +- **`format_warning()`**: Warning messages with [WARNING] prefix |
| 153 | + |
| 154 | +#### Parsing Utilities |
| 155 | +- **`parse_env_vars()`**: Parse KEY=VALUE environment variables |
| 156 | +- **`parse_header()`**: Parse KEY=VALUE HTTP headers |
| 157 | +- **`parse_input()`**: Parse VS Code input variable definitions |
| 158 | +- **`parse_host_list()`**: Parse comma-separated hosts or 'all' |
| 159 | +- **`get_package_mcp_server_config()`**: Extract MCP config from package metadata |
| 160 | + |
| 161 | +## Handler Signature Convention |
| 162 | + |
| 163 | +All handlers follow a consistent signature: |
| 164 | + |
| 165 | +```python |
| 166 | +def handle_command(args: Namespace) -> int: |
| 167 | + """Handle 'hatch command' command. |
| 168 | + |
| 169 | + Args: |
| 170 | + args: Namespace with: |
| 171 | + - env_manager: HatchEnvironmentManager instance |
| 172 | + - mcp_manager: MCPHostConfigurationManager instance (if needed) |
| 173 | + - <command-specific arguments> |
| 174 | + |
| 175 | + Returns: |
| 176 | + Exit code (0 for success, 1 for error) |
| 177 | + """ |
| 178 | +``` |
| 179 | + |
| 180 | +**Key Invariants**: |
| 181 | +- Managers accessed via `args.env_manager` and `args.mcp_manager` |
| 182 | +- Return `EXIT_SUCCESS` (0) on success, `EXIT_ERROR` (1) on failure |
| 183 | +- Use `ResultReporter` for unified output |
| 184 | +- Handle dry-run mode consistently |
| 185 | +- Request confirmation for destructive operations |
| 186 | + |
| 187 | +## Output Formatting Standards |
| 188 | + |
| 189 | +### Mutation Commands |
| 190 | +Commands that modify state follow this pattern: |
| 191 | + |
| 192 | +1. **Build consequences**: Add all actions to `ResultReporter` |
| 193 | +2. **Show prompt**: Display present-tense preview with dim colors |
| 194 | +3. **Request confirmation**: Use `request_confirmation()` unless auto-approved |
| 195 | +4. **Execute**: Perform the actual operations |
| 196 | +5. **Report results**: Display past-tense results with bright colors |
| 197 | + |
| 198 | +### List Commands |
| 199 | +Commands that display data use `TableFormatter`: |
| 200 | + |
| 201 | +1. **Define columns**: Specify widths and alignment |
| 202 | +2. **Add rows**: Populate with data |
| 203 | +3. **Render**: Print formatted table with headers and separator |
| 204 | + |
| 205 | +### Show Commands |
| 206 | +Commands that display detailed views use hierarchical output: |
| 207 | + |
| 208 | +1. **Header**: Entity name with `highlight()` for emphasis |
| 209 | +2. **Metadata**: Key-value pairs with indentation |
| 210 | +3. **Sections**: Grouped related information |
| 211 | +4. **Separators**: Use `═` for visual separation between entities |
| 212 | + |
| 213 | +## Exit Code Standards |
| 214 | + |
| 215 | +- **`EXIT_SUCCESS` (0)**: Operation completed successfully |
| 216 | +- **`EXIT_ERROR` (1)**: Operation failed or validation error |
| 217 | +- **Partial success**: Return `EXIT_ERROR` but use `report_partial_success()` |
| 218 | + |
| 219 | +## Design Principles |
| 220 | + |
| 221 | +### Separation of Concerns |
| 222 | +- **Routing**: `__main__.py` handles argument parsing and routing only |
| 223 | +- **Business logic**: Handler modules implement command logic |
| 224 | +- **Presentation**: `cli_utils.py` provides formatting infrastructure |
| 225 | +- **Domain logic**: Managers (`HatchEnvironmentManager`, `MCPHostConfigurationManager`) handle state |
| 226 | + |
| 227 | +### DRY (Don't Repeat Yourself) |
| 228 | +- Shared utilities in `cli_utils.py` eliminate duplication |
| 229 | +- `ResultReporter` provides consistent output across all commands |
| 230 | +- `TableFormatter` standardizes list output |
| 231 | +- Parsing utilities handle common argument formats |
| 232 | + |
| 233 | +### Consistency |
| 234 | +- All handlers follow the same signature pattern |
| 235 | +- All mutation commands use `ResultReporter` |
| 236 | +- All list commands use `TableFormatter` |
| 237 | +- All errors use structured formatting |
| 238 | + |
| 239 | +### Testability |
| 240 | +- Handlers are pure functions (input → output) |
| 241 | +- Managers injected via `args` namespace (dependency injection) |
| 242 | +- Clear separation between CLI and business logic |
| 243 | +- Utilities are independently testable |
| 244 | + |
| 245 | +## Command Organization |
| 246 | + |
| 247 | +### Namespace Structure |
| 248 | +``` |
| 249 | +hatch |
| 250 | +├── create <name> # System: Package template creation |
| 251 | +├── validate <path> # System: Package validation |
| 252 | +├── env # Environment management |
| 253 | +│ ├── create <name> |
| 254 | +│ ├── remove <name> |
| 255 | +│ ├── list [hosts|servers] |
| 256 | +│ ├── use <name> |
| 257 | +│ ├── current |
| 258 | +│ ├── show <name> |
| 259 | +│ └── python |
| 260 | +│ ├── init |
| 261 | +│ ├── info |
| 262 | +│ ├── remove |
| 263 | +│ ├── shell |
| 264 | +│ └── add-hatch-mcp |
| 265 | +├── package # Package management |
| 266 | +│ ├── add <name> |
| 267 | +│ ├── remove <name> |
| 268 | +│ ├── list (deprecated) |
| 269 | +│ └── sync <name> |
| 270 | +└── mcp # MCP host configuration |
| 271 | + ├── discover |
| 272 | + │ ├── hosts |
| 273 | + │ └── servers |
| 274 | + ├── list |
| 275 | + │ ├── hosts |
| 276 | + │ └── servers |
| 277 | + ├── show |
| 278 | + │ ├── hosts |
| 279 | + │ └── servers |
| 280 | + ├── configure <host> <server> |
| 281 | + ├── remove |
| 282 | + │ ├── server <name> |
| 283 | + │ └── host <name> |
| 284 | + ├── sync |
| 285 | + └── backup |
| 286 | + ├── restore <host> |
| 287 | + ├── list <host> |
| 288 | + └── clean <host> |
| 289 | +``` |
| 290 | + |
| 291 | +## Related Documentation |
| 292 | + |
| 293 | +- [Adding CLI Commands](../implementation_guides/adding_cli_commands.md): Step-by-step guide for adding new commands |
| 294 | +- [Component Architecture](./component_architecture.md): Overall system architecture |
| 295 | +- [CLI Reference](../../users/CLIReference.md): User-facing command documentation |
0 commit comments