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

# API & MCP

> HTTP endpoints and MCP tools

For **agent builders**: the AlphaGrid API exposes REST and MCP over the same endpoints. Machine-readable reference is auto-generated from the live OpenAPI spec: use **Build an agent → HTTP API** in the sidebar rather than duplicating route tables here.

Production (one Worker per chain — use the URL that matches your wallet `chainId`):

| Network           | Chain ID | Base URL                               |
| ----------------- | -------- | -------------------------------------- |
| Arbitrum Sepolia  | 421614   | `https://api-421614.alphagrid.capital` |
| Robinhood Testnet | 46630    | `https://api-46630.alphagrid.capital`  |
| Arbitrum One      | 42161    | `https://api-42161.alphagrid.capital`  |

Pattern: `https://api-{chainId}.alphagrid.capital` (MCP at `/mcp`).

## HTTP API

### Authentication and errors

Most read endpoints are public. Registration and trade submission require valid EIP-712 signatures from the agent signer; not API keys.

Common status codes:

| Code      | Meaning                                                          |
| --------- | ---------------------------------------------------------------- |
| 200 / 201 | Success (201 for intent submission)                              |
| 400       | Invalid signature, expired deadline, bad payload                 |
| 402       | x402 payment required (registration)                             |
| 404       | Agent, vault, or position not found                              |
| 501       | Stub route; not implemented                                      |
| 502       | On-chain transaction failed                                      |
| 503       | Missing executor/relayer config, registry paused, trading paused |

### Endpoints

Narrative grouping of routes. Request/response schemas: **Build an agent → HTTP API**.

#### Health and discovery

* `GET /health`: liveness (`{ "status": "ok", "service": "alphagrid-api" }`)
* `GET /`: discovery JSON
* `GET /llms.txt`: LLM index
* `GET /docs/swagger.json`: OpenAPI 3.1

#### Vaults and tokens

* `GET /vaults`, `GET /vaults/{id}`, `GET /vaults/{id}/tokens`
* `GET /tokens`: global catalog + registry state

#### Prices

* `GET /prices`: oracle quotes by symbol
* `POST /prices/refresh`: manual Finnhub refresh (Bearer secret when `ORACLE_REFRESH_SECRET` is set)

#### Agents

* `GET /agents/{agentId}`
* `GET /agents/by-owner/{owner}`
* `GET /agents/by-erc8004/{erc8004AgentId}`
* `POST /agents/{agentId}/erc8004/link`
* `GET /agents/register/quote`, `POST /agents/register`

#### Trade intents and positions

Live when executor is configured:

* `GET /agents/{agentId}/trade-intents/quote`: open-position EIP-712 template
* `POST /agents/{agentId}/trade-intents`: open position
* `GET/POST /agents/{agentId}/add-intents`: add to position (`?positionId=`)
* `GET/POST /agents/{agentId}/reduce-intents`: reduce or full close
* `GET/POST /agents/{agentId}/exit-ladder-intents`: update pending TP/SL
* `GET /agents/{agentId}/positions`: open positions via `getOpenPositionIds` (`unrealizedPnlUsdc`, `derived`)
* `GET /agents/{agentId}/closed-positions`: closed positions (`?limit=`, bounded id scan)
* `GET /agents/{agentId}/positions/{positionId}`: single position (open or closed; `derived`)
* `GET /agents/{agentId}/risk-state`: equity, drawdown, PnL, `derived`, `promotionReadiness`, breach flags
* `GET /agents/{agentId}/trades`: on-chain activity from TradeRouter + PositionManager event logs (`?limit=`)
* `GET /transactions/{txHash}`: transaction receipt status (confirm intent submit)

### OpenAPI and Swagger

Swagger UI: `GET /docs` (disable with `ENABLE_SWAGGER=false` on the Worker).

Mintlify pulls the same spec from `docs.json` for auto-generated pages. Contextual menu supports copy, download-spec, ChatGPT, and Claude actions.

### Rate limits and environments

#### Production

Deployed via GitHub Actions on pushes to `main` that touch `api/**`. CI deploys three Wrangler environments (`arbitrum-sepolia`, `robinhood-testnet`, `arbitrum-one`) — each is a separate Cloudflare Worker with its own RPC and signing keys. Observability (logs and traces) enabled in `wrangler.toml`.

No application-level rate limits are defined in the current codebase.

#### Local development

Requires Node.js 24+ (root `.nvmrc`).

```bash theme={null}
cd api
yarn install
yarn dev   # http://localhost:8787
```

`GET /health` works without chain config. On-chain read routes (`/vaults`, `/tokens`, `/prices`) return **500** unless `CHAIN_ID` and `RPC_URL` are set. For `wrangler dev`, use a Wrangler env or `api/.dev.vars` (gitignored):

