# CLI Guide

The MorganaBench CLI (`mb`) is a single-binary command-line tool for interacting with the MorganaBench platform. It covers corpora, specifications, benchmarks, evaluations, and custom metrics — and is designed for both interactive use and scripting by CI pipelines and AI agents.

## Installation

### One-liner install

```bash
curl -fsSL https://raw.githubusercontent.com/morganalabs/mb-cli/main/install.sh | bash
```

The installer places the `mb` binary in `/usr/local/bin`. On macOS that
directory is not writable by default, so the installer runs `sudo` and
**macOS will prompt for your login (system) password** — this is the local
`sudo` prompt, not your MorganaBench credentials. To install without `sudo`,
point it at a writable directory: `INSTALL_DIR="$HOME/.local/bin"`.

### Installing a specific version

```bash
curl -fsSL https://raw.githubusercontent.com/morganalabs/mb-cli/main/install.sh | MB_VERSION=0.4.0 bash
```

- Use the bare version number `yy.xx.zz` (e.g. `0.4.0`) — **without** a leading
  `v`. `MB_VERSION=v0.4.0` will not resolve.
- Available versions are listed on the
  [GitHub releases page](https://github.com/morganalabs/mb-cli/releases).
- Omit `MB_VERSION` to install the latest release. `mb version` prints the
  installed version; run it after installing to confirm.

## Authentication

### Interactive login

```bash
mb login --email you@example.com --password your-password
```

Use the **same email and password you use to sign in to the MorganaBench web
app** — the CLI authenticates against the same account. Run `mb login` with no
flags to be prompted interactively (the password is not echoed).

> **The email is case-sensitive.** Sign in with the exact case your account was
> registered with (e.g. `Jane.Doe@example.com`, not `jane.doe@example.com`).
> This matches the web app, which authenticates the same way against the same
> endpoint.

This stores your token in `~/.morganabench/tokens.yaml` (mode 0600). Subsequent commands use the stored token automatically.

> **Note on the API URL.** The CLI talks to the **same host as the web app** —
> for the hosted service that is `https://morganabench.morganalabs.ai`, which is
> also the default. There is no separate "API URL": the REST API is served under
> `/api/v1` on that same host. You only need `--url` (or the `mb login` prompt)
> when pointing the CLI at a different environment (e.g. a staging deployment).

### Token-based (CI / scripting)

Use `--print-token` to obtain the access token, then pass it via `--token` — no stored state needed:

```bash
TOKEN=$(mb login --url https://morganabench.example.com \
    --email "$EMAIL" --password "$PASSWORD" --print-token)

mb --url https://morganabench.example.com --token "$TOKEN" corpus list
```

### Other auth commands

```bash
mb whoami           # Show current user
mb logout           # Clear stored credentials
```

## Global Flags

| Flag | Description |
|------|-------------|
| `--url URL` | API base URL (overrides config/env) |
| `--token TOKEN` | Bearer token (overrides stored token) |
| `--output FORMAT` | Output format: `json`, `table`, `human` (default: auto-detect TTY) |
| `--quiet` | Suppress non-essential output (stderr progress) |
| `--no-wait` | For create commands: return immediately without polling |
| `--timeout SECS` | Override default polling timeout (default: 30m) |
| `--profile NAME` | Config profile name (default: `default`) |
| `--config PATH` | Path to config file (default: `~/.morganabench/config.yaml`) |
| `--dry-run` | Print what a mutating command would do, without executing it |

## Output Formats

| Format | When | Use for |
|--------|------|---------|
| `human` | Default when stdout is a TTY | Interactive use — colored tables and progress |
| `json` | Default when stdout is piped | Scripting — raw API JSON, parseable with `jq` |
| `table` | Explicit `--output table` | Shell scripting — tab-separated values |

Examples:

```bash
# Parse JSON output with jq
mb corpus list --output json | jq '.[].id'

# Human-readable table
mb corpus list --output human

# Tab-separated for awk/cut
mb corpus list --output table | cut -f1,2
```

### Example responses

Progress and status messages are written to **stderr**; the parseable result
goes to **stdout**, so `| jq` and redirects only ever see the data.

`mb login` (interactive, TTY) — human summary on stderr:

```text
Login successful
  Email:   you@example.com
  Profile: default
  URL:     https://morganabench.morganalabs.ai
  Token expires in: 3600s
```

`mb corpus create ...` (JSON stdout; the "Uploading…"/"Corpus created:" lines go to stderr):

```json
{
  "id": "019f8d88-d1ed-771d-8950-256736b50e6e",
  "status": "ready",
  "name": "Product Docs"
}
```

`mb version`:

```json
{
  "cli_version": "0.4.0",
  "commit": "abc1234",
  "date": "2026-07-23T10:00:00Z",
  "server_url": "https://morganabench.morganalabs.ai",
  "api": { "version": "0.1.0", "git_hash": "1074afe8" }
}
```

An error (exit code non-zero, message on stderr):

```text
Error: API error 404 (NOT_FOUND): Corpus 00000000-... not found
```

## Configuration

The CLI stores configuration in `~/.morganabench/`:

**`config.yaml`** — Server URL and profile settings:

```yaml
profiles:
  default:
    url: https://morganabench.example.com
    email: user@example.com
active_profile: default
```

**`tokens.yaml`** (mode 0600) — Stored authentication tokens.

Flags always take precedence over config file values.

## Commands

### System

```bash
mb ping              # Check server connectivity
mb health            # Check server health
mb version           # Show CLI and server versions
mb limits            # Show your resource limits
```

The rest of the commands are grouped by resource, one page each:

- [Corpus](corpus.md) — upload and manage source data
- [Specification](specification.md) — reusable generation recipes
- [Benchmark](benchmark.md) — generate benchmarks, including More-Like-This (MLT)
- [Metrics](metric.md) — list system and custom metrics; define and manage your own
- [Evaluation](evaluation.md) — score agent output against a benchmark

## Common Workflows

### Full pipeline (interactive)

```bash
# 1. Login
mb login --email you@example.com --password your-password

# 2. Upload corpus
mb corpus create "Product Docs" --file docs.tgz --type docs

# 3. Generate benchmark (10 cases) from a saved Library spec
mb benchmark create --corpus <corpus-id> -n 10 --spec-id <library-spec-id> --name "Product Benchmark"

# 4. Run your agent against the benchmark, save results to executed.jsonl

# 5. Evaluate
mb eval create "Agent v2 Eval" --file executed.jsonl --benchmark <benchmark-id>

# 6. Download results
mb eval download <eval-id> -o results.json
```

### Tools pipeline (tool-calling benchmarks)

```bash
# 1. Login
mb login --email you@example.com --password your-password

# 2. Upload a tools corpus (MCP-formatted JSON, or a zip/tgz archive of JSON files)
mb corpus create "API Tools" --file tools.json --type tools

# 3. Generate a tool-calling benchmark from a YAML file
#    (use --spec-id <library-spec-id> if you have a saved Library spec instead)
mb benchmark create --corpus <corpus-id> -n 10 --spec ./tools-spec.yaml --name "Tools Benchmark"

# 4. Run your agent against the benchmark, capture tool call traces to executed.jsonl

# 5. Evaluate with tool_call_correctness metric
mb eval create "Agent Tools Eval" --file executed.jsonl --benchmark <benchmark-id> --metrics tool_call_correctness

# 6. Download results
mb eval download <eval-id> -o results.json
```

### CI pipeline (scripted)

```bash
#!/bin/bash
set -euo pipefail

MB="mb --url $SERVER_URL --token $TOKEN --output json --quiet"

# Create corpus and capture ID
CORPUS_ID=$($MB corpus create "CI Corpus" --file data.tgz | jq -r '.id')

# Generate benchmark
BM_ID=$($MB benchmark create --corpus "$CORPUS_ID" -n 5 --spec ./spec.yaml --name "CI BM" | jq -r '.id')

# Run your agent
$MB benchmark download $BM_ID | run_my_agent > executed.jsonl

# Evaluate
EVAL_ID=$($MB eval create "CI Eval" --file executed.jsonl --benchmark "$BM_ID" | jq -r '.id')

# Check results
$MB eval get "$EVAL_ID" | jq '.metrics'
```

## Aliases

| Alias | Expands to |
|-------|-----------|
| `bm` | `benchmark` |
| `specification` | `spec` |
| `evaluation` | `eval` |
| `metric` | `metrics` |
| `corpora` | `corpus` |

## List Filtering

All list commands support common filtering flags:

| Flag | Description |
|------|-------------|
| `--status S` | Filter by status (repeatable) |
| `--search Q` | Text search by name |
| `--sort FIELD` | Sort field: `name`, `status`, `created_at`, `updated_at` |
| `--order DIR` | Sort direction: `asc` or `desc` |
| `--limit N` | Page size |
| `--offset N` | Items to skip |

Example:

```bash
mb corpus list --status ready --sort created_at --order desc --limit 10
```

## Polling and Waiting

By default, `create` commands poll until the resource reaches a terminal status (`ready` or `failed`). Override this behavior:

```bash
# Return immediately after creation
mb benchmark create --corpus <id> -n 10 --no-wait

# Wait separately with custom timeout
mb benchmark wait <id> --timeout 3600

# Global timeout for all waits
mb --timeout 900 benchmark create --corpus <id> -n 10
```

### What `--timeout` does (and doesn't)

`--timeout` bounds **how long the CLI waits** for a resource to reach a terminal
status (`ready`/`failed`). It is a client-side polling deadline only:

- It does **not** cancel or shorten the server-side job. Corpus indexing,
  benchmark generation, and evaluation keep running on the server after the CLI
  stops waiting.
- If the deadline elapses first, the command exits non-zero with a
  `polling timed out (last status: ...)` message; the resource may still finish
  later. Re-attach at any time with `mb <resource> wait <id>` (or check
  `mb <resource> get <id>`).
- The default is 30 minutes. A per-command `--timeout` (e.g. on
  `mb corpus wait`) takes precedence over the global `mb --timeout`.

So a short `--timeout` bounding a fast operation may look like it "had no effect"
— the resource simply became `ready` before the deadline mattered.

## Error Handling

The CLI exits with code 0 on success, non-zero on failure. Error messages are printed to stderr:

```bash
mb corpus get nonexistent-id
# Exit code: 1
# stderr: Error: GET /api/v1/corpus/nonexistent-id: 404 Not Found
```

Use `--output json` to get structured error output for programmatic handling.

## What the CLI doesn't cover

A few interactive, exploratory features in the web UI have no CLI equivalent
by design — they depend on a human reviewing generated output one item at a
time:

- **MLT candidate discovery** ("Discover more examples" in Benchmark
  Create's More-Like-This flow): the accept/reject candidate review loop.
  The CLI's [More like this](benchmark.md#more-like-this-mlt) support covers
  providing your own curated seed examples directly.
- **Sandbox** (Documents and Tools): the scratch-space preview surfaces for
  trying out guidance against a small sample of content before committing to a
  full benchmark.
- **Spec review**: the AI copilot that reviews a specification's YAML for
  issues while editing.
- **Metric preview**: the draft-config scoring preview shown while authoring
  a custom metric, before saving it — see
  [Custom metrics](metric.md#custom-metrics).

These are all editor-time aids, not part of the generate → evaluate pipeline
the CLI is built to script.