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

# CLI Reference

> Complete command reference for the Craft Agents CLI client

# CLI Reference

The `craft-cli` is a terminal client that connects to a running Craft Agent headless server over WebSocket. It provides commands for listing resources, managing sessions, sending messages with real-time streaming, and validating server health.

## Installation

```bash theme={null}
# Clone the repository
git clone https://github.com/anthropics/craft-agents.git
cd craft-agents

# Install dependencies
bun install

# Option A: Run directly
bun run apps/cli/src/index.ts <command>

# Option B: Link globally (adds craft-cli to PATH)
cd apps/cli && bun link
craft-cli <command>
```

### Quick Start

The fastest way to try it out — no server setup needed:

```bash theme={null}
# Self-contained run (spawns a server automatically)
ANTHROPIC_API_KEY=sk-... bun run apps/cli/src/index.ts run "Hello, world!"
```

## Connection Options

| Flag                  | Env Variable         | Default     | Description                      |
| --------------------- | -------------------- | ----------- | -------------------------------- |
| `--url <ws[s]://...>` | `CRAFT_SERVER_URL`   | —           | Server WebSocket URL             |
| `--token <secret>`    | `CRAFT_SERVER_TOKEN` | —           | Authentication token             |
| `--workspace <id>`    | —                    | auto-detect | Workspace ID                     |
| `--timeout <ms>`      | —                    | `10000`     | Request timeout                  |
| `--tls-ca <path>`     | `CRAFT_TLS_CA`       | —           | Custom CA cert (self-signed TLS) |
| `--json`              | —                    | `false`     | JSON output for scripting        |
| `--send-timeout <ms>` | —                    | `300000`    | Timeout for `send` command       |

Flags override environment variables. If `--workspace` is omitted, the first available workspace is used automatically.

## Commands

### Info & Health

| Command    | Channel                   | Description                                       |
| ---------- | ------------------------- | ------------------------------------------------- |
| `ping`     | handshake only            | Verify connectivity — prints clientId and latency |
| `health`   | `credentials:healthCheck` | Check credential store health                     |
| `versions` | `system:versions`         | Show server runtime versions                      |

### Resource Listing

| Command       | Channel               | Description                               |
| ------------- | --------------------- | ----------------------------------------- |
| `workspaces`  | `workspaces:get`      | List all workspaces (id, name, path)      |
| `sessions`    | `sessions:get`        | List sessions (id, name, preview, status) |
| `connections` | `LLM_Connection:list` | List LLM connections                      |
| `sources`     | `sources:get`         | List configured sources                   |

### Session Operations

| Command                                    | Channel                | Description                   |
| ------------------------------------------ | ---------------------- | ----------------------------- |
| `session create [--name <n>] [--mode <m>]` | `sessions:create`      | Create a new session          |
| `session messages <id>`                    | `sessions:getMessages` | Print message history         |
| `session delete <id>`                      | `sessions:delete`      | Delete a session              |
| `cancel <id>`                              | `sessions:cancel`      | Cancel in-progress processing |

### Send Message (Streaming)

```bash theme={null}
craft-cli send <session-id> <message>
echo "Summarize this" | craft-cli send <session-id>
```

The `send` command subscribes to `session:event` and streams the AI response to stdout in real time:

| Event Type    | Output                               |
| ------------- | ------------------------------------ |
| `text_delta`  | Text appended inline                 |
| `tool_start`  | `[tool: name — intent]` marker       |
| `tool_result` | Tool output (truncated to 200 chars) |
| `error`       | Error to stderr, exit code 1         |
| `complete`    | Newline, exit code 0                 |
| `interrupted` | `[interrupted]`, exit code 130       |

### Raw RPC

```bash theme={null}
craft-cli invoke <channel> [json-args...]   # Send any RPC channel
craft-cli listen <channel>                   # Subscribe to push events
```

`invoke` sends a request to any channel and prints the response. `listen` subscribes to a push channel and prints events as they arrive (Ctrl+C to stop).

### Run (Self-Contained)

```bash theme={null}
craft-cli run <prompt>
craft-cli run --workspace-dir ./project --source github "List open PRs"
```

