> ## Documentation Index
> Fetch the complete documentation index at: https://docs.mutagent.io/llms.txt
> Use this file to discover all available pages before exploring further.

# CLI Commands

> Complete MutagenT CLI command reference

# CLI Command Reference

<Tip>
  Use `mutagent <command> --help` for detailed help on any command. Add `--json` to any command for machine-readable output.
</Tip>

## Global Options

These options apply to all commands:

| Option              | Description                                                         |
| ------------------- | ------------------------------------------------------------------- |
| `--json`            | Output results as JSON for machine-readable output                  |
| `--non-interactive` | Disable all interactive prompts (also enabled by `CI=true` env var) |
| `--api-key <key>`   | Override API key for this command                                   |
| `--endpoint <url>`  | Override API endpoint                                               |
| `--help`            | Show help for any command                                           |
| `-v, --version`     | Show CLI version                                                    |

<Note>
  **JSON output** includes `_links` objects with deep links to the corresponding resource on [app.mutagent.io](https://app.mutagent.io). This is useful for AI agents that need to reference the web UI.

  ```json theme={null}
  {
    "data": { ... },
    "_links": {
      "self": "https://app.mutagent.io/prompts/123",
      "dashboard": "https://app.mutagent.io/dashboard"
    }
  }
  ```
</Note>

### Environment Variables

| Variable                        | Description                    |
| ------------------------------- | ------------------------------ |
| `MUTAGENT_API_KEY`              | API key (skips login entirely) |
| `MUTAGENT_ENDPOINT`             | Custom API endpoint            |
| `MUTAGENT_NON_INTERACTIVE=true` | Non-interactive mode           |
| `CI=true`                       | Enables non-interactive mode   |

***

## Authentication

### `mutagent login`

Top-level shortcut for `mutagent auth login`. Opens an interactive login flow.

```bash theme={null}
mutagent login
mutagent login --browser
mutagent login --non-interactive
```

| Option              | Description                                             |
| ------------------- | ------------------------------------------------------- |
| `--browser`         | Force browser-based OAuth authentication                |
| `--non-interactive` | Disable interactive prompts (auto-selects browser auth) |
| `--endpoint <url>`  | API endpoint (default: `https://api.mutagent.io`)       |

### `mutagent auth login`

Authenticate with MutagenT. In interactive mode, prompts you to choose between browser OAuth and API key entry. In non-interactive mode, auto-selects browser auth.

```bash theme={null}
# Interactive (choose method)
mutagent auth login

# Browser OAuth flow
mutagent auth login --browser

# Non-interactive auto browser flow (AI agents)
mutagent auth login --non-interactive
```

| Option              | Description                                             |
| ------------------- | ------------------------------------------------------- |
| `--browser`         | Force browser-based OAuth authentication                |
| `--non-interactive` | Disable interactive prompts (auto-selects browser auth) |
| `--endpoint <url>`  | API endpoint (default: `https://api.mutagent.io`)       |

<Note>
  For CI/CD pipelines, set the `MUTAGENT_API_KEY` environment variable instead of using `auth login`. The CLI picks it up automatically -- no login step required. You can also pass the global `--api-key` flag to any command.
</Note>

<Tip>
  On successful login, the CLI auto-detects your organization and workspace. If you have multiple organizations or workspaces, you will be prompted to select one (interactive mode only).
</Tip>

### `mutagent auth status`

Check authentication status. Validates the stored API key against the server. Shows onboarding completion state, `.mutagent/mutation-context.md` presence, and resource counts (prompts, datasets, evaluations).

```bash theme={null}
mutagent auth status
mutagent auth status --json
```

### `mutagent auth logout`

Clear stored credentials.

```bash theme={null}
mutagent auth logout
```

***

## Configuration

### `mutagent config list`

Display all configuration values. The API key is masked for security.

```bash theme={null}
mutagent config list
mutagent config list --json
```

### `mutagent config get <key>`

Get a specific configuration value.

```bash theme={null}
mutagent config get endpoint
mutagent config get defaultWorkspace
mutagent config get defaultOrganization
mutagent config get apiKey
```

| Key                   | Description                       |
| --------------------- | --------------------------------- |
| `apiKey`              | Stored API key (masked in output) |
| `endpoint`            | API endpoint URL                  |
| `format`              | Output format preference          |
| `timeout`             | Request timeout                   |
| `defaultWorkspace`    | Default workspace ID              |
| `defaultOrganization` | Default organization ID           |

### `mutagent config set workspace <id>`

Set the default workspace ID. Persists so you do not need to pass headers on every request.

```bash theme={null}
mutagent config set workspace ws_abc123
```

### `mutagent config set org <id>`

Set the default organization ID. Required for org-scoped API keys.

```bash theme={null}
mutagent config set org org_abc123
```

***

## Prompts

### `mutagent prompts list`

List all prompts.

```bash theme={null}
mutagent prompts list
mutagent prompts list --limit 10
mutagent prompts list --json
```

| Option            | Description           | Default |
| ----------------- | --------------------- | ------- |
| `-l, --limit <n>` | Max prompts to return | `50`    |

### `mutagent prompts get <id>`

Get prompt details with optional nested data.

```bash theme={null}
mutagent prompts get <id>
mutagent prompts get <id> --with-datasets --with-evals
mutagent prompts get <id> --json
```

| Option            | Description                |
| ----------------- | -------------------------- |
| `--with-datasets` | Include linked datasets    |
| `--with-evals`    | Include evaluation history |

### `mutagent prompts create`

Create a new prompt. Supports multiple input methods.

```bash theme={null}
# System + Human with output schema (recommended)
mutagent prompts create --name "classifier" --system "Classify emails" --human "{email}" --output-schema '{"type":"object","properties":{"category":{"type":"string"}}}'

# Inline raw prompt with template variables
mutagent prompts create --name "raw-prompt" --raw "Summarize: {text}"

# System + human message pair
mutagent prompts create --name "my-prompt" --system "You are helpful" --human "Hello"

# Full messages array
mutagent prompts create --name "chat" --messages '[{"role":"system","content":"..."}]'
```

| Option                    | Description                                        |
| ------------------------- | -------------------------------------------------- |
| `-n, --name <name>`       | Prompt name                                        |
| `--description <text>`    | Prompt description (shown in dashboard)            |
| `-r, --raw <text>`        | Raw prompt text (single prompt with `{variables}`) |
| `--system <text>`         | System prompt (use with `--human`)                 |
| `--human <text>`          | Human/user prompt (use with `--system`)            |
| `--messages <json>`       | Full messages array as JSON                        |
| `--output-schema <json>`  | Output schema as JSON (required for optimization)  |
| `-c, --content <content>` | Prompt content (deprecated, use `--raw`)           |

<Note>
  Input methods (pick one, priority order): `--system/--human` > `--raw` > `--messages`.
</Note>

<Warning>
  `outputSchema` is required for optimization. Provide it via `--output-schema`. In interactive mode, you will be prompted if missing.
</Warning>

### `mutagent prompts update <id>`

Update an existing prompt.

```bash theme={null}
mutagent prompts update <id> --name "new-name"
mutagent prompts update <id> --system "Updated system prompt"
mutagent prompts update <id> --raw "Updated raw prompt"
```

| Option                        | Description                           |
| ----------------------------- | ------------------------------------- |
| `-n, --name <name>`           | New name                              |
| `--description <text>`        | New description                       |
| `-r, --raw <text>`            | New raw prompt text                   |
| `--system <text>`             | New system prompt                     |
| `--human <text>`              | New human prompt                      |
| `--messages <json>`           | New messages array as JSON            |
| `--input-schema <json>`       | Input schema as JSON string           |
| `--input-schema-file <path>`  | Input schema from JSON file           |
| `--output-schema <json>`      | Output schema as JSON string          |
| `--output-schema-file <path>` | Output schema from JSON file          |
| `-c, --content <content>`     | New content (deprecated, use `--raw`) |

### `mutagent prompts delete <id>`

Delete a prompt.

```bash theme={null}
mutagent prompts delete <id>
mutagent prompts delete <id> --force
mutagent prompts delete <id> --force --json
```

| Option    | Description                                                      |
| --------- | ---------------------------------------------------------------- |
| `--force` | Skip confirmation prompt (required for non-interactive/CI usage) |

***

## Datasets

Datasets are scoped to prompts and managed via the `prompts dataset` subcommand group.

### `mutagent prompts dataset list <prompt-id>`

List datasets for a prompt.

```bash theme={null}
mutagent prompts dataset list <prompt-id>
mutagent prompts dataset list <prompt-id> --json
```

### `mutagent prompts dataset add <prompt-id>`

Add a dataset to a prompt.

```bash theme={null}
# Inline JSON data
mutagent prompts dataset add <prompt-id> -d '[{"input":{"text":"hello"},"expectedOutput":{"result":"world"}}]'

# With a custom name
mutagent prompts dataset add <prompt-id> -d '[...]' --name "My Dataset"
```

| Option              | Description                         |
| ------------------- | ----------------------------------- |
| `-d, --data <json>` | Inline JSON array of dataset items  |
| `-n, --name <name>` | Dataset name (default: timestamped) |

### `mutagent prompts dataset delete <prompt-id> <dataset-id>`

Delete a dataset from a prompt.

```bash theme={null}
mutagent prompts dataset delete <prompt-id> <dataset-id>
mutagent prompts dataset delete <prompt-id> <dataset-id> --force
```

| Option    | Description              |
| --------- | ------------------------ |
| `--force` | Skip confirmation prompt |

***

## Evaluations

Evaluations are scoped to prompts and managed via the `prompts evaluation` subcommand group.

### `mutagent prompts evaluation list <prompt-id>`

List evaluations for a prompt.

```bash theme={null}
mutagent prompts evaluation list <prompt-id>
mutagent prompts evaluation list <prompt-id> --json
```

### `mutagent prompts evaluation get <evaluation-id>`

Get evaluation details including criteria.

```bash theme={null}
mutagent prompts evaluation get <evaluation-id>
mutagent prompts evaluation get <evaluation-id> --json
```

### `mutagent prompts evaluation create <prompt-id>`

Create an evaluation configuration for a prompt. Evaluations define the criteria used to score prompt outputs during optimization.

```bash theme={null}
# Guided mode (interactive -- builds criteria step by step)
mutagent prompts evaluation create <prompt-id> --guided

# Inline JSON (for pre-validated criteria)
mutagent prompts evaluation create <prompt-id> -d '{"name":"Accuracy","evalConfig":{"criteria":[...]}}'

# Basic evaluation
mutagent prompts evaluation create <prompt-id> --name "Accuracy Check"

# With description
mutagent prompts evaluation create <prompt-id> --name "QA" --description "Quality assurance eval"
```

| Option                 | Description                                            |
| ---------------------- | ------------------------------------------------------ |
| `-d, --data <json>`    | Evaluation as JSON string (for pre-validated criteria) |
| `-n, --name <name>`    | Evaluation name (required unless using `--guided`)     |
| `--description <text>` | Evaluation description                                 |
| `--guided`             | Interactive guided mode -- build criteria step by step |

<Tip>
  Use `--guided` for an interactive walkthrough that fetches the prompt's `outputSchema` and helps you build criteria targeting specific output fields.
</Tip>

### `mutagent prompts evaluation delete <evaluation-id>`

Delete an evaluation.

```bash theme={null}
mutagent prompts evaluation delete <evaluation-id>
mutagent prompts evaluation delete <evaluation-id> --force
```

| Option    | Description              |
| --------- | ------------------------ |
| `--force` | Skip confirmation prompt |

***

## Optimization

Optimization jobs are managed via the `prompts optimize` subcommand group.

<Mermaid>
  graph LR
  A\["optimize start"] --> B\["optimize status"]
  B -->|poll| B
  B --> C\["optimize results"]
</Mermaid>

### `mutagent prompts optimize start <prompt-id>`

Start a prompt optimization job. Requires a configured LLM provider, a dataset, and evaluation criteria.

```bash theme={null}
# Basic optimization (dataset and evaluation are required)
mutagent prompts optimize start <prompt-id> --dataset <dataset-id> --evaluation <eval-id>

# With tuning parameters
mutagent prompts optimize start <prompt-id> --dataset <dataset-id> --evaluation <eval-id> --max-iterations 5

# With target score and model override
mutagent prompts optimize start <prompt-id> --dataset <dataset-id> --evaluation <eval-id> --target-score 0.95 --model claude-sonnet-4-6
```

| Option                    | Description                                    | Default |
| ------------------------- | ---------------------------------------------- | ------- |
| `-d, --dataset <id>`      | Dataset ID for optimization (required)         | --      |
| `-e, --evaluation <id>`   | Evaluation ID for scoring (required)           | --      |
| `--max-iterations <n>`    | Max optimization iterations                    | `1`     |
| `--target-score <n>`      | Target accuracy score 0-1 (e.g., `0.9`)        | `0.8`   |
| `--patience <n>`          | Iterations without improvement before stopping | --      |
| `--model <model-id>`      | Target LLM model (e.g., `claude-sonnet-4-6`)   | --      |
| `--eval-model <model-id>` | Evaluation model (defaults to target model)    | --      |

<Warning>
  **Prerequisites (all required):**

  1. LLM Provider configured -- check with `mutagent providers list` or configure at [app.mutagent.io/settings/providers](https://app.mutagent.io/settings/providers)
  2. Dataset uploaded -- check with `mutagent prompts dataset list <prompt-id>`
  3. Evaluation criteria defined -- via dashboard or `mutagent prompts evaluation create`
</Warning>

### `mutagent prompts optimize status <job-id>`

Check optimization job status. Includes a progress bar in table mode.

```bash theme={null}
mutagent prompts optimize status <job-id>
mutagent prompts optimize status <job-id> --json
```

### `mutagent prompts optimize results <job-id>`

Get optimization results after the job completes. Results display an optimization scorecard with before/after comparison, score progression across iterations, and an apply/reject flow for the optimized prompt.

```bash theme={null}
mutagent prompts optimize results <job-id>
mutagent prompts optimize results <job-id> --diff
mutagent prompts optimize results <job-id> --apply
mutagent prompts optimize results <job-id> --json
```

| Option    | Description                               |
| --------- | ----------------------------------------- |
| `--apply` | Apply the optimized prompt as new version |
| `--diff`  | Show the prompt diff (before/after)       |
| `--watch` | Stream optimization progress in real-time |

### `mutagent prompts optimize watch <job-id>`

Watch an existing optimization job's progress in real-time.

```bash theme={null}
mutagent prompts optimize watch <job-id>
```

***

## Traces

### `mutagent traces list`

List traces with optional filtering.

```bash theme={null}
mutagent traces list
mutagent traces list --prompt <prompt-id>
mutagent traces list --source claude-code --json
mutagent traces list --limit 10 --json
```

| Option                  | Description                                                      | Default |
| ----------------------- | ---------------------------------------------------------------- | ------- |
| `-p, --prompt <id>`     | Filter by prompt ID                                              | --      |
| `-s, --source <source>` | Filter by trace source (e.g., `claude-code`, `sdk`, `langchain`) | --      |
| `-l, --limit <n>`       | Max traces to return                                             | `50`    |

### `mutagent traces get <id>`

Get full trace details including spans, tokens, and latency.

```bash theme={null}
mutagent traces get <trace-id>
mutagent traces get <trace-id> --json
```

### `mutagent traces analyze <prompt-id>`

Aggregate trace data for a prompt: average latency, token usage, error rates.

```bash theme={null}
mutagent traces analyze <prompt-id>
mutagent traces analyze <prompt-id> --json
```

### `mutagent traces export`

Export traces to a file or stdout.

```bash theme={null}
mutagent traces export
mutagent traces export --format json --output traces.json
mutagent traces export --format csv --output traces.csv
mutagent traces export --prompt <prompt-id> --format json
```

| Option                  | Description                          | Default |
| ----------------------- | ------------------------------------ | ------- |
| `-p, --prompt <id>`     | Filter by prompt ID                  | --      |
| `-f, --format <format>` | Export format: `json` or `csv`       | `json`  |
| `-o, --output <path>`   | Output file path (stdout if omitted) | --      |

***

## Integrations

### `mutagent integrate`

When called without a framework argument, returns framework detection/exploration instructions for AI coding agents.

```bash theme={null}
mutagent integrate
```

### `mutagent integrate <framework>`

Generate integration instructions for a specific framework. This is a skill loader for AI coding agents -- it returns instructions that agents execute, not auto-install.

```bash theme={null}
mutagent integrate langchain
mutagent integrate openai
mutagent integrate vercel-ai --verify
mutagent integrate langchain --output INTEGRATION.md
mutagent integrate langchain --raw
```

| Framework   | Description                   |
| ----------- | ----------------------------- |
| `langchain` | Popular LLM framework         |
| `langgraph` | Agent workflow framework      |
| `vercel-ai` | AI SDK for streaming chat     |
| `openai`    | Direct OpenAI SDK integration |

| Option                | Description                         |
| --------------------- | ----------------------------------- |
| `-o, --output <path>` | Save instructions to file           |
| `--raw`               | Output raw markdown (no formatting) |
| `--verify`            | Verify integration after generation |

### `mutagent integrate list`

List all available framework integrations with their npm packages and descriptions.

```bash theme={null}
mutagent integrate list
mutagent integrate list --json
```

***

## Init

### `mutagent init`

Initialize a MutagenT project in the current directory. Creates `.mutagentrc.json` with workspace config. In interactive mode, it detects your framework (Mastra, LangChain, LangGraph, Vercel AI, OpenAI), suggests packages, and optionally runs `mutagent explore`.

```bash theme={null}
mutagent init
mutagent init --non-interactive
```

<Tip>
  After `mutagent auth login`, the CLI may offer to run `mutagent init` as part of the onboarding flow.
</Tip>

***

## Explore

### `mutagent explore`

Scan your codebase for prompts, datasets, and MutagenT markers. Results are saved to `.mutagent/mutation-context.md`.

```bash theme={null}
mutagent explore
mutagent explore --path ./src
mutagent explore --include "**/*.{ts,py}" --depth 5
mutagent explore --markers-only
mutagent explore --json
```

| Option             | Description                            | Default                                                     |
| ------------------ | -------------------------------------- | ----------------------------------------------------------- |
| `-p, --path <dir>` | Directory to scan                      | `.`                                                         |
| `--depth <n>`      | Max directory depth                    | `10`                                                        |
| `--include <glob>` | Include file pattern                   | `**/*.{ts,js,py,tsx,jsx}`                                   |
| `--exclude <dirs>` | Comma-separated directories to exclude | `node_modules,dist,.git,build,.next,__pycache__,venv,.venv` |
| `--markers-only`   | Only find existing MutagenT markers    | --                                                          |

**Detection modes:**

* **Heuristic** -- Detects template variables (`{var}`), prompt constants, and schema definitions in your source code.
* **Marker** -- Finds `MutagenT:START` / `MutagenT:END` comment markers from previous uploads.

<Tip>
  Results are saved to `.mutagent/mutation-context.md` for use by other commands.
</Tip>

***

## Playground

### `mutagent playground run <prompt-id>`

Execute a prompt in the playground. Supports inline JSON input, file input, prompt-style flags, and streaming.

```bash theme={null}
# Inline JSON input
mutagent playground run <prompt-id> --input '{"topic": "AI observability"}'

# Streaming mode
mutagent playground run <prompt-id> --input '{"topic": "AI"}' --stream

# With model override
mutagent playground run <prompt-id> --input '{"topic": "AI"}' --model gpt-5

# With prompt-style flags
mutagent playground run <prompt-id> --system "You are a helpful assistant." --human "Hello!"

# Full messages array
mutagent playground run <prompt-id> --messages '[{"role":"user","content":"Hi"}]'
```

| Option                | Description                                      |
| --------------------- | ------------------------------------------------ |
| `-i, --input <json>`  | Input variables as JSON                          |
| `-s, --stream`        | Stream the response (tokens output as generated) |
| `-m, --model <model>` | Override the prompt's default model              |
| `--system <text>`     | System prompt text                               |
| `--human <text>`      | Human/user message text                          |
| `--messages <json>`   | Full messages array as JSON string               |

<Note>
  **Input methods are mutually exclusive.** Use one of:

  * `--input` for template variable input
  * `--system` / `--human` for quick message construction
  * `--messages` for full messages array

  In streaming mode with `--json`, each token is output as a separate JSON object.
</Note>

***

## Agents

### `mutagent agents list`

List agents with optional filtering.

```bash theme={null}
mutagent agents list
mutagent agents list --status active
mutagent agents list --name "reviewer" --json
```

| Option                  | Description                                       | Default |
| ----------------------- | ------------------------------------------------- | ------- |
| `-l, --limit <n>`       | Max agents to return                              | `50`    |
| `-o, --offset <n>`      | Pagination offset                                 | `0`     |
| `-n, --name <name>`     | Filter by name                                    | --      |
| `-s, --status <status>` | Filter by status (`active`, `paused`, `archived`) | --      |

### `mutagent agents get <id>`

Get agent details including system prompt, model, status, tools, and tags.

```bash theme={null}
mutagent agents get <agent-id>
mutagent agents get <agent-id> --json
```

### `mutagent agents create`

Create a new agent.

```bash theme={null}
# Inline JSON (recommended for CI/scripts/agents)
mutagent agents create -d '{"name":"Code Reviewer","slug":"code-reviewer","systemPrompt":"Review code for bugs"}'

# With individual flags
mutagent agents create --name "Code Reviewer" --slug code-reviewer --system-prompt "Review code for bugs"

# With optional fields
mutagent agents create --name "Helper" --slug helper --system-prompt "..." --model claude-sonnet-4-6 --description "General helper agent"
```

| Option                         | Description                                                              |
| ------------------------------ | ------------------------------------------------------------------------ |
| `-d, --data <json>`            | Agent as JSON string (recommended for CI/scripts/agents)                 |
| `-n, --name <name>`            | Agent name                                                               |
| `-s, --slug <slug>`            | URL-friendly slug                                                        |
| `-p, --system-prompt <prompt>` | System prompt                                                            |
| `-m, --model <model>`          | Model (e.g., `claude-sonnet-4-6`, `claude-opus-4-5`, `claude-haiku-4-5`) |
| `--description <desc>`         | Agent description                                                        |

### `mutagent agents update <id>`

Update an existing agent.

```bash theme={null}
mutagent agents update <id> --name "New Name"
mutagent agents update <id> --status paused
mutagent agents update <id> --model claude-sonnet-4-6
mutagent agents update <id> -d '{"name":"New Name","status":"paused"}'
```

| Option                         | Description                                      |
| ------------------------------ | ------------------------------------------------ |
| `-d, --data <json>`            | Agent updates as JSON string (CI/scripts/agents) |
| `-n, --name <name>`            | New name                                         |
| `-p, --system-prompt <prompt>` | New system prompt                                |
| `-m, --model <model>`          | New model                                        |
| `--description <desc>`         | New description                                  |
| `-s, --status <status>`        | New status (`active`, `paused`, `archived`)      |

### `mutagent agents delete <id>`

Delete an agent.

```bash theme={null}
mutagent agents delete <id>
mutagent agents delete <id> --force
```

| Option    | Description                                                      |
| --------- | ---------------------------------------------------------------- |
| `--force` | Skip confirmation prompt (required for non-interactive/CI usage) |

***

## Workspaces

<Note>
  Manage workspaces in the dashboard at [app.mutagent.io](https://app.mutagent.io).
</Note>

### `mutagent workspaces list`

List workspaces.

```bash theme={null}
mutagent workspaces list
mutagent workspaces list --limit 10 --json
```

| Option             | Description              | Default |
| ------------------ | ------------------------ | ------- |
| `-l, --limit <n>`  | Max workspaces to return | `50`    |
| `-o, --offset <n>` | Pagination offset        | `0`     |

### `mutagent workspaces get <id>`

Get workspace details.

```bash theme={null}
mutagent workspaces get <workspace-id>
mutagent workspaces get <workspace-id> --json
```

***

## Providers

<Note>
  Configure providers in the dashboard at [app.mutagent.io/settings/providers](https://app.mutagent.io/settings/providers).
</Note>

### `mutagent providers list`

List configured LLM providers.

```bash theme={null}
mutagent providers list
mutagent providers list --type openai
mutagent providers list --json
```

| Option              | Description             | Default |
| ------------------- | ----------------------- | ------- |
| `-l, --limit <n>`   | Max providers to return | `50`    |
| `-o, --offset <n>`  | Pagination offset       | `0`     |
| `-t, --type <type>` | Filter by provider type | --      |

**Provider types:** `openai`, `anthropic`, `google`, `azure`, `bedrock`, `groq`, `glm`, `moonshot`, `custom`

### `mutagent providers get <id>`

Get provider details.

```bash theme={null}
mutagent providers get <provider-id>
mutagent providers get <provider-id> --json
```

### `mutagent providers test <id>`

Test a provider connection. Returns connectivity status, response time, and available models.

```bash theme={null}
mutagent providers test <provider-id>
mutagent providers test <provider-id> --json
```

***

## Skills

### `mutagent skills install`

Install the MutagenT CLI skill for Claude Code. Creates `.claude/skills/mutagent-cli/SKILL.md` that teaches coding agents how to use the MutagenT CLI.

```bash theme={null}
mutagent skills install
mutagent skills install --json
```

<Tip>
  After installing, Claude Code will understand MutagenT CLI commands and can autonomously create prompts, upload datasets, run optimizations, and check traces on your behalf.
</Tip>

## Hooks

Hook handlers for AI coding assistants. Supports full Claude Code session telemetry via the traces/spans model. All handlers are **non-blocking** — failures print a warning to stderr and exit 0.

<Note>
  Hooks are configured in your AI assistant's settings file. They read JSON from stdin and send lightweight telemetry to the MutagenT API. Use `mutagent hooks install` to configure all hooks automatically rather than editing JSON manually.
</Note>

### `mutagent hooks install`

Install all MutagenT hook handlers into Claude Code's settings file. This is the recommended way to configure hooks — it writes all 11 event handlers into `.claude/settings.local.json` and validates the configuration.

```bash theme={null}
mutagent hooks install
mutagent hooks install --json
```

<Tip>
  Running `mutagent hooks install` is idempotent — it is safe to re-run after CLI updates to pick up new hook events without duplicating existing entries.
</Tip>

### Hook Event Taxonomy (v2)

MutagenT supports **11 Claude Code hook events**. Each maps to a handler subcommand that creates, updates, or closes spans in the active trace.

| Event                | Handler Subcommand      | Span Effect                                                    |
| -------------------- | ----------------------- | -------------------------------------------------------------- |
| `SessionStart`       | `session-start`         | Creates root `agent` span; starts trace                        |
| `SessionEnd`         | `session-end`           | Closes root span; finalises trace                              |
| `Stop`               | `stop`                  | Records a graceful agent-stop event on the root span           |
| `PreToolUse`         | `pre-tool-use`          | Opens a child `tool` span                                      |
| `PostToolUse`        | `post-tool-use`         | Closes `tool` span with `status: ok`                           |
| `PostToolUseFailure` | `post-tool-use-failure` | Closes `tool` span with `status: error`                        |
| `UserPromptSubmit`   | `user-prompt-submit`    | Opens a `chain` span for the turn; records user input          |
| `SubagentStart`      | `subagent-start`        | Opens a child `agent` span for the sub-agent                   |
| `SubagentStop`       | `subagent-stop`         | Closes the sub-agent `agent` span                              |
| `PreCompact`         | `pre-compact`           | Records a `custom` compaction event (pre-compaction snapshot)  |
| `PostCompact`        | `post-compact`          | Records a `custom` compaction event (post-compaction snapshot) |

### Trace Shape

Each Claude Code session produces a trace that mirrors the agent execution tree:

<Mermaid>
  flowchart TD
  A\["SessionStart → root agent span"] --> B\["UserPromptSubmit → chain span (turn 1)"]
  B --> C\["PreToolUse → tool span"]
  C --> D\["PostToolUse → tool span closed (ok)\nor PostToolUseFailure → closed (error)"]
  B --> E\["SubagentStart → child agent span"]
  E --> F\["SubagentStop → child agent span closed"]
  B --> G\["PreCompact / PostCompact → custom events"]
  A --> H\["Stop → graceful stop event"]
  A --> I\["SessionEnd → root span closed"]

  style A fill:#7C3AED,color:#fff
  style B fill:#06B6D4,color:#fff
  style C fill:#334155,color:#fff
  style E fill:#7C3AED,color:#fff
</Mermaid>

### Manual Configuration

If you prefer to configure hooks manually rather than using `mutagent hooks install`, add the following to `.claude/settings.local.json`:

```json theme={null}
{
  "hooks": {
    "SessionStart": [
      {
        "matcher": "",
        "hooks": [{ "type": "command", "command": "mutagent hooks claude-code session-start" }]
      }
    ],
    "SessionEnd": [
      {
        "matcher": "",
        "hooks": [{ "type": "command", "command": "mutagent hooks claude-code session-end" }]
      }
    ],
    "Stop": [
      {
        "matcher": "",
        "hooks": [{ "type": "command", "command": "mutagent hooks claude-code stop" }]
      }
    ],
    "PreToolUse": [
      {
        "matcher": "",
        "hooks": [{ "type": "command", "command": "mutagent hooks claude-code pre-tool-use" }]
      }
    ],
    "PostToolUse": [
      {
        "matcher": "",
        "hooks": [{ "type": "command", "command": "mutagent hooks claude-code post-tool-use" }]
      }
    ],
    "PostToolUseFailure": [
      {
        "matcher": "",
        "hooks": [{ "type": "command", "command": "mutagent hooks claude-code post-tool-use-failure" }]
      }
    ],
    "UserPromptSubmit": [
      {
        "matcher": "",
        "hooks": [{ "type": "command", "command": "mutagent hooks claude-code user-prompt-submit" }]
      }
    ],
    "SubagentStart": [
      {
        "matcher": "",
        "hooks": [{ "type": "command", "command": "mutagent hooks claude-code subagent-start" }]
      }
    ],
    "SubagentStop": [
      {
        "matcher": "",
        "hooks": [{ "type": "command", "command": "mutagent hooks claude-code subagent-stop" }]
      }
    ],
    "PreCompact": [
      {
        "matcher": "",
        "hooks": [{ "type": "command", "command": "mutagent hooks claude-code pre-compact" }]
      }
    ],
    "PostCompact": [
      {
        "matcher": "",
        "hooks": [{ "type": "command", "command": "mutagent hooks claude-code post-compact" }]
      }
    ]
  }
}
```

### Handler Reference

#### `mutagent hooks claude-code session-start`

Handle session start event. Creates a new trace with source `claude-code` and opens the root `agent` span.

```bash theme={null}
echo '{"session_id": "abc-123"}' | mutagent hooks claude-code session-start
```

#### `mutagent hooks claude-code session-end`

Handle session end event. Closes the root span and cleans up state.

```bash theme={null}
echo '{"session_id": "abc-123"}' | mutagent hooks claude-code session-end
```

#### `mutagent hooks claude-code stop`

Handle graceful stop event. Records a stop event on the active root span without closing the trace (session-end handles that).

```bash theme={null}
echo '{"session_id": "abc-123"}' | mutagent hooks claude-code stop
```

#### `mutagent hooks claude-code pre-tool-use`

Handle pre-tool-use event. Opens a `tool` span within the current turn span.

```bash theme={null}
echo '{"session_id": "abc-123", "tool_name": "Read", "tool_input": {"file": "main.ts"}}' | mutagent hooks claude-code pre-tool-use
```

#### `mutagent hooks claude-code post-tool-use`

Handle post-tool-use event. Closes the matching tool span with `status: ok`.

```bash theme={null}
echo '{"session_id": "abc-123", "tool_name": "Read", "tool_result": "file contents..."}' | mutagent hooks claude-code post-tool-use
```

#### `mutagent hooks claude-code post-tool-use-failure`

Handle post-tool-use failure event. Closes the matching tool span with `status: error`. Added in v2 to distinguish tool failures from successful tool calls.

```bash theme={null}
echo '{"session_id": "abc-123", "tool_name": "Bash", "error": "command not found"}' | mutagent hooks claude-code post-tool-use-failure
```

#### `mutagent hooks claude-code user-prompt-submit`

Handle user prompt submission. Opens a `chain` span for the turn and records the user input as span input.

```bash theme={null}
echo '{"session_id": "abc-123", "message": "Fix the bug in main.ts"}' | mutagent hooks claude-code user-prompt-submit
```

#### `mutagent hooks claude-code subagent-start`

Handle sub-agent start event. Opens a child `agent` span under the current turn span.

```bash theme={null}
echo '{"session_id": "abc-123", "subagent_id": "sub-456"}' | mutagent hooks claude-code subagent-start
```

#### `mutagent hooks claude-code subagent-stop`

Handle sub-agent stop event. Closes the child `agent` span.

```bash theme={null}
echo '{"session_id": "abc-123", "subagent_id": "sub-456"}' | mutagent hooks claude-code subagent-stop
```

#### `mutagent hooks claude-code pre-compact`

Handle pre-compaction event. Records a `custom` event on the active span with a snapshot of the context before compaction.

```bash theme={null}
echo '{"session_id": "abc-123"}' | mutagent hooks claude-code pre-compact
```

#### `mutagent hooks claude-code post-compact`

Handle post-compaction event. Records a `custom` event on the active span after compaction completes.

```bash theme={null}
echo '{"session_id": "abc-123"}' | mutagent hooks claude-code post-compact
```

### Stdin Schema

| Field         | Required | Events                                   | Description                    |
| ------------- | -------- | ---------------------------------------- | ------------------------------ |
| `session_id`  | Yes      | All                                      | Session identifier             |
| `tool_name`   | Yes      | pre/post-tool-use, post-tool-use-failure | Name of the tool               |
| `tool_input`  | No       | pre-tool-use                             | Tool input data                |
| `tool_result` | No       | post-tool-use                            | Tool result data               |
| `error`       | No       | post-tool-use-failure                    | Error message from failed tool |
| `message`     | No       | user-prompt-submit                       | User prompt text               |
| `subagent_id` | No       | subagent-start, subagent-stop            | Sub-agent identifier           |

<Tip>
  Session state is stored in `/tmp/mutagent-hook-{sessionId}.json` during the session and cleaned up on `session-end`. The API calls use a 5-second timeout and fire-and-forget pattern.
</Tip>

***

## Feedback

### `mutagent feedback send`

Send feedback to the MutagenT team.

```bash theme={null}
mutagent feedback send -m "Your feedback message here"
mutagent feedback send -m "Found a bug" --category bug
```

| Option                 | Description                                        |
| ---------------------- | -------------------------------------------------- |
| `-m, --message <text>` | Feedback message (required)                        |
| `--category <type>`    | Feedback category: `bug`, `feature`, `improvement` |

***

## Usage

### `mutagent usage`

Show resource counts (prompts, datasets, evaluations) and optimization run limits for your current plan.

```bash theme={null}
mutagent usage
mutagent usage --json
```

The command shows a progress bar for optimization usage and a link to upgrade at [app.mutagent.io/settings/billing](https://app.mutagent.io/settings/billing).

***

## Workflows

Common command sequences for typical tasks.

### Evaluate and Optimize Loop

```bash theme={null}
# 1. Create a prompt
mutagent prompts create --name "My Prompt" --raw "Your prompt text here"

# 2. Upload a dataset
mutagent prompts dataset add <prompt-id> --name "Training Data" --file data.json

# 3. Create evaluation criteria
mutagent prompts evaluation create <prompt-id> --name "Quality Check" --file criteria.json

# 4. Start optimization
mutagent prompts optimize start <prompt-id> --dataset <dataset-id> --max-iterations 3

# 5. Monitor progress
mutagent prompts optimize status <job-id>

# 6. Get results
mutagent prompts optimize results <job-id>
```

### Quick Test

```bash theme={null}
mutagent playground run <prompt-id> --input '{"key": "value"}'
```

### CI/CD Integration

```bash theme={null}
export MUTAGENT_API_KEY=mt_xxxx
mutagent prompts list --json
mutagent traces list --prompt <prompt-id> --json
```

***

## Exit Codes

| Code | Meaning                 |
| ---- | ----------------------- |
| `0`  | Success                 |
| `1`  | General error           |
| `2`  | Authentication required |
| `3`  | Configuration error     |
| `5`  | Network error           |
| `6`  | Rate limit exceeded     |
| `8`  | Permission error        |
