# MUMLA CLI Installation & Usage Guide

**Status**: Production Ready
**Last Updated**: March 2025

---

## Table of Contents

1. [Installation](#installation)
2. [First-Time Setup](#first-time-setup)
3. [Server Management](#server-management)
4. [Basic Usage](#basic-usage)
5. [Architecture](#architecture)
6. [Troubleshooting](#troubleshooting)

---

## Installation

### Option 1: Install from PyPI (Future - After Publishing)

```bash
pip install mumla
```

### Option 2: Install from Source (Current)

```bash
# Clone the repository
git clone https://github.com/your-org/mumla.git
cd mumla

# Install in development mode
pip install -e .

# Verify installation
mumla --help
```

**What gets installed:**
- `mumla` command-line tool
- MUMLA API server (`app/` package)
- CLI interface (`cli/` package)
- All dependencies (typer, rich, httpx, cryptography, fastapi, moorcheh-sdk, etc.)

---

## First-Time Setup

### Quick Start (Recommended - 2 Steps!)

#### Step 1: Get Moorcheh API Key

1. Go to [Moorcheh Dashboard](https://moorcheh.ai)
2. Sign up or log in
3. Navigate to API Keys section
4. Create a new API key
5. Copy the key

#### Step 2: Initialize & Start

```bash
# Initialize MUMLA
mumla init
# Enter your API key when prompted

# Start MUMLA (single command - server + CLI!)
mumla serve
```

**That's it!** The server is now running. Open a new terminal for CLI commands.

### Alternative: Manual Server Management

If you prefer to manage the server separately:

```bash
# Terminal 1: Start the server manually
python -m app.main

# Terminal 2: Initialize CLI
mumla

# Terminal 2: Use CLI commands
mumla agent create my-agent
```

**Output:**
```
+----------------------------------------+
| MUMLA CLI Initialization               |
| Setting up your MUMLA configuration... |
+----------------------------------------+

Enter your Moorcheh API key: ********

Testing connection to MUMLA server...
OK Connection successful!
Server version: 1.0.0

Configuration saved to: ~/.mumla/config.yaml

Next steps:
  1. Start MUMLA: mumla serve
  2. In another terminal, create an agent: mumla agent create my-agent

Or use the quick workflow:
  mumla serve (starts server)
```

**What happens:**
- API key is encrypted with Fernet and saved to `~/.mumla/config.yaml`
- Connection to server is tested
- CLI is ready to use!

---

## Server Management

### Recommended: Embedded Server Mode (`mumla serve`)

**Terminal 1 - Start Server:**
```bash
mumla serve
```

**Output:**
```
+--------------------------+
| MUMLA Server Starting... |
| Host: 0.0.0.0:8000       |
+--------------------------+

Starting MUMLA server...
Server URL: http://localhost:8000
API Docs: http://localhost:8000/docs
Health Check: http://localhost:8000/health

Server is running. Press CTRL+C to stop.
```

**Terminal 2 - Use CLI:**
```bash
mumla agent create my-agent
mumla agent activate my-agent
mumla remember "First memory"
```

**Pros:**
- ✅ Single command to start everything
- ✅ Beautiful terminal UI
- ✅ Built-in port conflict detection
- ✅ Clean shutdown with CTRL+C

**Options:**
```bash
mumla serve --port 8080        # Use different port
mumla serve --reload           # Auto-reload for development
mumla serve --host 127.0.0.1   # Localhost only
```

### Alternative: Manual Server Management

If you prefer to manage the server separately:

**Terminal 1 - Server:**
```bash
python -m app.main
```

**Terminal 2 - CLI:**
```bash
mumla agent create my-agent
mumla agent activate my-agent
mumla remember "First memory"
```

**Use when:**
- You want direct control over uvicorn parameters
- You're debugging server issues
- You're running in production with supervisord/systemd

---

## Basic Usage

### Complete Workflow Example

```bash
# 1. Create an agent (one-time)
mumla agent create my-assistant --pattern tool --description "My AI assistant"

# Output:
# OK Agent 'my-assistant' created successfully!
# Pattern: tool
# Description: My AI assistant

# 2. Activate the agent (starts a session)
mumla agent activate my-assistant --duration-hours 4

# Output:
# OK Agent 'my-assistant' activated!
# Session duration: 4 hours
# Session expires: 2025-12-28T10:30:00

# 3. Store memories
mumla remember "User prefers dark mode" --type preference --tags "ui,settings"
mumla remember "Implemented login feature" --type decision --tags "auth,feature"

# Output for each:
# OK Memory stored successfully!
# Memory ID: abc-123-def-456
# Type: preference | Confidence: 0.8

# 4. Search memories
mumla recall "dark mode" --limit 5

# Output:
# Found 1 memories:
#
# +--------------------------------- Memory 1 ----------------------------------+
# | User prefers dark mode                                                      |
# |                                                                             |
# | User prefers dark mode                                                      |
# |                                                                             |
# | Type: preference | Confidence: 0.80 | Score: 0.923                          |
# +-----------------------------------------------------------------------------+

# 5. Ask questions (RAG)
mumla answer "What UI preferences does the user have?"

# Output:
# +------------------------------- RAG Response --------------------------------+
# | Question: What UI preferences does the user have?                           |
# |                                                                             |
# | Answer:                                                                     |
# | Based on stored memories:                                                   |
# | - User prefers dark mode                                                    |
# +-----------------------------------------------------------------------------+

# 6. Check session status
mumla session info

# Output:
# Active Session
# +-----------------------------------------+
# | Agent ID      | my-assistant            |
# | Session Token | eyJhbGciOiJIUzI1NiI...  |
# +-----------------------------------------+

# 7. When done
mumla agent deactivate

# Output:
# OK Agent 'my-assistant' deactivated
```

### All Available Commands

```bash
# Initialization
mumla init                              # Setup CLI with API key

# Agent Management
mumla agent create AGENT_ID             # Create new agent
mumla agent list                        # List all agents
mumla agent activate AGENT_ID           # Start session
mumla agent deactivate                  # End session

# Memory Operations
mumla remember "content"                # Store memory (fact)
mumla remember "content" --type TYPE    # Store with type
mumla remember "content" --tags "a,b"   # Store with tags
mumla recall "query"                    # Search memories
mumla answer "question"                    # RAG question answering

# Session Management
mumla session info                      # Show session details
mumla session extend --hours 2          # Extend session

# Configuration
mumla config show                       # Display config

# Help
mumla --help                            # Show all commands
mumla COMMAND --help                    # Show command help
```

---

## Architecture

### How It Works

```
┌─────────────────┐
│   User Types    │
│  mumla init     │
└────────┬────────┘
         │
         ▼
┌─────────────────────────────────────┐
│  CLI (cli/main.py)                  │
│  - Typer framework                  │
│  - Rich terminal UI                 │
│  - Config management                │
│  - API client wrapper               │
└────────┬────────────────────────────┘
         │ HTTP Requests
         │ (Authorization: Bearer API_KEY)
         │ (X-Session-Token: JWT)
         ▼
┌─────────────────────────────────────┐
│  MUMLA Server (app/main.py)         │
│  - FastAPI application              │
│  - Session-based API                │
│  - JWT token management             │
│  - Agent & memory services          │
└────────┬────────────────────────────┘
         │ moorcheh-sdk
         │ (Semantic operations)
         ▼
┌─────────────────────────────────────┐
│  Moorcheh Cloud                     │
│  - No-indexing semantic database    │
│  - Instant write-to-search          │
│  - Namespace: mumla_agent_{id}      │
└─────────────────────────────────────┘
```

### File Structure

```
mumla/
├── pyproject.toml          # Package definition, entry point
├── app/                    # MUMLA Server
│   ├── main.py            # FastAPI app
│   ├── routes/            # API endpoints
│   └── services/          # Business logic
├── cli/                    # CLI Package
│   ├── main.py            # CLI entry point (Typer app)
│   ├── client/            # API client wrapper
│   │   └── api_client.py
│   └── config/            # Config management
│       ├── models.py      # Pydantic models
│       └── manager.py     # Encryption, persistence
└── ~/.mumla/               # User config (created at runtime)
    ├── config.yaml        # User configuration
    └── .key               # Encryption key (0600 permissions)
```

### Entry Point

**[pyproject.toml:25](pyproject.toml#L25)**
```toml
[project.scripts]
mumla = "cli.main:app"
```

This creates the `mumla` command that runs the Typer app in `cli/main.py`.

### Configuration File

**Location:** `~/.mumla/config.yaml` (Linux/Mac) or `C:\Users\<user>\.mumla\config.yaml` (Windows)

**Contents:**
```yaml
version: "2.0"

server:
  url: "localhost"
  port: 8000
  auto_start: false

moorcheh:
  api_key_encrypted: "gAAAAABf..."  # Fernet encrypted

session:
  default_duration_hours: 4
  auto_extend: true

cli:
  interactive_mode: true
  smart_parse: true
  color_output: true

active_agent_id: "my-assistant"
active_session_token: "eyJhbGciOiJIUzI1NiI..."
```

**Security:**
- API key encrypted with Fernet (symmetric encryption)
- Encryption key in `~/.mumla/.key` with 0600 permissions
- Never commit config files to version control

---

## Troubleshooting

### "mumla: command not found"

**Cause:** Package not installed or not in PATH

**Solution:**
```bash
# If installed with pip:
pip install mumla

# If installed from source:
cd mumla
pip install -e .

# Verify:
which mumla  # Should show path to command
mumla --help # Should work
```

### "Connection failed" Error

**Cause:** MUMLA server not running

**Check:**
```bash
# Is server running?
curl http://localhost:8000/health

# Should return:
# {"status":"healthy","service":"MUMLA","version":"1.0.0"}
```

**Solution:**
```bash
# Start server in a separate terminal
cd mumla
python -m app.main
```

### "No active agent" Error

**Cause:** Trying to use memory commands without an active session

**Solution:**
```bash
# List available agents
mumla agent list

# Activate one
mumla agent activate AGENT_ID
```

### "MUMLA not initialized" Error

**Cause:** CLI not configured

**Solution:**
```bash
mumla
# Follow the prompts
```

### Session Expired

**Cause:** JWT token expired (default: 4 hours)

**Solution:**
```bash
# Option 1: Reactivate
mumla agent activate AGENT_ID

# Option 2: Extend (if still valid)
mumla session extend --hours 4
```

### Windows Unicode Errors

All Unicode symbols (✓ ✗ ⚠ 🟢) replaced with ASCII equivalents (OK, ERROR, Warning, [Active]).

If you still see encoding errors, ensure your terminal uses UTF-8:
```bash
# PowerShell
chcp 65001

# CMD
chcp 65001
```

---

## Next Steps

1. **Try the Quick Start workflow** (5 minutes)
2. **Read the [CLI User Guide](CLI_USER_GUIDE.md)** for detailed examples
3. **Explore memory types** - fact, decision, instruction, etc.
4. **Set up automation** - Use CLI in scripts

---

## Support

- **Documentation:** [CLI_USER_GUIDE.md](CLI_USER_GUIDE.md)
- **API Reference:** [V2_QUICK_START.md](V2_QUICK_START.md)
- **Issues:** GitHub Issues
- **Moorcheh:** [moorcheh.ai/docs](https://moorcheh.ai/docs)

---

**License**: MIT
**Last Updated**: December 2025

