# Story 1.2: Implement Core CLI with `click` (Refactor from `argparse`)

## Status: Done

## Story

- As a Server Operator
- I want the Fabric MCP Server to have a CLI built with `click`
- so that command-line interactions are user-friendly, well-documented, and extensible

## Acceptance Criteria (ACs)

1. CLI entry point (`fabric_mcp.cli:main`) refactored to use `click`.
2. Supports commandline flag for stdio mode.
3. Supports `--log-level` (and short form `-l`) with choices and default `INFO`.
4. Supports `--version` flag.
5. Provides comprehensive `--help` via `click`.
6. No-args (without specified transport mode or info flags) prints help to stderr and exits non-zero.
7. `click`-based CLI is clear and well-structured.
8. Existing CLI tests updated for `click` and pass.

## Tasks / Subtasks

- [x] Add `click` dependency to pyproject.toml (AC: 1)
  - [x] Add `click` to dependencies section in `pyproject.toml`
  - [x] Run `uv lock` to update lock file
  - [x] Verify installation works with `make bootstrap`

- [x] Refactor CLI entry point to use `click` (AC: 1, 2, 3, 4, 5, 6, 7)
  - [x] Replace `argparse.ArgumentParser` with `click.command` decorator
  - [x] Convert `--stdio` flag to click option with proper help text
  - [x] Convert `--log-level/-l` to click option with choices and default 'info'
  - [x] Convert `--version` to click version option
  - [x] Implement click context for comprehensive help display
  - [x] Ensure no-args behavior prints help to stderr and exits with code 1
  - [x] Maintain existing log level case handling (lowercase input, uppercase internal)

- [x] Update and fix CLI tests for `click` compatibility (AC: 8)
  - [x] Update `test_cli_additional.py` to work with click's testing framework
  - [x] Replace direct `sys.argv` patches with `click.testing.CliRunner`
  - [x] Update version flag test to match click's output format
  - [x] Update help flag test for click's help display
  - [x] Update log level tests for click option handling
  - [x] Update stdio mode tests for click option handling
  - [x] Ensure all existing test scenarios continue to pass
  - [x] Add any new tests needed for click-specific behaviors

- [x] Verify CLI functionality and integration (AC: 1-8)
  - [x] Test CLI manually with all flag combinations
  - [x] Verify `fabric-mcp --version` works correctly
  - [x] Verify `fabric-mcp --help` provides comprehensive information
  - [x] Verify `fabric-mcp --stdio` launches server correctly
  - [x] Verify `fabric-mcp` with no args shows help and exits with code 1
  - [x] Verify log level options work with both long and short forms
  - [x] Run full test suite to ensure no regressions

## Dev Technical Guidance

### Current CLI Implementation Analysis

The current CLI in `src/fabric_mcp/cli.py` uses `argparse` and implements:

- Version handling via `argparse.ArgumentParser.add_argument` with `action="version"`
- Stdio mode flag (`--stdio`) as a boolean action
- Log level option (`-l, --log-level`) with choices and default 'info'
- Custom help behavior when no transport mode is specified

### Click Migration Strategy

1. **Dependency Addition**: Add `click>=8.0.0` to `pyproject.toml` dependencies section.

2. **Main Function Conversion**: Convert from function-based argparse to click decorator pattern:

   ```python
   @click.command()
   @click.option('--stdio', is_flag=True, help="Run the server in stdio mode (default).")
   @click.option('-l', '--log-level',
                 type=click.Choice(['debug', 'info', 'warning', 'error', 'critical'], case_sensitive=False),
                 default='info', help="Set the logging level (default: info)")
   @click.version_option(version=__version__, prog_name="fabric-mcp")
   def main(stdio, log_level):
   ```

3. **No-Args Behavior**: Click handles help display differently. Use click's context and check if no relevant options provided:

   ```python
   ctx = click.get_current_context()
   if not stdio:
       click.echo(ctx.get_help(), err=True)
       ctx.exit(1)
   ```

4. **Test Migration**: Replace `sys.argv` mocking with `click.testing.CliRunner`:

   ```python
   from click.testing import CliRunner
   runner = CliRunner()
   result = runner.invoke(main, ['--version'])
   ```

### Key Considerations

- **Backward Compatibility**: Ensure all current CLI behaviors are preserved
- **Case Handling**: Maintain current log level case handling (lowercase input accepted)
- **Exit Codes**: Preserve current exit code behavior (0 for success, 1 for help display)
- **Error Output**: Maintain stderr output for help when no args provided
- **Test Coverage**: Ensure all existing test scenarios continue to pass

### Files to Modify

1. `pyproject.toml` - Add click dependency
2. `src/fabric_mcp/cli.py` - Complete refactor to click
3. `tests/unit/test_cli_additional.py` - Update all tests for click
4. `uv.lock` - Will be updated automatically via `uv lock`

### Testing Strategy

- Use `click.testing.CliRunner` for all CLI tests
- Verify output format matches expectations (click may change formatting slightly)
- Test all option combinations and edge cases
- Ensure integration with logging and server startup remains intact

## Story Progress Notes

### Agent Model Used: `James - Full Stack Developer`

**Implementation Completed Successfully** ✅

**Summary of Changes:**

1. **Dependency Management**: Added `click>=8.0.0` to `pyproject.toml` and updated `uv.lock`
2. **CLI Refactor**: Complete conversion from `argparse` to `click`:
   - Replaced `ArgumentParser` with `@click.command()` decorator
   - Converted `--stdio` to click flag option
   - Converted `--log-level/-l` to click choice option with case-insensitive validation
   - Implemented `@click.version_option()` for version display
   - Added proper help display for no-args scenario with exit code 1
3. **Test Migration**: Updated `test_cli_additional.py` to use `click.testing.CliRunner`:
   - Replaced all `sys.argv` patches with CliRunner invocations
   - Updated assertions for click's output formats and exit codes
   - All 10 CLI tests passing successfully
4. **Format Updates**: Updated integration and core tests to expect click's version format (`fabric-mcp, version X.X.X`)
5. **Code Quality**: Fixed pylint warnings and maintained 9.96/10 code quality score

**All Tests Passing**: ✅ 72/72 tests passing (100% success rate)

**Manual Verification Completed**:

- `uv run fabric-mcp --version` ✅
- `uv run fabric-mcp --help` ✅
- `uv run fabric-mcp` (no args) correctly shows help to stderr and exits with code 1 ✅
- All log levels work correctly ✅
- Stdio mode functions properly ✅

**Files Modified**:

- `pyproject.toml` - Added click dependency
- `src/fabric_mcp/cli.py` - Complete CLI refactor to click
- `tests/unit/test_cli_additional.py` - Full test migration to CliRunner
- `tests/unit/test_core.py` - Updated version format expectation
- `tests/integration/test_mcp_integration.py` - Updated version format expectations
- `uv.lock` - Updated automatically with new dependencies

**Ready for Review** 🔍

### Completion Notes List

#### STORY COMPLETED SUCCESSFULLY ✅

All acceptance criteria met:

- [x] CLI successfully refactored from `argparse` to `click`
- [x] All existing functionality preserved and working
- [x] Better user experience with click's enhanced help and error messages
- [x] Improved extensibility for future CLI enhancements
- [x] All tests passing (72/72 - 100% success rate)
- [x] Code quality maintained (9.96/10 pylint score)
- [x] Manual verification completed for all CLI functions

The CLI now provides:

- Professional help formatting with click
- Better option validation and error messages
- Enhanced version display format
- Improved extensibility for future CLI features
- Robust test coverage with click.testing.CliRunner

Ready for code review and merge.

### Change Log
