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

# Build with AI

> Give a coding assistant or an AI agent these docs, the OpenAPI spec and the Lean MCP server, then let it trade safely on a test key.

These docs are available as plain Markdown, as one file for language models and through a hosted
MCP server, and the OpenAPI spec describes every endpoint. Give them to a coding assistant or an
agent so it works from the real API, then start it on a test key.

## Docs for language models

| File | Address | Use it for |
| - | - | - |
| `llms.txt` | [lean.mintlify.site/llms.txt](https://lean.mintlify.site/llms.txt) | An index of every page with a one line summary. Point an agent here first. |
| `llms-full.txt` | [lean.mintlify.site/llms-full.txt](https://lean.mintlify.site/llms-full.txt) | Every page in one Markdown file. Attach it when the model can't browse. |
| A page as Markdown | Add `.md` to the page's address, for example [lean.mintlify.site/quickstart.md](https://lean.mintlify.site/quickstart.md) | One page without navigation or styling. |

The menu at the top of each page copies the page as Markdown, opens it as Markdown, opens it in
ChatGPT or Claude with the page as context, or copies the address of the docs MCP server.

## Connect the docs MCP server

The docs have a hosted Model Context Protocol (MCP) server at `https://lean.mintlify.site/mcp`. An
assistant connected to it can search these docs and read their pages while it works. It serves only
the public docs: it can't call the Lean API or see your account, and it needs no key.

```bash Claude Code theme={"dark"}
claude mcp add --transport http lean-api https://lean.mintlify.site/mcp
```

```json Cursor (.cursor/mcp.json) theme={"dark"}
{
  "mcpServers": {
    "lean-api": { "url": "https://lean.mintlify.site/mcp" }
  }
}
```

```json VS Code (.vscode/mcp.json) theme={"dark"}
{
  "servers": {
    "lean-api": { "type": "http", "url": "https://lean.mintlify.site/mcp" }
  }
}
```

Any other client that supports remote MCP servers over HTTP takes the same address.

## Run the Lean MCP server

The Lean MCP server is different from the docs MCP server: it calls the Lean API with your API key,
so an assistant connected to it can read markets, books, candles, orders, positions, profit and
loss, risk, stop losses, deposits, withdrawals and transfers for your account. It runs on your machine over stdio with [Bun](https://bun.sh), and the key stays in
its environment, so the key is never sent to the model. The server is the `sdks/mcp` package of the
Lean SDKs, started with `bun sdks/mcp/src/index.ts`.

| Setting | What it does |
| - | - |
| `LEAN_API_KEY` | Required. The key the server sends with every request. |
| `LEAN_API_URL` | The API address. Defaults to `https://api.lean.xyz`. |
| `LEAN_API_TIMEOUT_MS` | How long to wait for each request, in milliseconds. Defaults to 30000. |
| `--enable-trading` | A command line flag that asks for the trading tools. |

**It is read only by default.** These tools are always available: `list_markets`, `get_market`,
`quote_market`, `get_market_book`, `get_market_trades`, `get_market_candles`, `get_prices`,
`list_orders`, `get_order`, `list_fills`, `get_positions`, `get_balances`, `get_account_config`,
`get_pnl`, `get_pnl_history`, `get_risk`, `list_stop_losses`, `get_stop_loss`,
`list_limit_chases`, `get_limit_chase`, `get_deposit_addresses`, `get_deposit_assets`, `list_withdrawals`, `get_withdrawal`,
`quote_transfer`, `list_transfers` and `get_transfer`. Any tool that takes a market ID also takes
a venue's own ID for it, such as a Polymarket token ID, a Kalshi market ticker or a ticker with a
`pm:`, `pmus:` or `hl:` prefix. The read and trading tools cover Kalshi, Polymarket, Polymarket US
and Hyperliquid. Deposits, transfers and withdrawals cover Polymarket and Hyperliquid only.

**Tools that change anything need two things:** the server starts with `--enable-trading`, and
the key has the scope the API checks for that tool. Otherwise the assistant isn't offered them at
all. With the flag and a **Read only** key, the server says so when it starts and stays read only.

| Tools | Scope the key needs |
| - | - |
| `preview_order`, `create_order`, `amend_order`, `cancel_order`, `cancel_orders_batch`, `cancel_all_orders`, `set_cancel_after`, `close_positions`, `create_stop_loss`, `cancel_stop_loss`, `create_limit_chase`, `cancel_limit_chase`, `pause_trading`, `lower_limits` and `create_deposit_addresses` | `trade`, a **Read and trade** key (see [Authentication](https://docs.lean.xyz/authentication.md#create-a-key)) |
| `create_transfer` and `execute_transfer` | `trade` and `route`. A **Read and trade** key made in the Lean app has both. Only test keys can transfer for now. See [Transfers](https://docs.lean.xyz/transfers.md). |
| `create_withdrawal` | `withdraw`. See [Withdrawals through the API](https://docs.lean.xyz/funding.md#withdrawals-through-the-api). |

`create_order` and `preview_order` take every order type the API takes: limit or market, by
quantity or by dollar amount, good till canceled, immediate or cancel, fill or kill, or good till
a time, and post only.

`pause_trading` and `lower_limits` let an assistant stop its own trading or tighten its own key.
Neither can be undone through the API: only the Lean app resumes trading or raises a limit.

Start with a test key, so orders are simulated and no money moves, and give the key tight limits.
Every tool answers with the API response, including `livemode`, and an API error comes back with
its code, message and request ID. A tool refuses any argument it does not define, so a misspelled
filter is an error, not silently ignored.

```bash Claude Code theme={"dark"}
claude mcp add lean \
  --env LEAN_API_KEY=lean_sk_test_... \
  --env LEAN_API_URL=https://api.lean.xyz \
  -- bun /absolute/path/to/sdks/mcp/src/index.ts
```

```json Cursor (.cursor/mcp.json) theme={"dark"}
{
  "mcpServers": {
    "lean": {
      "command": "bun",
      "args": ["/absolute/path/to/sdks/mcp/src/index.ts"],
      "env": {
        "LEAN_API_KEY": "lean_sk_test_...",
        "LEAN_API_URL": "https://api.lean.xyz"
      }
    }
  }
}
```

```json Cursor with trading tools theme={"dark"}
{
  "mcpServers": {
    "lean": {
      "command": "bun",
      "args": ["/absolute/path/to/sdks/mcp/src/index.ts", "--enable-trading"],
      "env": { "LEAN_API_KEY": "lean_sk_test_..." }
    }
  }
}
```

The assistant should still preview every order and wait for your approval before it places one.
The [system prompt](#a-system-prompt-for-a-trading-agent) and
[safety checklist](#safety-checklist) below apply to it too.

## Use the OpenAPI spec

The [OpenAPI spec](https://lean.mintlify.site/api-reference/openapi.json) (OpenAPI 3.0) lists every endpoint with its
parameters, request and response schemas and error shapes. Its server is `{baseUrl}/v1`, and
`baseUrl` defaults to `https://api.lean.xyz`, the same value as `LEAN_API_URL` in these guides.

```bash theme={"dark"}
curl -sS -o lean-openapi.json https://lean.mintlify.site/api-reference/openapi.json
```

**Give it to an agent.** Many agent frameworks turn OpenAPI operations into tools. Load only the
operations the agent needs. A research agent needs the market reads and
[Preview an order](https://docs.lean.xyz/api-reference/orders/preview-order.md). Leave out the `/api-keys` operations:
they take the session token of a person signed in to Lean, not an API key. When the model writes
requests itself, attach the spec, or the schemas for the calls it makes, so its bodies match.

**Generate a client.** For TypeScript and Rust, the [TypeScript SDK](https://docs.lean.xyz/typescript-sdk.md) and the
[Rust SDK](https://docs.lean.xyz/rust-sdk.md) are already generated from the spec. Any OpenAPI 3.0 generator works for
other languages, for example:

```bash theme={"dark"}
# Python client
npx @openapitools/openapi-generator-cli generate -i lean-openapi.json -g python -o lean-client

# TypeScript types
npx openapi-typescript lean-openapi.json -o lean-api.d.ts
```

Send the key as `Authorization: Bearer <key>`, the spec's `apiKey` scheme. The spec's
`info.version` is the release named in the [changelog](https://docs.lean.xyz/changelog.md). Download the spec again when
the changelog lists a new release. See [Versioning](https://docs.lean.xyz/versioning.md).

## A system prompt for a trading agent

Start from this prompt for an agent that trades through `/v1` with a test key. Give the agent the
key through its environment or a tool, never in the prompt text, so the key isn't sent to the model
provider or kept in logs.

```text theme={"dark"}
You trade sports prediction markets through the Lean API.

Setup
- Base URL: the LEAN_API_URL environment variable (https://api.lean.xyz).
- Send the key from the LEAN_API_KEY environment variable as "Authorization: Bearer <key>".
  Never print, log or repeat the key.
- The key is a test key (it starts with lean_sk_test_). Orders are simulated and no money moves.
  Every successful response has data.livemode. If it is ever true, stop and tell the user.
- Docs index: https://lean.mintlify.site/llms.txt
  Spec: https://lean.mintlify.site/api-reference/openapi.json
  Follow the spec for every field name and type.

Placing orders
- Before placing an order, send the exact body to POST /v1/orders/preview. Place it only if
  would_submit is true and you can explain every entry in warnings. Show the user the preview
  and wait for approval before you place it.
- Give every order a new client_order_id and write it down before you send POST /v1/orders.
- On a timeout or network error, look the order up with
  GET /v1/orders?client_order_id=<id>. Retry only with the same client_order_id and the same body.
  Never resend an order with a new client_order_id until you know the first one was not placed.
- An order whose status is unconfirmed may be on the venue. Read it back by client_order_id. Do not
  resend it.

Errors and limits
- 422 means Lean placed nothing. Read error.details.reason and do not retry the same order.
  ORDER_NOTIONAL_LIMIT and DAILY_NOTIONAL_LIMIT are the key's limits: do not split an order to get
  under them.
- 429: wait for the Retry-After header, then retry. Stay under 5 requests a second.
- 503 FEATURE_DISABLED with details.reason TRADING_PAUSED: trading is paused. Stop placing orders
  and tell the user. Only a person can resume trading.
- If you are unsure what an order will do, or something looks wrong, stop and pause the key:
  POST /v1/account/pause with {"scope": "api_key", "reason": "<why>"}.
```

## Safety checklist

* **Start in test mode.** A test key simulates orders and fills with simulated balances, and
  responses carry `livemode: false`. Move to a live key only after the agent behaves well on a test
  key. See [Go live](https://docs.lean.xyz/test-mode.md#go-live).
* **Preview before placing.** [Preview an order](https://docs.lean.xyz/api-reference/orders/preview-order.md) shows the
  legs, prices, cost and `would_submit` without placing anything. It is the natural approval step.
  See [Preview](https://docs.lean.xyz/preview.md).
* **Use idempotency keys.** A `client_order_id` saved before sending makes every retry safe. The
  same ID never places a second order. See [Idempotency](https://docs.lean.xyz/orders.md#idempotency).
* **Set tight key limits.** Give the agent's key a per order and daily limit no higher than it
  needs. Lean refuses any order above them before it reaches a venue. A research agent gets a
  **Read only** key, which can preview but not place orders. See
  [Authentication](https://docs.lean.xyz/authentication.md#create-a-key) and
  [Lower key limits](https://docs.lean.xyz/api-reference/account/lower-key-limits.md).
* **Keep a way to stop it.** [Pause trading](https://docs.lean.xyz/orders.md#pause-trading) stops new orders for a key or
  the whole trading account in one call, and only the Lean dashboard resumes. Run the pause from a
  monitor outside the agent too, and revoke a key from Lean at any time.

> [card] [An AI agent that trades within a budget](https://docs.lean.xyz/use-cases/ai-agent-trading.md)
>
> A research agent on a read only key proposes trades, and an execution key places them after
> approval.

> [card] [Quickstart](https://docs.lean.xyz/quickstart.md)
>
> From a new key to a filled test order in one call.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.