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

# MCP Server

> Run Horizon as an MCP server for Claude Code, Cursor, Windsurf, VS Code, and Claude Desktop.

The Horizon MCP server exposes 26 tools and 2 context resources via the [Model Context Protocol](https://modelcontextprotocol.io). Any MCP-compatible client can connect and trade prediction markets, equities, options, and crypto through natural language.

Tools are organized into **14 individual tools** for common trading operations and **12 compound tools** (including `equity` for stocks/options data) that group related capabilities via an `action` parameter. This keeps the tool list small enough for LLMs to load efficiently while preserving all 241+ capabilities.

## Installation

```bash theme={null}
pip install horizon-sdk[mcp]
# or
uv pip install horizon-sdk[mcp]
```

This installs the `mcp` package alongside Horizon. The server is available as both a module and a console script:

<CodeGroup>
  ```bash Module theme={null}
  python -m horizon.mcp
  ```

  ```bash Console script theme={null}
  horizon-mcp
  ```

  ```bash HTTP transport theme={null}
  python -m horizon.mcp --http
  ```
</CodeGroup>

## Architecture

The server lazily initializes a singleton Engine on the first tool call. Configuration comes from environment variables - no config files needed.

The MCP server (`horizon.mcp_server`) delegates to `horizon.tools` which manages a singleton Engine backed by the Rust core.

### Compound Tool Pattern

Most tools beyond the core 14 use an **action-dispatch** pattern:

```json theme={null}
{
  "tool": "wallet",
  "params": {
    "action": "trades",
    "params": "{\"address\": \"0x1234...\", \"limit\": 50}"
  }
}
```

The `action` parameter selects the operation, and `params` is a JSON string with action-specific arguments. Each compound tool's description lists all available actions.

## Individual Tools (14)

### Portfolio & Status

#### engine\_status

Get the engine's current state.

```json theme={null}
{
  "running": true,
  "kill_switch_active": false,
  "kill_switch_reason": null,
  "open_orders": 3,
  "active_positions": 2,
  "total_realized_pnl": 12.45,
  "total_unrealized_pnl": -3.20,
  "daily_pnl": 9.25,
  "uptime_secs": 3600
}
```

#### list\_positions

Returns all open positions.

```json theme={null}
[
  {
    "market_id": "will-btc-hit-100k",
    "side": "yes",
    "size": 25.0,
    "avg_entry_price": 0.55,
    "realized_pnl": 0.0,
    "unrealized_pnl": 2.50,
    "exchange": "polymarket"
  }
]
```

#### list\_open\_orders

Parameters: `market_id` (optional) - filter by market.

#### list\_recent\_fills

Parameters: `limit` (default: 20) - number of fills to return.

#### portfolio\_metrics

Get portfolio metrics: total value, PnL, exposure, diversification, concentration. No parameters.

### Trading

#### submit\_order

Place a limit order on the engine's configured exchange.

| Parameter     | Type   | Description                          |
| ------------- | ------ | ------------------------------------ |
| `market_id`   | string | Market identifier                    |
| `side`        | string | `"buy"` or `"sell"`                  |
| `price`       | float  | Probability price (0-1)              |
| `size`        | float  | Number of contracts                  |
| `market_side` | string | `"yes"` or `"no"` (default: `"yes"`) |

Returns the order ID on success, or `{"error": "..."}` on failure.

#### cancel\_order

Parameters: `order_id` - the ID to cancel.

#### cancel\_all\_orders

Cancels all open orders across all exchanges. Returns `{"canceled_count": N}`.

### Risk Management

#### activate\_kill\_switch

Parameters: `reason` - why you're activating it.

<Warning>
  This is an emergency stop. It immediately cancels all open orders across all exchanges. Use only in emergencies.
</Warning>

### Market Data

#### get\_feed\_snapshot

Parameters: `name` - feed name (as configured in the engine).

```json theme={null}
{
  "name": "btc",
  "price": 97234.50,
  "bid": 97230.00,
  "ask": 97239.00,
  "volume_24h": 1234567.89,
  "source": "binance_ws",
  "timestamp": 1708185600.123
}
```

### Discovery

#### discover\_markets

Search for markets on an exchange.

| Parameter     | Type   | Default        | Description                                                        |
| ------------- | ------ | -------------- | ------------------------------------------------------------------ |
| `exchange`    | string | `"polymarket"` | `"polymarket"`, `"kalshi"`, `"limitless"`, `"alpaca"`, or `"ibkr"` |
| `query`       | string | `""`           | Search text                                                        |
| `limit`       | int    | `10`           | Max results                                                        |
| `market_type` | string | `"all"`        | `"all"`, `"binary"`, or `"multi"`                                  |

#### get\_market\_detail

Get detailed information for a specific market including price history, orderbook, recent trades, and top holders.

| Parameter    | Type   | Default        | Description                  |
| ------------ | ------ | -------------- | ---------------------------- |
| `slug_or_id` | string | required       | Market slug or condition ID  |
| `exchange`   | string | `"polymarket"` | `"polymarket"` or `"kalshi"` |

#### top\_markets

Get the highest-volume active markets.

| Parameter  | Type   | Default        | Description                  |
| ---------- | ------ | -------------- | ---------------------------- |
| `exchange` | string | `"polymarket"` | `"polymarket"` or `"kalshi"` |
| `limit`    | int    | `10`           | Max results                  |
| `category` | string | `""`           | Category filter              |

### Sizing

#### kelly\_sizing

Compute Kelly-optimal position size.

| Parameter  | Type  | Default  | Description                           |
| ---------- | ----- | -------- | ------------------------------------- |
| `prob`     | float | -        | Your estimated probability (0–1)      |
| `price`    | float | -        | Current market price (0–1)            |
| `bankroll` | float | `1000.0` | Total capital                         |
| `fraction` | float | `0.25`   | Kelly fraction (0.25 = quarter Kelly) |
| `max_size` | float | `100.0`  | Hard cap on position size             |

## Compound Tools (12)

### feed

Feed management and data. 7 actions: `list_feeds`, `start`, `metrics`, `all_metrics`, `health`, `parity`, `discover_events`.

```json theme={null}
// Start a Chainlink feed
{"action": "start", "params": "{\"name\": \"eth_usd\", \"feed_type\": \"chainlink\", \"config_json\": \"{\\\"contract_address\\\":\\\"0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419\\\",\\\"rpc_url\\\":\\\"https://eth.llamarpc.com\\\"}\"}"}

// Check feed health
{"action": "health", "params": "{\"stale_threshold\": 30.0}"}

// Check YES/NO price parity
{"action": "parity", "params": "{\"market_id\": \"will-btc-hit-100k\"}"}
```

### order\_management

Advanced order operations. 5 actions: `cancel_market`, `add_stop_loss`, `add_take_profit`, `list_contingent`, `deactivate_kill_switch`.

```json theme={null}
// Add a stop-loss
{"action": "add_stop_loss", "params": "{\"market_id\": \"will-btc-hit-100k\", \"side\": \"yes\", \"order_side\": \"sell\", \"size\": 200, \"trigger\": 0.40}"}

// List all contingent orders
{"action": "list_contingent", "params": "{}"}
```

### wallet

Polymarket wallet analytics (public, no auth). 11 actions: `trades`, `market_trades`, `positions`, `value`, `profile`, `top_holders`, `market_flow`, `profile_wallet` \[PRO], `track` \[ULTRA], `consensus` \[ULTRA], `scan_signals` \[ULTRA].

```json theme={null}
// Get wallet positions
{"action": "positions", "params": "{\"address\": \"0x1234...\", \"sort_by\": \"CURRENT\"}"}

// Analyze trade flow for a market
{"action": "market_flow", "params": "{\"condition_id\": \"0xabc...\", \"trade_limit\": 500}"}
```

### analytics

Quantitative analytics toolkit. 84 actions across categories: statistics, signals, portfolio, AFML (bars/labels/frac\_diff), microstructure, state estimation, causality, execution, copula, portfolio optimization, hedging, pricing, bootstrap, risk/regime, and more.

```json theme={null}
// Compute Hurst exponent
{"action": "hurst_exponent", "params": "{\"prices\": [100, 101, 99, 102, 98]}"}

// Kelly sizing adjusted for risk-free rate
{"action": "yield_adjusted_kelly", "params": "{\"prob\": 0.72, \"price\": 0.58, \"rfr\": 0.05, \"duration_days\": 30}"}

// Bootstrap Sharpe ratio confidence interval
{"action": "bootstrap_sharpe", "params": "{\"returns\": [0.01, -0.02, 0.03, 0.01, -0.01]}"}

// Hedge analysis
{"action": "hedge_analysis", "params": "{\"spot_prices\": [100, 101, 99], \"hedge_prices\": [50, 50.5, 49.5]}"}
```

See the tool description for the full list of 84 actions and their parameters.

### scanning

Market scanning, signals, and execution. 11 actions: `sentinel_report` \[ULTRA], `oracle_forecast` \[ULTRA], `oracle_edges` \[ULTRA], `whale_galaxy` \[ULTRA], `llm_forecast`, `llm_scan`, `analyze_resolution`, `sniper_scan`, `execute_arbitrage`, `stealth_estimate` \[ULTRA], `stealth_execute` \[ULTRA].

```json theme={null}
// Scan for LLM-detected edges
{"action": "llm_scan", "params": "{\"min_edge_bps\": 200, \"max_markets\": 20}"}

// Cross-exchange arbitrage
{"action": "execute_arbitrage", "params": "{\"market_id\": \"will-btc-hit-100k\", \"buy_exchange\": \"kalshi\", \"sell_exchange\": \"polymarket\", \"buy_price\": 0.48, \"sell_price\": 0.52, \"size\": 10}"}
```

### unusual\_whales

Unusual Whales market intelligence. 36 actions across: flow (`options_flow`, `stock_flow`, `dark_pool`, `market_tide`, `spike`), Congress/insider (`congress_trades`, `congress_trader`, `insider_trades`), stock data (`stock_info`, `stock_state`, `earnings`, `earnings_schedule`, `seasonality`), options analytics (`greek_exposure`, `greek_exposure_by_strike`, `greek_exposure_by_expiry`, `iv_rank`, `vol_term_structure`, `max_pain`, `option_chains`), short interest (`short_interest`, `short_volume`, `ftd`), screeners (`screener_stocks`, `screener_options`), ETF (`etf_holdings`, `etf_flow`), institutions (`institutions`, `institution_holdings`, `institution_ownership`), calendars (`economic_calendar`, `fda_calendar`), other (`news`, `prediction_whales`, `prediction_unusual`, `crypto_whales`).

```json theme={null}
// Get unusual options flow for AAPL
{"action": "options_flow", "params": "{\"ticker\": \"AAPL\", \"min_premium\": 100000, \"is_sweep\": true}"}

// Get Congress trades
{"action": "congress_trades", "params": "{\"limit\": 50}"}
```

### market\_data

Market data from Massive (Polygon.io). 24 actions across: price data (`aggregates`, `snapshot`, `last_trade`, `last_quote`, `previous_close`, `grouped_daily`), movers (`gainers_losers`, `crypto_gainers_losers`), reference (`ticker_details`, `search_tickers`, `market_status`, `market_holidays`), technical indicators (`sma`, `ema`, `rsi`, `macd`), options (`options_chain`, `options_contracts`), other (`news`, `dividends`, `splits`, `crypto_snapshot`, `forex_conversion`, `forex_snapshot`).

```json theme={null}
// Get OHLCV bars
{"action": "aggregates", "params": "{\"ticker\": \"AAPL\", \"from_date\": \"2025-01-01\", \"to_date\": \"2025-03-01\", \"timespan\": \"day\"}"}

// Get real-time snapshot
{"action": "snapshot", "params": "{\"ticker\": \"AAPL\"}"}
```

### cloud

Horizon Cloud deployment and management. 12 actions: `list_strategies`, `get_strategy`, `create_strategy`, `validate`, `list_credentials`, `save_credentials`, `deploy`, `stop`, `status`, `metrics`, `logs`, `account`.

```json theme={null}
// Create a strategy
{"action": "create_strategy", "params": "{\"name\": \"Simple MM\", \"code\": \"import horizon as hz\\n...\"}"}

// Deploy
{"action": "deploy", "params": "{\"strategy_id\": \"uuid\", \"credential_id\": \"uuid\", \"mode\": \"paper\"}"}

// Get metrics
{"action": "metrics", "params": "{\"strategy_id\": \"uuid\"}"}
```

### marketplace

Horizon strategy marketplace. 18 actions across: browse (`browse`, `get_listing`, `leaderboard`), publish (`publish`, `my_listings`, `listing_earnings`), subscribe (`subscribe`, `unsubscribe`, `my_subscriptions`, `signals`), purchase (`purchase`, `my_purchases`), payments (`connect_payments`, `payment_status`), verification (`verify_performance`, `listing_badges`, `verify_trader`, `verification_status`).

```json theme={null}
// Browse strategies
{"action": "browse", "params": "{\"sort_by\": \"sharpe\", \"limit\": 20}"}

// Subscribe to signals
{"action": "subscribe", "params": "{\"listing_id\": \"uuid\", \"size_scale\": 0.5}"}
```

### fund

Multi-strategy fund management (requires `HORIZON_FUND_MODE=1`). 16 actions across: status (`status`, `report`, `risk_dashboard`, `stress_test`), strategies (`deploy_strategy`, `stop_strategy`, `pause_strategy`, `resume_strategy`, `list_strategies`, `scale_strategy`), analytics (`nav_history`, `pnl_attribution`, `correlation_matrix`, `execution_report`), memory (`memory_query`, `memory_record`).

```json theme={null}
// Deploy a strategy to the fund
{"action": "deploy_strategy", "params": "{\"name\": \"momentum\", \"markets\": [\"will-btc-hit-100k\"], \"mode\": \"paper\"}"}

// Get risk dashboard
{"action": "risk_dashboard", "params": "{}"}
```

### account

Horizon account and credentials. 3 actions: `setup`, `login`, `key_status`.

```json theme={null}
// Check key status
{"action": "key_status", "params": "{}"}
```

### equity

Equity and options market data. 6 actions: `quote`, `search`, `options_chain`, `greeks`, `iv_surface`, `screener`.

Uses [Unusual Whales](/providers/unusual-whales) as the data source.

```json theme={null}
// Stock quote
{"action": "quote", "params": "{\"symbol\": \"AAPL\"}"}

// Options chain
{"action": "options_chain", "params": "{\"symbol\": \"SPY\"}"}

// Greek exposure
{"action": "greeks", "params": "{\"symbol\": \"TSLA\"}"}

// IV term structure
{"action": "iv_surface", "params": "{\"symbol\": \"AAPL\"}"}

// Stock screener
{"action": "screener", "params": "{}"}
```

## Resources

The server exposes two MCP resources for context injection:

| URI                   | Description               |
| --------------------- | ------------------------- |
| `horizon://status`    | Engine status as JSON     |
| `horizon://positions` | Current positions as JSON |

Clients can attach these as context when starting a conversation.

## Error Handling

Every tool returns `{"error": "..."}` on failure instead of crashing the server. Common errors:

| Error                        | Cause                            |
| ---------------------------- | -------------------------------- |
| `"risk rejection: ..."`      | Order blocked by risk pipeline   |
| `"order not found: ..."`     | Invalid order ID for cancel      |
| `"feed not found: ..."`      | Unknown feed name                |
| `"unknown exchange: ..."`    | Invalid exchange in discover     |
| `"Unknown action '...'"`     | Invalid action for compound tool |
| `"Invalid params JSON: ..."` | Malformed params string          |

## Testing

Verify the server starts and responds to the MCP initialize handshake:

```bash theme={null}
echo '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-03-26","capabilities":{},"clientInfo":{"name":"test","version":"1.0"}}}' | python -m horizon.mcp
```

You should see a JSON-RPC response with the server's capabilities and 26 tools.
