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

# CLI Agent Mode

> Use the Nile CLI as an agent tool with JSON output mode — 30+ commands for reading protocol state, opening positions, and managing margin, with OWS wallet signing integration.

The Nile CLI (`nile`) outputs structured JSON by default, making it a natural subprocess tool for AI agents. With 30+ commands covering reads, writes, and simulations, agents can drive the full protocol lifecycle through shell invocations.

## Install

```bash theme={null}
npm install -g @nile-markets/cli
```

One-shot without installing — ideal for sandboxed agents (`-y` skips the prompt; `@latest` forces dist-tag re-resolution instead of reusing a stale npx cache):

```bash theme={null}
npx -y @nile-markets/cli@latest pool state
```

Or via the installer script:

```bash theme={null}
curl -fsSL https://mcp.nilemarkets.com/install.sh | bash
```

Or via Cargo:

```bash theme={null}
cargo install nile-markets-cli
```

Verify installation:

```bash theme={null}
nile --version
```

The installed binary embeds Sepolia contract addresses, a free public RPC endpoint, and the subgraph URL. No environment variables, config files, or API keys needed for read commands.

## JSON Output

All commands output JSON by default. You can also set the format explicitly:

```bash theme={null}
nile pool state                    # JSON by default
nile --format json pool state      # Explicit JSON
nile --format table pool state     # Human-readable table
```

JSON responses follow a consistent envelope:

```json theme={null}
{
  "protocol": { "name": "Nile Markets", "version": "0.3.2" },
  "network": "sepolia",
  "source": "subgraph",
  "data": {
    "totalAssets": "50000000000",
    "riskCapacityUtilization": "4500",
    "sharePrice": "1002345678901234567"
  }
}
```

Pipe JSON output to `jq` for field extraction:

```bash theme={null}
nile pool state --format json | jq '.data.totalAssets'
nile oracle state --format json | jq '.data.spot.price'
nile position list --account 0xabc... --format json | jq '.data[] | .id'
```

## Command Groups

| Group        | Key Commands                                    | Description                                             |
| ------------ | ----------------------------------------------- | ------------------------------------------------------- |
| **pool**     | `state`, `deposit`, `withdraw`, `transactions`  | Liquidity pool metrics and LP operations                |
| **position** | `list`, `get`, `search`, `open`, `close`        | Position lifecycle and queries                          |
| **account**  | `balance`, `deposit`, `withdraw`                | Margin account management                               |
| **oracle**   | `state`, `price`                                | Spot and forward price feeds                            |
| **protocol** | `mode`                                          | Operating mode (NORMAL, DEGRADED, REDUCE\_ONLY, PAUSED) |
| **simulate** | `open`                                          | Preview margin, fees, and entry strike before trading   |
| **stats**    | `daily`                                         | Volume, fees, and position activity over time           |
| **fees**     | `list`                                          | Fee event breakdown by category                         |
| **token**    | `balance`, `allowance`, `approve`, `mint`       | ERC-20 balance checks and approvals                     |
| **config**   | `show`, `set-rpc`, `set-subgraph`, `set-wallet` | CLI configuration management                            |

## Agent Workflow Example

A typical agent-driven trade flow chains CLI commands as subprocess calls:

<Steps>
  <Step title="Check protocol mode">
    Verify the protocol is in NORMAL mode before suggesting trades.

    ```bash theme={null}
    nile protocol mode --format json
    ```

    ```json theme={null}
    { "data": { "mode": "NORMAL" } }
    ```
  </Step>

  <Step title="Check balances">
    Read the trader's USDC wallet balance and margin account state.

    ```bash theme={null}
    nile token balance --account 0xYOUR_ADDR --format json
    nile account balance --account 0xYOUR_ADDR --format json
    ```
  </Step>

  <Step title="Simulate the trade">
    Preview margin requirements, fees, and entry strike before committing.

    ```bash theme={null}
    nile simulate open --side LONG --tenor 1M --notional 10000 --margin 500 --format json
    ```
  </Step>

  <Step title="Execute the trade">
    Open the position. The CLI builds the transaction, delegates signing to OWS, and broadcasts.

    ```bash theme={null}
    nile position open --side LONG --tenor 1M --notional 10000 --margin 500
    ```
  </Step>

  <Step title="Verify">
    Confirm the position was created and check real-time PnL.

    ```bash theme={null}
    nile position get --id <POSITION_ID> --format json
    ```
  </Step>
</Steps>

## OWS Wallet Signing

Read commands work immediately after install. Write commands (open/close positions, deposit/withdraw) require an [OWS-compatible wallet](https://docs.openwallet.sh/) for transaction signing.

```bash theme={null}
# Install OWS
curl -fsSL https://openwallet.sh/install.sh | bash

# Import your private key
echo "<your-private-key>" | ows wallet import --name my-wallet --private-key --chain evm

# Configure the CLI to use your wallet
nile config set-wallet my-wallet
```

The CLI never handles private keys directly. All signing is delegated to the OWS subprocess via `ows sign tx`. Wallet setup (key import, passphrase configuration) happens entirely outside the Nile workflow.

<Warning>
  Write commands require Sepolia ETH for gas. Get testnet ETH from [alchemy.com/faucets](https://www.alchemy.com/faucets/ethereum-sepolia) or [sepoliafaucet.com](https://sepoliafaucet.com).
</Warning>

## Configuration

The CLI works zero-config for Sepolia. For advanced use cases, override settings persistently or per-command.

### Persistent Config

Stored in `~/.nile/config.json`:

```bash theme={null}
nile config show                   # Show current config
nile config set-rpc <url>          # Override default RPC URL
nile config set-subgraph <url>     # Override default subgraph URL
nile config set-wallet <name>      # Set default wallet name
nile config set-signer <binary>    # Use a different signer binary (default: ows)
```

### Environment Variables

| Variable            | Description                                           |
| ------------------- | ----------------------------------------------------- |
| `NILE_RPC_URL`      | RPC URL override                                      |
| `NILE_SUBGRAPH_URL` | Subgraph URL override                                 |
| `NILE_NETWORK`      | Target network (default: `sepolia`)                   |
| `NILE_WALLET`       | Wallet name                                           |
| `NILE_FORMAT`       | Output format: `json` or `table` (default: `json`)    |
| `NILE_FROM`         | Sender address override (read-only/simulate commands) |

### Resolution Order

For all configurable values: CLI flag > environment variable > `~/.nile/config.json` > embedded default.

## CLI vs MCP

Both surfaces expose the same protocol operations. Choose based on your agent's architecture.

| Aspect          | CLI                                            | MCP                                            |
| --------------- | ---------------------------------------------- | ---------------------------------------------- |
| **Integration** | Subprocess / shell                             | HTTP server                                    |
| **Signing**     | Built-in via OWS                               | Returns unsigned calldata                      |
| **Auth**        | None (local binary)                            | None (M2 testnet)                              |
| **Output**      | JSON or table                                  | JSON tool responses                            |
| **Best for**    | Local agents, automation scripts, CI pipelines | Cloud agents, multi-turn chat, hosted services |

<Tip>
  For agents running locally with shell access, the CLI is the fastest path to end-to-end trades — it handles signing and broadcasting in a single command. For hosted or multi-tenant agents, use the [MCP Server](mcp-server) which returns unsigned calldata for client-side signing.
</Tip>
