lrvx-mcp

v0.12.1
lrvx-mcp Checked 6 hours ago Published 16 days ago

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

ParameterTypeDescription
filterstringOptional 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.

ParameterTypeDescription
code *stringError 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'.

ParameterTypeDescription
filterstringOptional substring filter on function name.
limitintegerMax 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.

ParameterTypeDescription
code *stringPython 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'.

ParameterTypeDescription
eventobjectOptional event dict to introspect. If type_name is omitted, the dict's shape is matched against known struct shapes.
type_namestringEvent 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…

ParameterTypeDescription
name *stringSymbol name in any binding's spelling. Case-sensitive; common transformations (Lrvx prefix, lrvx_indicator_ prefix) are tried automatically.
languagestringOptional 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.

ParameterTypeDescription
language *stringBinding surface. One of: capi, python, cpp, capi, python, node, codon, quickjs.
filterstringOptional substring filter on symbol name.
limitintegerMax 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.

ParameterTypeDescription
topic *stringTopic. One of: strategy, connector, indicator, event-handler, risk, backtest.
languagestringOptional 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…

ParameterTypeDescription
language *stringTarget language. Required. lrvx is polyglot — ask the user which binding they want before calling this tool.
kindstringStrategy shape. One of: bar-driven, trade-driven, hybrid. Default: bar-driven.
namestringClass 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.

ParameterTypeDescription
project_name *stringDirectory name for the new project. Created under `target_dir`. Special characters in the name become snake_case in the bundled `__PROJECT_SLUG__`.
template *stringTemplate to scaffold from. Required.
target_dirstringParent 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`.

ParameterTypeDescription
exchange *stringccxt exchange id (bitget, binance, bybit, ...).
mode *string`historical` = ccxt backfill of past data. `live` = capture from now onwards via `lrvx tape record`.
out_path *stringOutput `.lrvx` directory (will be created if missing).
symbol *stringSymbol in the exchange's spelling (BTC/USDT, BTCUSDT — both accepted).
data_typestringHistorical mode only. `klines` (1m bars by default) or `trades` (per-print). Trades have higher fidelity but are limited by what each exchange exposes.
durationstringLive mode. Recording duration (`1h`, `30m`, `2d`). Omit for an open-ended recording (Ctrl+C to stop).
from_dtstringHistorical mode. Start datetime — ISO (2026-04-01) or unix-ms.
max_recordsintegerHistorical mode. Refuse to start if estimated row count exceeds this. Default 1_000_000.
to_dtstringHistorical 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`…

ParameterTypeDescription
dataset_path *stringAbsolute path to a CSV dataset on disk. Capped at 64 MiB.
strategy_code *stringPython source defining a `lrvx.Strategy` subclass at module level. The worker also accepts a top-level `STRATEGY = MyStrategy` assignment as the entry point.
symbolstringSymbol name to register before the run. Default: BTCUSDT.
wall_timeout_sintegerWall-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.

ParameterTypeDescription
data *arrayInput series (e.g. close prices). Up to 125k samples.
name *stringIndicator 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.

ParameterTypeDescription
amount_in *stringInput amount, native wei (decimal string).
pool *objectPool 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 *stringThe pool's AMM type.
iintegerIn-token index (default 0).
jintegerOut-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.

ParameterTypeDescription
amount *stringInput amount as 'NUMBER SYMBOL', e.g. '50000 USDC'.
venues *arrayPool 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…
intostringOut-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.

ParameterTypeDescription
pool *objectA pool spec: {venue, token0:{symbol,decimals}, token1:{symbol,decimals}, ...venue params}.
sizes *arrayTrade 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.

ParameterTypeDescription
pool *objectA pool spec: {venue, token0:{symbol,decimals}, token1:{symbol,decimals}, ...venue params} -- the replay's starting state.
evm_logsarrayDecoded Uniswap v2 Swap log dicts (data word order amount0In, amount1In, amount0Out, amount1Out). Supply this or `swaps`.
swapsarraySwaps 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.

ParameterTypeDescription
description *stringFree-text description of what kind of indicator the user wants.
kintegerHow many candidates to return. Default 3.

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…

ParameterTypeDescription
accountstringFilter to one account.
state_pathstringOverride snapshot path (defaults to LRVX_RUNTIME_STATE or /tmp/lrvx-runtime-state.json).
strategystringFilter 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.

ParameterTypeDescription
filterstringCase-insensitive substring matched against symbol_name or strategy.
state_pathstringOverride 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.

ParameterTypeDescription
state_pathstringOverride snapshot path.
strategystringFilter 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.

ParameterTypeDescription
state_pathstringOverride 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.

ParameterTypeDescription
account *stringAccount 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_tokenstringRequired for live scope. One-shot token issued by ControlServer.issue_approval().
dry_runbooleanDefault true. Set false to actually dispatch.
pricenumberRequired for limit orders; ignored for market.
reasonstringFree-text annotation recorded in the audit log.
typestringDefault 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.

ParameterTypeDescription
account *stringAccount the order belongs to. paper-prefixed names are allowed in paper scope; live scope is required for any other.
order_id *integer
dry_runboolean

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.

ParameterTypeDescription
account *stringAccount whose orders to cancel. paper-prefixed names are allowed in paper scope; live scope is required for any other.
dry_runboolean
symbolinteger0 (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.

ParameterTypeDescription
account *stringAccount whose positions to flatten. paper-prefixed names are allowed in paper scope; live scope is required for any other.
dry_runboolean
symbolintegerRestrict 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.

ParameterTypeDescription
active *boolean
dry_runboolean
reasonstringFree-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'.

ParameterTypeDescription
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'.

ParameterTypeDescription
strategy *string
namestringOptional: 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.

ParameterTypeDescription
from_ts_nsinteger
limitintegerMax records to return. Default 100.
strategystring
to_ts_nsinteger
typestringEvent 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.

ParameterTypeDescription
event_id *string
max_depthintegerStop 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'.

ParameterTypeDescription
from_ts_nsinteger
param_overridesobjectOptional dict of strategy params to swap before the replay.
strategystring
to_ts_nsinteger

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

ParameterTypeDescription
param_overrides *object
strategy *string
from_ts_nsinteger
to_ts_nsinteger

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.

ParameterTypeDescription
code *stringPython source of the strategy module / class.