# Cerbero MCP — API Reference (V2.0.0)

Documento di riferimento completo per tutti gli endpoint HTTP e i tool MCP
esposti dal container `cerbero-mcp`. Generato dall'analisi diretta dei
router FastAPI in `src/cerbero_mcp/routers/`.

---

## 1. Autenticazione

Tutte le chiamate ai namespace `/mcp-*` richiedono:

| Header | Valore | Note |
|---|---|---|
| `Authorization` | `Bearer <TOKEN>` | `TESTNET_TOKEN` → upstream testnet · `MAINNET_TOKEN` → upstream live · token sconosciuto → `401` |
| `X-Bot-Tag` | stringa ≤ 64 char | identifica il bot chiamante, loggato nell'audit · mancante → `400` |

Gli endpoint pubblici (`/health`, `/apidocs`, `/openapi.json`) non
richiedono auth. L'endpoint `/admin/audit` richiede bearer ma **non**
richiede `X-Bot-Tag`.

---

## 2. Endpoint pubblici

| Path | Metodo | Descrizione |
|---|---|---|
| `/health` | GET | Liveness — sempre `200` finché il processo è vivo |
| `/health/ready` | GET | Readiness — itera i client registry, status `ready` / `degraded` / `not_ready`. Forza `503` se `READY_FAILS_ON_DEGRADED=true` |
| `/apidocs` | GET | Swagger UI interattiva |
| `/openapi.json` | GET | Schema OpenAPI 3.1 |

---

## 3. Endpoint admin

| Path | Metodo | Descrizione |
|---|---|---|
| `/admin/audit` | GET | Query del JSONL `AUDIT_LOG_FILE`. Filtri: `from`, `to`, `actor`, `exchange`, `action`, `bot_tag`, `limit` (default 1000, max 10000) |
| `/admin/ibkr/rotate-keys/confirm?env=` | POST | Swap atomico chiavi IBKR con auto-rollback su validazione fallita |

---

## 4. Namespace MCP — panoramica

| Namespace | Tool | Tipo | Note |
|---|---|---|---|
| `/mcp-deribit/tools/*` | 33 | exchange (options-first) | DVOL, GEX, dealer gamma, spread payoff |
| `/mcp-bybit/tools/*` | 30 | exchange (spot + perp + options) | basis, funding, batch orders |
| `/mcp-hyperliquid/tools/*` | 16 | exchange (perp DEX) | L1 signing, leverage cap |
| `/mcp-alpaca/tools/*` | 18 | exchange (US stocks + options) | clock/calendar, fractional |
| `/mcp-ibkr/tools/*` | 24 | exchange (multi-asset broker) | OAuth 1.0a, streaming WS, bracket/OCO/OTO |
| `/mcp-macro/tools/*` | 11 | data provider (read-only) | yields, FRED, COT |
| `/mcp-sentiment/tools/*` | 9 | data provider (read-only) | news, social, funding cross-exchange |
| `/mcp-cross/tools/*` | 1 | aggregator | storico consensus multi-exchange |

**Totale**: ~142 tool MCP.

---

## 5. `/mcp-deribit/tools/*`

### Info
- `is_testnet` — flag ambiente corrente
- `environment_info` — stringa diagnostica completa

### Market data
- `get_ticker`, `get_ticker_batch`
- `get_instruments`
- `get_orderbook`, `get_orderbook_imbalance`
- `get_historical` (chiave `candles` uniforme)
- `get_trade_history`

### Account
- `get_positions`
- `get_account_summary`

### Options analytics
- `get_dvol`, `get_dvol_history`
- `get_gex`, `get_dealer_gamma_profile`
- `get_vanna_charm`
- `get_oi_weighted_skew`, `get_smile_asymmetry`, `get_atm_vs_wings_vol`
- `get_pc_ratio`, `get_skew_25d`, `get_term_structure`
- `get_iv_rank`, `get_realized_vol`
- `find_by_delta`, `calculate_spread_payoff`

### Technicals
- `get_technical_indicators`
- `run_backtest`

### Write (richiede leverage cap)
- `place_order`, `place_combo_order`
- `cancel_order`
- `set_stop_loss`, `set_take_profit`
- `close_position`

---

## 6. `/mcp-bybit/tools/*`

### Info
- `environment_info`

### Market data
- `get_ticker`, `get_ticker_batch`
- `get_orderbook`, `get_orderbook_imbalance`
- `get_historical`
- `get_instruments`, `get_option_chain`
- `get_trade_history`