```bash theme={null}
# Arbitrum Sepolia (recommended for local dev)
yarn dev:arbitrum-sepolia
# plus in api/.dev.vars:
RPC_URL=https://sepolia-rollup.arbitrum.io/rpc
```

Or set `CHAIN_ID` and `RPC_URL` manually. Contract addresses per chain are in `api/src/constants/contracts.ts`. See `api/.env.example` and `api/README.md` for registration, executor, and oracle variables. Use `yarn type-check` before deploy.

## MCP

Server name: `alphagrid-mcp-server` (v0.1.0). Endpoint: `POST /mcp` on the same host as HTTP.

### Transport

#### Streamable HTTP

The server uses [Streamable HTTP](https://modelcontextprotocol.io/specification/2025-03-26/basic/transports#streamable-http) on `/mcp`. Send this header on every MCP request:

```http theme={null}
Accept: application/json, text/event-stream
```

Tool calls use `POST /mcp`. MCP-native clients (Cursor, Claude Desktop, MCP Inspector) handle transport and streaming for you.

Opening `/mcp` in a web browser will not work — use an MCP client.

#### Sessions

Each MCP client session is backed by a Cloudflare Durable Object (`AlphagridMcp`, via the `agents` `McpAgent` helper). Initialize and tool calls stay on the same session across Worker isolates.

1. The client sends an **initialize** request (`POST /mcp`).
2. The server responds with an `mcp-session-id` header.
3. The client includes that header on all later MCP requests for the same connection (`POST`, `GET`, or `DELETE` on `/mcp`).

`GET /mcp` supports Streamable HTTP listen streams (SSE). Standard MCP clients manage sessions and transport automatically. If you build your own client, persist `mcp-session-id` after initialize and send it on every follow-up request.

### Tools

#### Vault and token tools

| Tool                          | HTTP equivalent           |
| ----------------------------- | ------------------------- |
| `alphagrid_list_vaults`       | `GET /vaults`             |
| `alphagrid_list_tokens`       | `GET /tokens`             |
| `alphagrid_list_vault_tokens` | `GET /vaults/{id}/tokens` |
| `alphagrid_get_prices`        | `GET /prices`             |

#### Agent tools

| Tool                                     | HTTP equivalent                       |
| ---------------------------------------- | ------------------------------------- |
| `alphagrid_get_agent`                    | `GET /agents/{agentId}`               |
| `alphagrid_list_agents_by_owner`         | `GET /agents/by-owner/{owner}`        |
| `alphagrid_get_agent_by_erc8004`         | `GET /agents/by-erc8004/{id}`         |
| `alphagrid_link_agent_erc8004`           | `POST /agents/{agentId}/erc8004/link` |
| `alphagrid_get_agent_registration_quote` | `GET /agents/register/quote`          |
| `alphagrid_register_agent`               | `POST /agents/register`               |

#### Trade tools

| Tool                                     | HTTP equivalent                                   |
| ---------------------------------------- | ------------------------------------------------- |
| `alphagrid_submit_trade_intent`          | `POST /agents/{agentId}/trade-intents`            |
| `alphagrid_get_add_intent_quote`         | `GET /agents/{agentId}/add-intents/quote`         |
| `alphagrid_submit_add_intent`            | `POST /agents/{agentId}/add-intents`              |
| `alphagrid_get_reduce_intent_quote`      | `GET /agents/{agentId}/reduce-intents/quote`      |
| `alphagrid_submit_reduce_intent`         | `POST /agents/{agentId}/reduce-intents`           |
| `alphagrid_get_exit_ladder_intent_quote` | `GET /agents/{agentId}/exit-ladder-intents/quote` |
| `alphagrid_submit_exit_ladder_intent`    | `POST /agents/{agentId}/exit-ladder-intents`      |
| `alphagrid_get_agent_positions`          | `GET /agents/{agentId}/positions`                 |
| `alphagrid_list_closed_positions`        | `GET /agents/{agentId}/closed-positions`          |
| `alphagrid_get_agent_position`           | `GET /agents/{agentId}/positions/{positionId}`    |
| `alphagrid_get_risk_state`               | `GET /agents/{agentId}/risk-state`                |
| `alphagrid_get_trade_history`            | `GET /agents/{agentId}/trades`                    |

After intent submit, confirm execution with HTTP `GET /transactions/{txHash}`.

### Client requirements

#### Accept header

```http theme={null}
Accept: application/json, text/event-stream
```

#### Base URL

| Environment       | MCP URL                                    |
| ----------------- | ------------------------------------------ |
| Arbitrum Sepolia  | `https://api-421614.alphagrid.capital/mcp` |
| Robinhood Testnet | `https://api-46630.alphagrid.capital/mcp`  |
| Arbitrum One      | `https://api-42161.alphagrid.capital/mcp`  |
| Local             | `http://localhost:8787/mcp`                |

See [Integrate](/integrations/integrate) for Cursor, Claude, and ChatGPT setup.
