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

# Agent Integration

> The starting point for AI agents integrating Legend onchain finance.

## Overview

Legend gives AI agents access to DeFi yield, borrowing, trading (perpetuals and prediction markets coming soon), and cross-chain transfers across 8 EVM networks and Solana (coming soon). Whether you connect through the MCP Server, the CLI, or the REST API directly, you get access to the same execution engine — the same one powering Legend's consumer app with real money and real users.

**Skill reference:** [legend.xyz/SKILL.md](https://legend.xyz/SKILL.md)

***

## Golden Path

Paste this into your agent to get started:

```
Read https://legend.xyz/SKILL.md and set up Legend
```

For manual setup → [MCP Setup](/agents/mcp/setup)

***

## Integration Options

### Local MCP Server (recommended)

Runs via `legend-cli mcp serve`. Includes all tools plus `plan_and_execute` — create, sign, and execute in one tool call. No separate signing step. → [Full setup](/agents/mcp/setup)

### Remote MCP Server

The hosted server at `https://prime-api.legend.xyz/mcp`. Works with Claude Code, Cursor, OpenAI Responses API, and any MCP-compatible host. Best for read-only operations or shared team access. Executing plans requires a separate CLI signing step.

```bash theme={null}
claude mcp add --transport http legend-remote https://prime-api.legend.xyz/mcp
```

### CLI

Direct key management, signing, and API access. Useful for scripting and CI/CD.

```bash theme={null}
legend-cli plan earn acc_xxx --amount 1000000 --asset USDC --network base --protocol compound --execute
```

→ [CLI Reference](/agents/cli)

### REST API

```bash theme={null}
curl -X POST https://api.legend.xyz/accounts/{id}/plan/earn \
  -H "Authorization: Bearer YOUR_KEY" \
  -H "Content-Type: application/json" \
  -d '{"amount": "100000000", "asset": "USDC", "network": "base"}'
```

→ [API Reference](/api-reference/prime-account)

***

## Authentication

| Method                   | Best for                            | How                                                                        |
| ------------------------ | ----------------------------------- | -------------------------------------------------------------------------- |
| **OAuth (Google SSO)**   | CLI, Local MCP                      | `legend-cli login` — opens browser, saves JWT to profile                   |
| **OAuth (browser flow)** | Remote MCP with Claude Code, Cursor | `claude mcp add` → `/mcp` → Authenticate in browser                        |
| **Query Key**            | Programmatic agents, CI/CD          | `Authorization: Bearer qk_...` or `legend-cli config set query-key qk_...` |

OAuth JWTs last 30 days. Both OAuth and query keys work with all integration paths.

***

## How It Works: Plan → Sign → Execute

Every action that moves funds follows a three-step flow. This is what keeps Legend non-custodial — signing keys never touch Legend's servers.

### 1. Plan

Your agent requests an operation. Legend returns a full human-readable plan — amounts, routes, protocols, fees — before anything happens onchain. Plans are free and expire after 2 minutes.

```json theme={null}
POST /accounts/{account_id}/plan/earn
{
  "amount": "100000000",
  "asset": "USDC",
  "network": "base",
  "protocol": "compound"
}
```

Response includes:

* `plan_id` — valid for 2 minutes
* `details` — every step, every chain, human-readable
* `details.eip712_data.digest` — the hash to sign

### 2. Sign

The CLI signs using the P256 key stored in your macOS Keychain. Turnkey then produces the EIP-712 signature using the account's secp256k1 wallet key. The P256 key never leaves hardware. The secp256k1 key never leaves Turnkey's secure infrastructure.

Legend never sees your private key. Nothing moves without your approval.

### 3. Execute

```json theme={null}
POST /accounts/{account_id}/plan/execute
{
  "plan_id": "pln_xxx",
  "signature": "0x..."
}
```

Legend verifies the signature, submits the transaction onchain, and handles gas, bridging, and token approvals atomically.

The `plan_and_execute` MCP tool does all three in one call.

***

## Working with Amounts

Amounts are always in the token's smallest unit:

| Token      | Amount | Smallest unit                         |
| ---------- | ------ | ------------------------------------- |
| 1 USDC     | 1      | `"1000000"` (6 decimals)              |
| \$100 USDC | 100    | `"100000000"`                         |
| 1 ETH      | 1      | `"1000000000000000000"` (18 decimals) |

***

## Core Actions

### Earn

Check available rates, then deploy:

```
1. get_portfolio(account_id) → look at yield_markets for rates
2. plan_and_execute(account_id, action: "earn", amount, asset, network, protocol)
```

The `yield_markets` keys in the portfolio tell you the protocol to use:

| yield\_market prefix | protocol parameter |
| -------------------- | ------------------ |
| `comet/...`          | `"compound"`       |
| `aave/...`           | `"aave"`           |
| `morpho_vault/...`   | `"morpho_vault"`   |

```json theme={null}
{
  "account_id": "acc_xxx",
  "action": "earn",
  "amount": "100000000",
  "asset": "USDC",
  "network": "base",
  "protocol": "compound"
}
```

### Withdraw from Yield

```json theme={null}
{
  "account_id": "acc_xxx",
  "action": "withdraw",
  "amount": "100000000",
  "asset": "USDC",
  "network": "base",
  "protocol": "compound"
}
```

### Swap

Use either `sell_amount` or `buy_amount`, not both:

```json theme={null}
{
  "account_id": "acc_xxx",
  "action": "swap",
  "sell_asset": "USDC",
  "buy_asset": "WETH",
  "sell_amount": "100000000",
  "network": "base"
}
```

### Transfer

```json theme={null}
{
  "account_id": "acc_xxx",
  "action": "transfer",
  "amount": "100000000",
  "asset": "USDC",
  "network": "base",
  "recipient": "0x742d35Cc6634C0532925a3b844Bc9e7595f2bD18"
}
```

### Borrow

```json theme={null}
{
  "account_id": "acc_xxx",
  "action": "borrow",
  "amount": "100000000",
  "asset": "USDC",
  "collateral_amount": "50000000000000000",
  "collateral_asset": "WETH",
  "network": "base",
  "protocol": "compound"
}
```

### Advanced

* `loop-long` — Open leveraged long positions on Morpho markets
* `migrate` — Move supply positions between protocols atomically
* `reinvest-rewards` — Claim, swap, bridge, and re-supply rewards in one plan
* `swap-and-supply` — Swap and deploy into yield in a single signature
* `plan/perp` — Perpetual positions on Hyperliquid (coming soon)
* `plan/predict` — Prediction markets on Polymarket (coming soon)
* `plan/spend` — Pay real-world expenses via virtual card (coming soon)

***

## Reading the Portfolio

`get_portfolio` returns everything about an account:

* **balances** — token amounts per chain. Key format: `token/{network}/{symbol}/{wallet}`. Values use scientific notation: `"300.25e6"` = 300.25 USDC.
* **prices** — USD prices. Key: `token/{SYMBOL}`. Value: `"2713.04"`.
* **yield\_markets** — where the account is earning, with `supply_apr`.
* **borrow\_markets** — open borrows with `borrow_apr` and collateral info.
* **rewards** — unclaimed protocol rewards.

***

## Supported Networks

| Network       | Chain ID | Display Name         |
| ------------- | -------- | -------------------- |
| `base`        | 8453     | Base                 |
| `ethereum`    | 1        | Ethereum             |
| `arbitrum`    | 42161    | Arbitrum             |
| `optimism`    | 10       | Optimism             |
| `polygon`     | 137      | Polygon              |
| `unichain`    | 130      | Unichain             |
| `world_chain` | 480      | World Chain          |
| `hyper_evm`   | 999      | HyperEVM             |
| `solana`      | —        | Solana (coming soon) |

Cross-chain is automatic — specify the target network and Legend bridges funds as needed.

***

## Typical Workflows

### Deploy idle USDC to best yield

```
1. get_portfolio → check yield_markets and supply_apr rates
2. plan_and_execute with action: "earn" into the best rate
```

### Swap ETH for USDC

```
1. get_portfolio → check ETH balance
2. plan_and_execute with action: "swap", sell_asset: "WETH", buy_asset: "USDC"
```

### Move funds to another wallet

```
plan_and_execute with action: "transfer", recipient address
```

### Check transaction status

```
get_activities → check status of recent operations
```

***

## Account Structure

Every integration starts with an Account — your organization's container. Under it you create sub-accounts, each with its own onchain smart wallet and signer key.

```bash theme={null}
# Create a sub-account
legend-cli accounts create --keygen

# List accounts
legend-cli accounts list

# Get portfolio
legend-cli folio acc_xxx
```

Sub-accounts are fully segregated — separate wallet, separate signer. Provision one per agent, per strategy, or per user. If one is compromised, the blast radius is limited to that sub-account.

***

## Non-Custodial Design

Legend never holds signing keys. The security model:

* **Reading** (portfolios, activities, reference data) — requires only API auth (query key or OAuth JWT)
* **Planning** (create earn/swap/transfer plans) — same, just API auth. Plans are free previews.
* **Executing** (moving funds) — requires a cryptographic signature from the account's P256 key. The agent signs locally via the local MCP server or CLI. Legend verifies the signature but never has access to the key.

When you run `legend-cli accounts create --keygen`, the CLI:

1. Generates a P256 key in your macOS Keychain (hardware-protected, non-exportable)
2. Sends only the public key to Legend, which creates a Turnkey sub-organization with that key
3. Saves the key reference and account details to `~/.legend/prod/profiles/default.json`

***

## Safety Properties

**Whitelisted protocols only** — Agents can only route funds into audited, whitelisted DeFi protocols. No arbitrary contract calls.

**Plan expiry** — Plans expire after 2 minutes. A stale plan cannot execute. If conditions change, the agent replans.

**Replay protection** — Every plan is domain-bound and chain-bound via EIP-712. A signature cannot be replayed on a different action or chain.

**Secure key storage** — The P256 signing key lives in macOS Keychain. It cannot be exported or accessed remotely.

**Revocable at any time** — Rotating or revoking a signing key immediately stops that agent. No need to drain wallets or unwind positions.

**Agent-in-the-loop** — Run a planner agent that constructs the intent and a separate signing agent that verifies the plan before approving. No human needs to review every transaction.

***

## Error Handling

| Status                 | Meaning                                | Action                                |
| ---------------------- | -------------------------------------- | ------------------------------------- |
| `plan_expired`         | Plan older than 2 minutes              | Create a new plan                     |
| `insufficient_balance` | Not enough funds                       | Fund the sub-account or reduce amount |
| `invalid_signature`    | Signature doesn't match plan digest    | Re-sign the current plan              |
| `network_unavailable`  | Target network temporarily unreachable | Retry with exponential backoff        |
| `protocol_paused`      | DeFi protocol paused                   | Try an alternative protocol           |

***

## Next Steps

<CardGroup cols={2}>
  <Card title="MCP Setup" icon="plug" href="/agents/mcp/setup">
    Connect in 2 minutes
  </Card>

  <Card title="MCP Tools" icon="wrench" href="/agents/mcp/tools">
    Complete tool reference
  </Card>

  <Card title="CLI Reference" icon="terminal" href="/agents/cli">
    Full CLI command reference
  </Card>

  <Card title="Claude Code Guide" icon="code" href="/agents/guides/claude-code">
    Full walkthrough
  </Card>

  <Card title="API Reference" icon="code" href="/api-reference/prime-account">
    Complete endpoint documentation
  </Card>

  <Card title="OpenAI Agents" icon="robot" href="/agents/guides/openai">
    OpenAI Responses API setup
  </Card>

  <Card title="Data Sources" icon="database" href="/agents/guides/data-sources">
    Free-tier APIs for strategy signals
  </Card>
</CardGroup>