### Derivati
- `get_funding_rate`, `get_funding_history`
- `get_open_interest`
- `get_basis_spot_perp`, `get_basis_term_structure`

### Account
- `get_positions`, `get_account_summary`, `get_open_orders`

### Technicals
- `get_indicators`

### Write
- `place_order`, `place_combo_order`
- `amend_order`, `cancel_order`, `cancel_all_orders`
- `set_stop_loss`, `set_take_profit`, `close_position`
- `set_leverage`, `switch_position_mode`
- `transfer_asset`

---

## 7. `/mcp-hyperliquid/tools/*`

### Info
- `environment_info`

### Market data
- `get_markets`, `get_ticker`, `get_orderbook`
- `get_historical`, `get_trade_history`
- `get_funding_rate`, `basis_spot_perp`

### Account
- `get_positions`, `get_account_summary`, `get_open_orders`

### Technicals
- `get_indicators`

### Write (L1 signing + leverage cap)
- `place_order`, `cancel_order`
- `set_stop_loss`, `set_take_profit`
- `close_position`

---

## 8. `/mcp-alpaca/tools/*`

### Info / calendar
- `environment_info`, `get_clock`, `get_calendar`

### Market data
- `get_assets`, `get_ticker`
- `get_bars`, `get_snapshot`
- `get_option_chain`

### Account
- `get_account`, `get_positions`, `get_activities`, `get_open_orders`

### Write
- `place_order`, `amend_order`
- `cancel_order`, `cancel_all_orders`
- `close_position`, `close_all_positions`

> **Nota**: override URL applicato solo all'endpoint trading. Gli
> endpoint dati (`data.alpaca.markets`) restano i default SDK.

---

## 9. `/mcp-ibkr/tools/*`

Auth via OAuth 1.0a Self-Service con minting di session token
unattended. Setup one-time per ambiente (paper + live) — vedi sezione
"IBKR Setup" del README.

### Info / clock
- `environment_info`, `get_clock`

### Account
- `get_account`, `get_positions`
- `get_open_orders`, `get_activities`

### Market data
- `get_ticker`, `get_bars`, `get_snapshot`
- `get_option_chain`, `search_contracts`

### Streaming (WebSocket singleton)
- `get_tick`, `get_depth`
- `subscribe_tick`, `unsubscribe`

### Write
- `place_order`, `amend_order`
- `cancel_order`, `cancel_all_orders`
- `close_position`, `close_all_positions`

### Complex orders
- `place_bracket_order` — entry + TP + SL atomico
- `place_oco_order` — One-Cancels-Other (OCA group)
- `place_oto_order` — One-Triggers-Other (parent → child)

---

## 10. `/mcp-macro/tools/*` (read-only)

| Tool | Sorgente |
|---|---|
| `get_economic_indicators` | FRED + Yahoo |
| `get_macro_calendar` | Finnhub + impact heuristic |
| `get_market_overview` | mix Yahoo + Deribit DVOL |
| `get_asset_price` | Yahoo Finance |
| `get_treasury_yields` | US Treasury XML |
| `get_equity_futures` | Yahoo |
| `get_yield_curve_slope` | derivato da treasury yields |
| `get_breakeven_inflation` | FRED (T10YIE / T5YIE) |
| `get_cot_tff` | CFTC TFF report |
| `get_cot_disaggregated` | CFTC disaggregated report |
| `get_cot_extreme_positioning` | percentili COT (gate ±5%) |

---

## 11. `/mcp-sentiment/tools/*` (read-only)

| Tool | Fonte |
|---|---|
| `get_crypto_news` | CryptoPanic + CoinDesk + CryptoCompare + Messari (deduped) |
| `get_world_news` | aggregato generalista |
| `get_social_sentiment` | LunarCrush + Fear&Greed Index |
| `get_funding_rates` | per-asset multi-exchange |
| `get_cross_exchange_funding` | snapshot multi-asset multi-venue |
| `get_funding_arb_spread` | spread arbitraggio funding |
| `get_oi_history` | open interest serie storica |
| `get_liquidation_heatmap` | heatmap liquidazioni |
| `get_cointegration_pairs` | screening coppie cointegrate |

---

## 12. `/mcp-cross/tools/*`

### `get_historical`
Aggregatore cross-exchange. Fan-out a tutti gli exchange che supportano
`(symbol, asset_class)`, poi consensus per-bar:

