lrvx-mcp
v0.12.1Model Context Protocol server for lrvx — gives AI agents grounded access to indicators, error codes, and the C API.
These tools were reported by the server itself during our smoke test (tools/list), not copied from the README.
lrvx_venue_guide
Use when the user wants to BUILD A MARKET rather than trade on one: simulate several agents/strategies against one shared order book, model market impact with reacting counterparties, or run a matching engine, clearing ledger, margin/liquidation, market-data feed or venue gateway. Returns a Markdown guide to the optional lrvx venue module (lrvx::venue): headers, order vocabulary, derivatives waterfall, the multi-agent demo, build flag, and verification posture. No arguments. Cheap; pure bundled text. NOT for an ordinary single-strategy backtest over historical data -- use run_backtest.
lrvx_overview
Call this FIRST when you don't know which lrvx MCP tool to use. Returns a Markdown narrative of the toolkit organised by category (discovery, building a backtest, live engine inspection, calibration), with canonical workflows for the most common tasks and a recent-additions section. No arguments. Cheap; pure bundled text. Cuts the AI-agent cycles spent rediscovering what the surface is on every fresh session.
list_indicators
List every indicator exposed by the lrvx Python binding with its class signature, batch function (if any), and shape (single-input scalar, OHLC tuple, multi-output, …). Use this when the user asks 'what indicators does lrvx support' or before suggesting an indicator name.
| Parameter | Type | Description |
|---|---|---|
filter | string | Optional substring filter; case-insensitive. |
lookup_error_code
Resolve a lrvx error code (e.g. 'E_SYM_001') to its full Markdown documentation page — fix recipe, common causes, diagnostics. Use whenever a LrvxError is raised in user code; never guess at a fix from the message alone.
| Parameter | Type | Description |
|---|---|---|
code * | string | Error code, e.g. 'E_SYM_001'. Case-sensitive. |
list_capi_functions
Search the lrvx C-API surface from the committed ABI snapshot. Returns name + return type + parameter types for every exported `lrvx_*` function. Use when the user is writing FFI code (Codon, QuickJS, Rust cgo, ctypes) or asks 'what C symbols can I call'.
| Parameter | Type | Description |
|---|---|---|
filter | string | Optional substring filter on function name. |
limit | integer | Max entries to return. Default 50. |
validate_strategy
Static-analysis check on a Python lrvx strategy: AST parses, expected hooks present (on_trade / on_bar), no forbidden patterns (eval, exec, __import__ tricks). Use this before running user-authored strategy code. Does NOT execute the code.
| Parameter | Type | Description |
|---|---|---|
code * | string | Python source for the strategy module/class. |
explain_event
Describe the fields of a lrvx event struct. Accepts a type name ('LrvxTradeData', 'LrvxBookData', 'LrvxBarData', 'LrvxSymbolContext', 'LrvxSignal') OR a raw event dict; returns each field's name, type, units, and human description. Use when the user asks 'what's in this event'.
| Parameter | Type | Description |
|---|---|---|
event | object | Optional event dict to introspect. If type_name is omitted, the dict's shape is matched against known struct shapes. |
type_name | string | Event struct name. One of: LrvxTradeData, LrvxBookData, LrvxBarData, LrvxSymbolContext, LrvxSignal. |
lookup_symbol
Resolve a lrvx symbol across every surface (C++, C-API, Python, Node, Codon, QuickJS). Methods resolve too, reported as Owner.method. Returns the local name, kind, and signature for each binding that exports it. Use this whenever the user names a struct, function, or indicator and you need to know what it's called in *their* language — never guess at the cross-language spelling. Accepts any spelling the user knows ('LrvxBarData', 'BarData', 'lrvx_indicator_ema', 'ema', 'Ema'). Filter to one language with the `language` arg if the user is writing in a specific binding. When the symbol has han…
| Parameter | Type | Description |
|---|---|---|
name * | string | Symbol name in any binding's spelling. Case-sensitive; common transformations (Lrvx prefix, lrvx_indicator_ prefix) are tried automatically. |
language | string | Optional binding filter. One of: capi, cpp, capi, python, node, codon, quickjs. |
list_bindings
Enumerate the public exports of one lrvx binding surface (C-API / Python / Node / Codon / QuickJS). Use this when the user asks 'what does the {Python|Node|Codon} binding expose?' or when they want to browse a binding before picking a symbol. Substring filter is case-insensitive.
| Parameter | Type | Description |
|---|---|---|
language * | string | Binding surface. One of: capi, python, cpp, capi, python, node, codon, quickjs. |
filter | string | Optional substring filter on symbol name. |
limit | integer | Max entries to return. Default 50. |
get_example
Return canonical lrvx example code for a topic, filtered optionally by language. Use this when the user asks 'show me how to {backtest|connect to ccxt|wire an indicator}' BEFORE writing fresh code from memory — the bundled examples are CI-validated, your generated code is not. Topics: strategy, connector, indicator, event-handler, risk, backtest. Languages: python, node, codon, cpp.
| Parameter | Type | Description |
|---|---|---|
topic * | string | Topic. One of: strategy, connector, indicator, event-handler, risk, backtest. |
language | string | Optional language filter. One of: python, node, codon, cpp. |
scaffold_strategy
Return a starter lrvx strategy class that compiles and passes `validate_strategy`. Use this as the *first* thing you write when the user asks to 'build a new strategy' — start from this canonical shell, then edit the indicator + signal logic, instead of writing the lrvx bookkeeping (constructor, hook names, signal builder) from memory. `language` is required — lrvx is polyglot and picking the binding for the user is wrong; ask which language they want first. Supported: python, node, codon, quickjs. Three kinds: bar-driven (TA on bar close), trade-driven (tick-by-tick), hybrid (both). The r…
| Parameter | Type | Description |
|---|---|---|
language * | string | Target language. Required. lrvx is polyglot — ask the user which binding they want before calling this tool. |
kind | string | Strategy shape. One of: bar-driven, trade-driven, hybrid. Default: bar-driven. |
name | string | Class name for the generated strategy. Must be a valid identifier. Default: MyStrategy. |
init_project
Create a new lrvx project from a bundled template. Thin wrapper around the canonical `lrvx new` CLI — the CLI stays the source of truth, this tool only makes it discoverable from MCP. Use when the user asks 'set up a new lrvx project' / 'I want to scaffold a research notebook' / 'start a live trading bot'. Three templates ship with lrvx: `research` (notebook + sample data + main.py), `live` (CCXT broker + dry-run safety harness), `indicator-library` (standalone indicator package with tests). Result includes the CLI output and a Next steps section with `docs_search` queries.
| Parameter | Type | Description |
|---|---|---|
project_name * | string | Directory name for the new project. Created under `target_dir`. Special characters in the name become snake_case in the bundled `__PROJECT_SLUG__`. |
template * | string | Template to scaffold from. Required. |
target_dir | string | Parent directory the project is created under. Default: current working dir. |
record_data
Capture market data into a `.lrvx` tape. Wraps the canonical recording paths — for `mode=live` shells out to the `lrvx tape record` CLI; for `mode=historical` shells out to `scripts/backfill_to_tape.py` which uses ccxt's `fetch_ohlcv` / `fetch_trades`. Use this when the user asks to 'record some BTC data' / 'pull a month of klines for backtest' / 'tape the last hour of trades'. The result is a `.lrvx` directory drivable by `BacktestRunner.run_tape`.
| Parameter | Type | Description |
|---|---|---|
exchange * | string | ccxt exchange id (bitget, binance, bybit, ...). |
mode * | string | `historical` = ccxt backfill of past data. `live` = capture from now onwards via `lrvx tape record`. |
out_path * | string | Output `.lrvx` directory (will be created if missing). |
symbol * | string | Symbol in the exchange's spelling (BTC/USDT, BTCUSDT — both accepted). |
data_type | string | Historical mode only. `klines` (1m bars by default) or `trades` (per-print). Trades have higher fidelity but are limited by what each exchange exposes. |
duration | string | Live mode. Recording duration (`1h`, `30m`, `2d`). Omit for an open-ended recording (Ctrl+C to stop). |
from_dt | string | Historical mode. Start datetime — ISO (2026-04-01) or unix-ms. |
max_records | integer | Historical mode. Refuse to start if estimated row count exceeds this. Default 1_000_000. |
to_dt | string | Historical mode. End datetime — ISO or unix-ms. |
run_backtest
Run a Python lrvx strategy against a CSV dataset in a sandboxed subprocess (rlimits on CPU / memory / output size + a wall-clock timeout). Use this when the user asks 'try this strategy on my data' or 'does this code actually work'. Treat as MVP sandbox: it caps resources but does NOT isolate the filesystem or network — never aim it at untrusted code outside a developer's own machine. Returns the backtest stats dict as JSON plus any stdout the strategy printed. Dispatch routing: the worker introspects the strategy class. If `on_bar` is overridden the dataset is dispatched as real `BarEvent`…
| Parameter | Type | Description |
|---|---|---|
dataset_path * | string | Absolute path to a CSV dataset on disk. Capped at 64 MiB. |
strategy_code * | string | Python source defining a `lrvx.Strategy` subclass at module level. The worker also accepts a top-level `STRATEGY = MyStrategy` assignment as the entry point. |
symbol | string | Symbol name to register before the run. Default: BTCUSDT. |
wall_timeout_s | integer | Wall-clock timeout in seconds. Default 60, capped at 600. |
compute_indicator
Run a single lrvx indicator over a list of floats and return the output. Use this to sanity-check an indicator's behaviour on a small price array BEFORE wiring it into a strategy — especially when the indicator has window / period / smoothing parameters whose effect isn't obvious from the name. Input is capped at 1 MiB. Requires the optional `lrvx` dependency.
| Parameter | Type | Description |
|---|---|---|
data * | array | Input series (e.g. close prices). Up to 125k samples. |
name * | string | Indicator name in lrvx — case either matches the class (`EMA`, `RSI`, `Bollinger`) or the function (`ema`, `rsi`, `vwap`). |
price_amm_swap
Price a DEX swap against an AMM pool, exact to the wei, through lrvx's integer curves. Use this to quote a fill or measure price impact on a constant-product (Uniswap v2), Raydium CP (Solana), or Uniswap v3 concentrated-liquidity pool from its on-chain state. Amounts are decimal strings (native wei / lamports), so 256-bit values are lossless. Requires the optional `lrvx` dependency.
| Parameter | Type | Description |
|---|---|---|
amount_in * | string | Input amount, native wei (decimal string). |
pool * | object | Pool parameters as decimal strings. constant_product: reserve0, reserve1, fee_num, fee_den. raydium_cp: reserve0, reserve1, trade_fee_rate. uniswap_v3: sqrt_price_x96, liquidity, fee_pips, ticks (opti… |
venue * | string | The pool's AMM type. |
i | integer | In-token index (default 0). |
j | integer | Out-token index (default 1). |
route_amm_swap
Best execution for a DEX swap across a set of AMM pools, exact to the wei. Give it the same notional and several venues (constant-product, Raydium CP, Uniswap v3) and it returns the venue that fills the most, the fill, and a per-venue comparison. Amounts are human 'NUMBER SYMBOL' strings (e.g. '50000 USDC'); each pool carries its token symbols and decimals, so directions are by symbol and a mis-routed swap raises instead of returning a quiet zero. Requires the optional `lrvx` dependency.
| Parameter | Type | Description |
|---|---|---|
amount * | string | Input amount as 'NUMBER SYMBOL', e.g. '50000 USDC'. |
venues * | array | Pool specs. Each: {venue, token0:{symbol,decimals}, token1:{symbol,decimals}, ... venue params}. constant_product/uniswap_v2: reserves (['1000 WETH','2000000 USDC']), fee, fee_den. raydium_cp: reserve… |
into | string | Out-token symbol (optional; inferred otherwise). |
amm_price_impact
The depth / slippage table for one AMM pool: the realized average price and price impact for each of a list of trade sizes, exact to the wei. Use this to reason about how large a trade a pool can absorb before quoting. Sizes are human 'NUMBER SYMBOL' strings. Requires the optional `lrvx` dependency.
| Parameter | Type | Description |
|---|---|---|
pool * | object | A pool spec: {venue, token0:{symbol,decimals}, token1:{symbol,decimals}, ...venue params}. |
sizes * | array | Trade sizes as 'NUMBER SYMBOL' strings. |
replay_pool_tape
Backtest a DEX position from a recorded pool history. Replays a list of swaps (or decoded Uniswap v2 Swap logs) through the exact curve and returns the price / reserves / LP-value / impermanent-loss / drift series over time. Use this to evaluate an LP position or a trading sequence against a real transcript. Requires the optional `lrvx` dependency.
| Parameter | Type | Description |
|---|---|---|
pool * | object | A pool spec: {venue, token0:{symbol,decimals}, token1:{symbol,decimals}, ...venue params} -- the replay's starting state. |
evm_logs | array | Decoded Uniswap v2 Swap log dicts (data word order amount0In, amount1In, amount0Out, amount1Out). Supply this or `swaps`. |
swaps | array | Swaps as [ts, 'NUMBER SYMBOL', into?] entries. Supply this or `evm_logs`. |
suggest_indicator
Recommend lrvx indicators for an English description of the user's intent ('trend filter', 'momentum oscillator', 'volatility band', 'mean revert', 'regime test'). Use this when the user describes what they want without naming an indicator — the tool maps phrasing to a ranked shortlist of real lrvx indicators. Pure keyword heuristic; no LLM call. Always confirm shape with `list_indicators` after picking one.
| Parameter | Type | Description |
|---|---|---|
description * | string | Free-text description of what kind of indicator the user wants. |
k | integer | How many candidates to return. Default 3. |
docs_search
Top-k full-text search over the lrvx documentation (how-to guides, reference pages, tutorials, error codes, bindings overviews, explanations). Use this to ground answers about lrvx behavior, configuration, or APIs in the actual docs instead of relying on training data — call it whenever the user asks 'how do I X' / 'what does Y do' / 'where is Z documented'. The index is built from a strict allowlist; private tracker / strategy / author files are NEVER indexed. Query syntax: plain word lists are AND-matched (every token must appear). Wrap a phrase in double quotes for exact match: `"walk fo…
| Parameter | Type | Description |
|---|---|---|
query * | string | Free-text query. Plain word lists are AND-matched. Wrap a phrase in double quotes for exact match. |
k | integer | Number of results to return (1..25). Default 5. |
get_positions
Read positions from a running lrvx engine via its runtime state snapshot. Use this when the user asks 'what's in my positions' / 'show me the BTC position' / 'is strategy X long or short'. Returns a JSON object {snapshot_age_ms, data:[{account, strategy, symbol_id, symbol_name, qty, avg_price, unrealized_pnl}, ...]}. Snapshot path is LRVX_RUNTIME_STATE env var or the passed `state_path`; the user app is responsible for writing the snapshot. When no engine has written a snapshot yet, returns {engine: 'not_running', data: [], hint: ...} instead of an error — that's a normal pre-engine state, n…
| Parameter | Type | Description |
|---|---|---|
account | string | Filter to one account. |
state_path | string | Override snapshot path (defaults to LRVX_RUNTIME_STATE or /tmp/lrvx-runtime-state.json). |
strategy | string | Filter to one strategy. |
get_open_orders
Read in-flight orders from the runtime state snapshot. Use this for 'what orders are pending' / 'do I have anything sitting on Bybit'. Optional substring filter matches against symbol_name or strategy. Returns the engine_not_running idle response when no snapshot is present yet (no error). Read-only.
| Parameter | Type | Description |
|---|---|---|
filter | string | Case-insensitive substring matched against symbol_name or strategy. |
state_path | string | Override snapshot path. |
get_pnl
Read PnL totals plus per-strategy breakdown from the runtime state snapshot. Use this for 'what's my PnL' / 'how is strategy X doing today'. Returns realized + unrealized + fees per strategy. Returns the engine_not_running idle response when no snapshot is present yet (no error). Read-only.
| Parameter | Type | Description |
|---|---|---|
state_path | string | Override snapshot path. |
strategy | string | Filter the per-strategy breakdown to one row; total still reflects the full snapshot. |
get_kill_switch
Read kill-switch state from the runtime state snapshot. Returns {active, reason, since_ns}. Use this for 'is trading halted' / 'why was the kill switch tripped'. When no engine has written a snapshot, returns the idle response with active=false (there is no live trading to halt). Read-only — to flip the switch use set_kill_switch.
| Parameter | Type | Description |
|---|---|---|
state_path | string | Override snapshot path. |
place_order
Place an order through the user's running lrvx engine. Talks HTTP to the local ControlServer the user app embeds; reads URL + bearer token from LRVX_CONTROL_URL and LRVX_CONTROL_TOKEN. Default dry_run=true; the server simulates acceptance without dispatching to the executor. live tier additionally requires an approve_token issued out of band by the operator. Use this for manual hedges or operator-driven order entry.
| Parameter | Type | Description |
|---|---|---|
account * | string | Account to place against. paper-prefixed names are allowed in paper scope; live scope is required for any other. |
qty * | number | |
side * | string | |
symbol * | integer | |
approve_token | string | Required for live scope. One-shot token issued by ControlServer.issue_approval(). |
dry_run | boolean | Default true. Set false to actually dispatch. |
price | number | Required for limit orders; ignored for market. |
reason | string | Free-text annotation recorded in the audit log. |
type | string | Default market. |
cancel_order
Cancel one open order by id. Talks HTTP to the local ControlServer. Default dry_run=true. Useful for operator-driven cleanup or panic stop. account is required and gated the same way as place_order: paper scope may only target paper-prefixed accounts.
| Parameter | Type | Description |
|---|---|---|
account * | string | Account the order belongs to. paper-prefixed names are allowed in paper scope; live scope is required for any other. |
order_id * | integer | |
dry_run | boolean |
cancel_all
Cancel every open order, optionally filtered by symbol. Default dry_run=true. The most common 'panic stop' primitive after set_kill_switch. account is required and gated the same way as place_order: paper scope may only target paper-prefixed accounts.
| Parameter | Type | Description |
|---|---|---|
account * | string | Account whose orders to cancel. paper-prefixed names are allowed in paper scope; live scope is required for any other. |
dry_run | boolean | |
symbol | integer | 0 (default) cancels across all symbols. |
flatten_positions
Close every open position with opposite-side market orders, optionally filtered by symbol. Default dry_run=true. Use for 'close everything' operator actions or end-of-day flatten. account is required and gated the same way as place_order: paper scope may only target paper-prefixed accounts, and rows the positions accessor tags with a different account are skipped.
| Parameter | Type | Description |
|---|---|---|
account * | string | Account whose positions to flatten. paper-prefixed names are allowed in paper scope; live scope is required for any other. |
dry_run | boolean | |
symbol | integer | Restrict to one symbol; omit to flatten all. |
set_kill_switch
Set the engine's kill-switch state. active=true halts all trading; active=false resumes. Default dry_run=true; explicit dry_run=false applies the change. Use for emergency halt and for resuming after manual review. The kill switch is engine-level, not per-account, so only live scope may call this -- paper tokens are refused even with dry_run=false.
| Parameter | Type | Description |
|---|---|---|
active * | boolean | |
dry_run | boolean | |
reason | string | Free-text annotation recorded in the audit log. |
list_strategies
List the strategies the running lrvx engine knows about, with name, status, and the symbols each one subscribes to. Read-only. Use when the user asks 'what's running' / 'which strategies are active'.
get_strategy_state
Return one strategy's current state as a JSON dict — params, position view, last decisions. Read-only. Use when the user asks 'what does strategy X think right now' / 'show me state for ema-trend'.
| Parameter | Type | Description |
|---|---|---|
name * | string |
get_indicator_values
Return the live values of indicators inside a strategy. Optional name filter narrows to one indicator. Read-only. Use for 'what's the EMA reading' / 'is the RSI overbought now'.
| Parameter | Type | Description |
|---|---|---|
strategy * | string | |
name | string | Optional: filter to one indicator. |
get_event_log
Query the engine event log (signals emitted, orders placed, fills received, risk checks). Filters AND-compose. Read-only. Use for 'what happened in the last 5 minutes' / 'show me all the signals from ema-trend'. Default limit 100.
| Parameter | Type | Description |
|---|---|---|
from_ts_ns | integer | |
limit | integer | Max records to return. Default 100. |
strategy | string | |
to_ts_ns | integer | |
type | string | Event type filter (e.g. 'signal', 'order', 'fill', 'risk_check'). |
explain_decision
Walk an event's causal-parent chain back toward the root. Returns the chain in order from the requested event to its root. Use when the user asks 'why did this fill happen' / 'trace the cause of order 42' — the chain shows which signal produced the order, which event triggered the signal, etc.
| Parameter | Type | Description |
|---|---|---|
event_id * | string | |
max_depth | integer | Stop walking after this many parents. Default 32. |
replay_window
Run a sandbox replay over a time window. The engine side decides what 'replay' means: typical setups use the bundled tape primitives to drive a SimulatedExecutor over a tape slice. Read-only (sandbox-only mutations). Use for 'replay the last hour' / 'rerun this period in sandbox'.
| Parameter | Type | Description |
|---|---|---|
from_ts_ns | integer | |
param_overrides | object | Optional dict of strategy params to swap before the replay. |
strategy | string | |
to_ts_ns | integer |
whatif
Counterfactual replay: same as replay_window plus a strategy-name filter and required param_overrides. Use for 'what if EMA period was 50 instead of 21' / 'show me the PnL if I had used a wider stop'.
| Parameter | Type | Description |
|---|---|---|
param_overrides * | object | |
strategy * | string | |
from_ts_ns | integer | |
to_ts_ns | integer |
validate_strategy_no_lookahead
Static-analysis check for the most common backtest bug: lookahead bias. Walks the strategy code's AST and flags .shift(-N) and np.roll(a, -N), forward-index arithmetic like df.iloc[i+1], forward slices like close[i:i+3], open-upper slices inside per-bar callbacks, and attribute names that look future-dated (next_*, future_*, lookahead_*). Only literal offsets are resolved; an offset held in a variable is not flagged. Heuristic, not a proof. Run before trusting any backtest result.
| Parameter | Type | Description |
|---|---|---|
code * | string | Python source of the strategy module / class. |