> ## 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.

## Connect Lean to your assistant

The Lean MCP server calls the Lean API for your account, so an assistant connected to it can read
markets, books, candles, orders, positions, profit and loss, risk, stop losses, deposits,
withdrawals and transfers, and trade if you let it. Lean hosts it at `https://api.lean.xyz/mcp`. Add
that address to your assistant and it sends you to Lean to log in. There you choose what it gets, exactly as when you
[create a key](https://docs.lean.xyz/authentication.md#create-a-key): the trading account, **Read only** or **Read and
trade**, test or live, spending limits and when the access expires. Nothing is copied or pasted,
and the assistant never sees a key.

```text Claude and ChatGPT theme={"dark"}
Add a custom connector with the address https://api.lean.xyz/mcp
```

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

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

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

Claude, Claude Code, ChatGPT, Codex, Cursor and VS Code are verified clients. Any other standard MCP
OAuth client using HTTPS or a local loopback callback is also supported and shown with an unverified
app warning naming its callback host; approve it only if you just started the login yourself.

The access is an API key with the assistant's name on it. It appears under **Settings › API** with
your other keys, the same limits, pauses and kill switch apply to it, and revoking it there
disconnects the assistant at once. Connecting the same assistant to the same trading account again
replaces its previous access.

The hosted server offers the tools described below. The trading tools appear when you choose
**Read and trade**, so there is no `--enable-trading` to pass.

## Docs for language models

| File | Address | Use it for |
| - | - | - |
| `llms.txt` | [docs.lean.xyz/llms.txt](https://docs.lean.xyz/llms.txt) | An index of every page with a one line summary. Point an agent here first. |
| `llms-full.txt` | [docs.lean.xyz/llms-full.txt](https://docs.lean.xyz/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 [docs.lean.xyz/quickstart.md](https://docs.lean.xyz/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 separate, read-only hosted Model Context Protocol (MCP) server at
`https://docs.lean.xyz/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://docs.lean.xyz/mcp
```

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

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

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

## Run the Lean MCP server

The same server also runs on your machine over stdio, for clients that start local servers. It
calls the Lean API with an API key you create, and the key stays in its environment, so the key is
never sent to the model. The server is the `@leanxyz/mcp` package on npm. It needs [Node.js](https://nodejs.org) 22 or
later (22.4 or later for `watch_stream`), and your MCP client starts it with `npx -y @leanxyz/mcp`.

| 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`, `preview_order`, `preview_orders_batch`, `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`, `list_conditional_sells`, `get_conditional_sell`, `get_deposit_addresses`, `get_deposit_assets`, `list_deposits`, `get_convertible_balances`, `list_withdrawals`, `get_withdrawal`,
`quote_transfer`, `list_transfers`, `get_transfer` and `watch_stream`. 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, and the market, book, trade, candle and order tools also cover Lighter's crypto
markets. Deposits and withdrawals cover Polymarket and Hyperliquid only. Live transfers
also reach Lighter.

`preview_order` and `preview_orders_batch` place nothing, so they work with a **Read only** key.
`quote_market` prices sports and event markets; to price a crypto price window, use
`preview_order`. `watch_stream` opens the [stream](https://docs.lean.xyz/streaming.md) for one call of up to 25 seconds
and returns what arrived: order updates, best price changes of up to 10 books, and the latest
positions and balances. An assistant uses it to wait for a fill or a price move instead of
polling, and nothing stays subscribed after it returns. If the connection drops while it watches
orders, the result says so, and the assistant checks the order with `get_order` before acting.

**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 |
| - | - |
| `create_order`, `amend_order`, `cancel_order`, `cancel_orders_batch`, `cancel_all_orders`, `set_cancel_after`, `close_positions`, `redeem_positions`, `merge_positions`, `convert_to_pusd`, `create_stop_loss`, `update_stop_loss`, `cancel_stop_loss`, `create_limit_chase`, `update_limit_chase`, `cancel_limit_chase`, `create_conditional_sell`, `cancel_conditional_sell`, `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)) |
| `reset_test_mode`, offered only with a test key | `trade`. It starts the test account over, as [Reset test mode](https://docs.lean.xyz/api-reference/test-mode/reset-test-mode.md) does. |
| `create_transfer`, `execute_transfer`, `create_routed_order` and `execute_routed_order` | `trade` and `route`. A **Read and trade** key made in the Lean app has both. A live transfer also needs trading enabled in the Lean app. See [Transfers](https://docs.lean.xyz/transfers.md) and [Routed orders](https://docs.lean.xyz/routed-orders.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 as compact JSON, including `livemode`. An API error
comes back with its status, code, message, request ID and details. A rate limit refusal also
carries `retry_after_seconds`, and where the next step is clear the error adds a `hint`, such as
reading an order back by its client ID before sending a write again after a timeout. A tool refuses any argument it does not define, so a misspelled
filter is an error, not silently ignored.

```json Claude Desktop (claude_desktop_config.json) theme={"dark"}
{
  "mcpServers": {
    "lean": {
      "command": "npx",
      "args": ["-y", "@leanxyz/mcp"],
      "env": { "LEAN_API_KEY": "lean_sk_test_..." }
    }
  }
}
```

```bash Claude Code theme={"dark"}
claude mcp add lean --env LEAN_API_KEY=lean_sk_test_... -- npx -y @leanxyz/mcp
```

```json Cursor (.cursor/mcp.json) theme={"dark"}
{
  "mcpServers": {
    "lean": {
      "command": "npx",
      "args": ["-y", "@leanxyz/mcp"],
      "env": { "LEAN_API_KEY": "lean_sk_test_..." }
    }
  }
}
```

```json Cursor with trading tools theme={"dark"}
{
  "mcpServers": {
    "lean": {
      "command": "npx",
      "args": ["-y", "@leanxyz/mcp", "--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://docs.lean.xyz/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://docs.lean.xyz/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.** Any OpenAPI 3.0 generator works with the spec, 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 prediction markets, sports and events, 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://docs.lean.xyz/llms.txt
  Spec: https://docs.lean.xyz/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.