- `close` = mediana delle close
- `open`/`high`/`low` = mediana corrispondente
- `sources` = numero di exchange che hanno contribuito al bar
- `div_pct = (max - min) / median` → quality gate per i bot

**Crypto** (`asset_class: "crypto"`): BTC, ETH, SOL via Bybit +
Hyperliquid + Deribit.
**Stocks** (`asset_class: "stocks"`): AAPL, SPY, QQQ, TSLA, NVDA via
Alpaca.

In caso di fallimento parziale ritorna i bar disponibili più
`failed_sources: [...]`. Se *tutti* gli upstream falliscono → `502
Bad Gateway` retryable.

---

## 13. Observability

### Request log (`mcp.request`)
Una riga JSON per richiesta con: `request_id`, `method`, `path`,
`status_code`, `duration_ms`, `actor`, `bot_tag`, `exchange`, `tool`,
`client_ip`, `user_agent`.

### Audit log (`mcp.audit`)
Persistito su `AUDIT_LOG_FILE` (JSONL) per le operazioni write.
Rotazione configurabile via `AUDIT_LOG_BACKUP_DAYS`.

### Correlation
Lo stesso `request_id` appare in `mcp.request`, `mcp.audit` e
nell'envelope di errore restituito al client.

---

## 14. Esempio chiamata

```bash
curl -X POST http://localhost:9000/mcp-bybit/tools/get_ticker \
  -H "Authorization: Bearer $MAINNET_TOKEN" \
  -H "X-Bot-Tag: scanner-alpha-prod" \
  -H "Content-Type: application/json" \
  -d '{"symbol":"BTCUSDT","category":"linear"}'
```

Per lo schema completo dei body di richiesta e risposta:
<http://localhost:9000/apidocs>.

---

## 15. Discovery strumenti — schemi `get_instruments` / `get_markets` / `get_historical`

Schemi dei body verificati sull'OpenAPI live (usati da `src/data/instruments.py`).

### Lista strumenti
| Exchange | Tool | Body | Risposta (campi utili) |
|---|---|---|---|
| Deribit | `get_instruments` | `{currency:"any", kind:"future", offset:int, limit:100}` (paginato, `has_more`) | `instruments[].name` (es. `BTC-PERPETUAL`, `SOL_USDC-PERPETUAL`), `expiry`, `tick_size` |
| Bybit | `get_instruments` | `{category:"linear", symbol?}` | `instruments[]`: `symbol`, `status`, `base_coin`, `quote_coin` |
| Hyperliquid | `get_markets` | `{}` | lista `{asset, mark_price, funding_rate, open_interest, volume_24h, max_leverage}` |

### Storico OHLCV (`get_historical`, chiave `candles` uniforme `{timestamp(ms),open,high,low,close,volume}`)
| Exchange | Body |
|---|---|
| Deribit | `{instrument, start_date:"YYYY-MM-DD", end_date, resolution}` — resolution `1/5/15/60/1D` |
| Bybit | `{symbol, category:"linear", interval:"1/5/15/60/D", start:int_ms, end:int_ms, limit}` |
| Hyperliquid | `{asset|instrument, start_date, end_date, resolution:"1m/5m/15m/1h/1d", limit}` |

### Simboli Deribit
- BTC/ETH → perpetui **inverse**: `BTC-PERPETUAL`, `ETH-PERPETUAL`
- Altcoin → perpetui **lineari USDC**: `<COIN>_USDC-PERPETUAL` (es. `SOL_USDC-PERPETUAL`)
- Trappola: `LTC-PERPETUAL`/`ADA-PERPETUAL` non esistono; `SOL-PERPETUAL` esiste ma è un contratto sbagliato (prezzo ~9.6 vs SOL reale ~82).

### Validazione (lato progetto)
`src/data/instruments.py` valida ogni strumento sui dati storici realmente
raccoglibili — esistenza, congruenza OHLC, not-flat, liquidità (volume daily) e
**congruenza prezzo cross-exchange** (scostamento dalla mediana del base-coin ≤5%).
Solo gli exchange con feed affidabile sono inclusi: **Deribit** e **Hyperliquid**
(esclusi Alpaca/stocks e **Bybit**, il cui feed testnet è farlocco). Output in
`data/instruments_registry.json`; il downloader scarica **solo** strumenti validati.

> **Testnet.** Il token osservatore punta a testnet (`"testnet": true` nei ticker):
> i prezzi possono divergere dal mainnet. La congruenza cross-exchange via mediana
> è il filtro che scarta i feed incongrui prima di usarli per backtest/trading.
