Bentrix Docs
HomePricingDashboard

The Rust SDK

Rust: bentrix::connect, and every tool is a method taking an arguments builder.

The client is the crate bentrix on crates.io. It finds the Bentrix running on this computer through the agents folder Bentrix writes at every start, pairs with it under the name you give — the name the person sees in ☰ › Settings › Agents, where the pairing's scopes are set — and talks to it over MCP. Nothing is typed: no address, no key.

01What you need

Rust (stable), and Bentrix open on the same computer.

02Install

Two ways, the same crate either way.

From crates.io. The client is the crate bentrix, its version the application's:

cargo add bentrix serde_json

From its source on your computer. Its source is github.com/bentrixhq/bentrix-rust, under the MIT licence; a clone of it is the SDK on your computer:

git clone https://github.com/bentrixhq/bentrix-rust

and name it by its path in your Cargo.toml:

[dependencies]
bentrix = { path = "../bentrix-rust" }
serde_json = "1"

03Connect

use bentrix as mcp;

fn main() -> Result<(), mcp::Error> {
    let b = mcp::connect(Some("my-agent"))?;
    let state = b.workspace().get_state(mcp::WorkspaceGetStateArgs::new())?;
    let bench = state["laboratories"][0]["benches"][0]["uri"].as_str().unwrap_or_default().to_string();
    let p: Vec<&str> = bench.trim_start_matches("bentrix://").split('/').collect();
    let book = b.trade().book(mcp::TradeBookArgs::new(p[0], p[1], p[3]))?;
    println!("{}", book["positions"]);
    Ok(())
}

04How a call looks

Every tool of the catalogue is a method, grouped by its domain: b.workspace(), b.chart(), b.study(), b.trade() …. A method takes the tool's arguments as one builder named after the tool — mcp::ChartOpenArgs::new(bench, symbol) takes the required arguments, and a method per optional one (.timeframe("H1")), and answers the tool's answer as a serde_json::Value. The whole list is at the end of this page; each method links to its tool's full entry — the arguments with their types and defaults, the scope a pairing must grant, and the plan.

05When Bentrix says no

A tool that runs and refuses answers an mcp::Error carrying the product's own sentence. The client also checks, when it connects, that the catalogue it was generated from is the one the running Bentrix serves: a different major version is refused before any call, so a program never calls a tool with arguments that no longer fit.

Busy is waited out, not raised. Bentrix answers one program at most 20 calls a second (a burst of 60), and answers a call past that busy (-40001, with the wait in retryAfterMs) before running anything. The client waits that long and sends the call again — so an order is never sent twice by it — up to ten times, each wait at most five seconds, and only then raises the refusal: bentrix::BUSY (-40001), BUSY_RETRIES (10) and BUSY_WAIT_MAX (5 s).

06Long work and streams

A tool that starts long work — a strategy run, a batch, a question put to the person in Bentrix's own window — answers a job; a job's method answers a Job read until it ends. A stream (bars as they close, ticks, quotes, deals, the Journal) is followed with wait_for, which answers what came after the cursor it is given and the cursor to give next.

Your first program

Save this as a file, with Bentrix open on this computer. It connects, lists your laboratories and their workbenches, and prints the selected workbench’s markets.

use bentrix as mcp;

fn main() -> Result<(), mcp::Error> {
    let client = mcp::connect(Some("my-agent"))?;

    // Every laboratory, and the workbenches in it.
    let state = client.workspace().get_state(mcp::WorkspaceGetStateArgs::new().depth("benches"))?;
    for lab in state["laboratories"].as_array().into_iter().flatten() {
        println!("laboratory: {}", lab["name"]);
        for bench in lab["benches"].as_array().into_iter().flatten() {
            println!("  workbench: {}", bench["uri"]);
        }
    }
    Ok(())
}

Run it

cargo run

The first run pairs the program: it appears in ☰ › Settings › Agents under the name it gave (my-agent), with the scopes read, lab and paper. If it says Bentrix is not running, open Bentrix and run it again.

A larger program, the one the tests run

This is the program Bentrix’s own tests run in Rust against a running Bentrix: it reads the workspace and a workbench’s book, is refused in the product’s words, and runs a reinforcement-learning episode through the tools.

use bentrix as mcp;
use serde_json::{json, Value};

fn check(held: bool, what: &str) -> Result<(), mcp::Error> {
    if held {
        Ok(())
    } else {
        Err(mcp::Error::Other(format!("FAILED: {what}")))
    }
}

fn main() -> Result<(), mcp::Error> {
    let b = mcp::connect(Some("rust-walk"))?;
    let state = b.workspace().get_state(mcp::WorkspaceGetStateArgs::new())?;
    let bench = state["laboratories"][0]["benches"][0]["uri"].as_str().unwrap_or_default().to_string();
    let p: Vec<&str> = bench.trim_start_matches("bentrix://").split('/').collect();
    let book = b.trade().book(mcp::TradeBookArgs::new(p[0], p[1], p[3]))?;
    check(book["positions"].is_array(), &format!("the book did not read: {book}"))?;
    let said = b.call("no_such_tool", Value::Null).err().map(|e| e.to_string()).unwrap_or_default();
    check(said.contains("no_such_tool"), &format!("a refusal did not say its tool: {said}"))?;

    let made = b.strategy().env_make(mcp::StrategyEnvMakeArgs::new(bench.clone()).interval("H1").window(8).episode("window").episode_bars(12))?;
    let env = made["env"].as_str().unwrap_or_default().to_string();
    let start = b.strategy().env_reset(mcp::StrategyEnvResetArgs::new(env.clone()).seed(5))?;
    check(start["obs"]["market"].as_array().map(Vec::len) == Some(8), "the observation is not shaped as declared")?;
    let mut rewards = Vec::new();
    let mut hashes = vec![start["info"]["ledger_hash"].clone()];
    for a in [1, 1, 2, 0, 2, 2, 1, 0, 1, 2, 0, 1] {
        let s = b.strategy().env_step(mcp::StrategyEnvStepArgs::new(env.clone(), a))?;
        rewards.push(s["reward"].as_f64().unwrap_or(f64::NAN));
        hashes.push(s["info"]["ledger_hash"].clone());
        if s["terminated"] == true || s["truncated"] == true {
            break;
        }
    }
    b.strategy().env_close(mcp::StrategyEnvCloseArgs::new(env.clone()))?;
    // A tool's own refusal (isError), not a request the wire refused.
    let refusal = b.strategy().env_step(mcp::StrategyEnvStepArgs::new(env, 0)).err();
    check(matches!(&refusal, Some(mcp::Error::Tool { message, .. }) if message.contains("No environment")), &format!("a closed environment's step was not refused in its words: {refusal:?}"))?;
    check(hashes.iter().any(|h| *h != hashes[0]), "the episode traded nothing")?;
    // serde_json writes an f64 in the shortest digits that read back as the same double.
    println!("{}", json!({"start_ms": start["info"]["start_ms"], "rewards": rewards, "hashes": hashes}));
    println!("PASS");
    Ok(())
}

Next

Bentrix 0.1.382Every number, name and default on these pages is read from the application itself.What is comingWhat changed