The `run` command is fully self-contained — it spawns a headless server, creates a session, sends the prompt, streams the response, and exits. No separate server setup needed. An API key is resolved from `--api-key`, `$LLM_API_KEY`, or a provider-specific env var (e.g., `$ANTHROPIC_API_KEY`, `$OPENAI_API_KEY`).

| Flag                     | Default     | Description                                   |
| ------------------------ | ----------- | --------------------------------------------- |
| `--workspace-dir <path>` | —           | Register a workspace directory before running |
| `--source <slug>`        | —           | Enable a source (repeatable)                  |
| `--output-format <fmt>`  | `text`      | Output format: `text` or `stream-json`        |
| `--mode <mode>`          | `allow-all` | Permission mode for the session               |
| `--no-cleanup`           | `false`     | Skip session deletion on exit                 |
| `--server-entry <path>`  | —           | Custom server entry point                     |

**LLM Configuration:**

| Flag                | Env Fallback   | Default            | Description                                                                             |
| ------------------- | -------------- | ------------------ | --------------------------------------------------------------------------------------- |
| `--provider <name>` | `LLM_PROVIDER` | `anthropic`        | Provider: `anthropic`, `openai`, `google`, `openrouter`, `groq`, `mistral`, `xai`, etc. |
| `--model <id>`      | `LLM_MODEL`    | (provider default) | Model ID (e.g., `claude-sonnet-4-5-20250929`, `gpt-4o`, `gemini-2.0-flash`)             |
| `--api-key <key>`   | `LLM_API_KEY`  | (provider env)     | API key — also checks provider-specific vars like `$OPENAI_API_KEY`                     |
| `--base-url <url>`  | `LLM_BASE_URL` | —                  | Custom endpoint for proxies, OpenRouter, or self-hosted models                          |

```bash theme={null}
# Multi-provider examples
craft-cli run --provider openai --model gpt-4o "Summarize this repo"
GOOGLE_API_KEY=... craft-cli run --provider google --model gemini-2.0-flash "Hello"
craft-cli run --provider anthropic --base-url https://openrouter.ai/api/v1 --api-key $OR_KEY "Hello"
```

### Validate Server

```bash theme={null}
# Against a running server
craft-cli --validate-server --url ws://127.0.0.1:9100 --token <token>

# Self-contained (auto-spawns a server)
craft-cli --validate-server
```

When no `--url` is provided, `--validate-server` automatically spawns a local headless server, runs the validation, and shuts it down.

Runs a 21-step integration test covering the full server lifecycle including source and skill creation:

1. Connect + handshake
2. `credentials:healthCheck`
3. `system:versions`
4. `system:homeDir`
5. `workspaces:get`
6. `sessions:get`
7. `LLM_Connection:list`
8. `sources:get`
9. `sessions:create` (temporary `__cli-validate-*` session)
10. `sessions:getMessages`
11. Send message + stream (text response)
12. Send message + tool use (Bash tool)
13. `sources:create` (temporary Cat Facts API source)
14. Send + source mention (uses the created source)
15. Send + skill create (writes SKILL.md via Bash)
16. `skills:get` (verify skill appears)
17. Send + skill mention (invokes the created skill)
18. `skills:delete` (cleanup)
19. `sources:delete` (cleanup)
20. `sessions:delete` (cleanup)
21. Disconnect

**Note:** This test mutates workspace state — it creates and deletes a temporary session, source, and skill. All resources are cleaned up on completion. Continues on failure and reports a summary.

Use `--json` for machine-readable output:

```bash theme={null}
craft-cli --validate-server --json | jq '.results[] | select(.status == "FAIL")'
```

## Troubleshooting

| Symptom                        | Cause              | Fix                                     |
| ------------------------------ | ------------------ | --------------------------------------- |
| Connection timeout             | Server not running | Verify server URL and that it's started |
| `AUTH_FAILED`                  | Wrong token        | Check `CRAFT_SERVER_TOKEN` matches      |
| `PROTOCOL_VERSION_UNSUPPORTED` | Version mismatch   | Update CLI and server                   |
| WebSocket error                | Network/TLS issue  | Use `--tls-ca` for self-signed certs    |
