Backtrader MCP
English | 中文
Backtrader MCP is an independent, local-first MCP server for building and
running reproducible Backtrader strategies. It turns confined CSV files into
immutable datasets, typed strategy intent into private drafts, and reviewed
drafts into bounded subprocess runs with durable status and reports.
P0 is deliberately offline and backtest-only. It does not expose brokers,
stores, credentials, live orders, arbitrary Python execution, or network
transports.
Full documentation (English / 中文):
https://cloudquant.github.io/backtrader-mcp/ (also buildable on Read the
Docs; sources under docs/).
Distribution contract
- Python 3.10 or newer.
- MCP Python SDK
>=2.0.0,<2.1 (validated at 2.0.0), using MCPServer and
local stdio.
- Independent wheel/source distribution; the only accepted Backtrader runtime is
cloudQuant/backtrader, pinned in
package metadata to commit 3c967ed61be184c0099ba5bef55d4bed09ad0b4a.
- SQLite/WAL state, content-addressed CSV data, private draft files, HMAC
capabilities, filesystem locks, idempotency records, and startup recovery.
- Product-owned
prepare_strategy_run, start_strategy_run,
get_run_status, cancel_strategy_run, and get_run_result tools. MCP SDK
v2.0.0 does not provide the Tasks extension, so this product does not claim
it.
- Observability tools:
list_jobs (state-filtered job enumeration),
get_run_logs (bounded, path-sanitized job log tails), and
list_target_tree (read-only target preimages for exact change reviews);
get_run_status reports log_uri, elapsed_seconds, and eta_bound.
- All 30 tools carry readOnlyHint/destructiveHint/idempotentHint/openWorldHint
annotations. Tool errors cross the MCP boundary as structured
[code] message text with an optional Suggestion: next step; absolute
filesystem paths in error text and job logs are redacted.
The wheel includes seven JSON Schema contracts under
backtrader_mcp/schemas/ and the deterministic comparison policy under
backtrader_mcp/policies/. It also includes its own immutable full metadata
snapshot: 1,155 unique records covering 1,152 functional tests, 1,035
three-file strategy packages, and 1,032 verified mappings. The fourteen
current-fork template entries (seven archetypes by two output profiles) remain
separate from those corpus records.
Install without changing the base environment
From this directory, create and activate a dedicated virtual environment, then
install the package. python may be any supported Python 3.10+ interpreter:
python -m venv .runtime
. .runtime/bin/activate
python -m pip install -c constraints/requirements-v2.txt .
python -m backtrader_mcp --help
The package dependency installs that pinned CloudQuant source. For a source
checkout or an environment where the dependency was skipped, run the explicit
installer instead:
backtrader-mcp install-backtrader | python -m json.tool
It installs only when Backtrader is absent. If another Backtrader distribution
is already installed, it leaves that distribution untouched and returns the
machine-readable installed_backtrader_untrusted warning.
Register only absolute, trusted roots in the host environment:
BACKTRADER_MCP_STATE_ROOT=/absolute/private/state
BACKTRADER_MCP_SOURCE_ROOTS={"market_data":"/absolute/read-only/csv","functional_corpus":"/absolute/read-only/tests/functional/strategies","package_corpus":"/absolute/read-only/strategies"}
BACKTRADER_MCP_TARGET_ROOTS={"strategies":"/absolute/generated/strategies"}
BACKTRADER_MCP_RUNTIMES={"default":"/absolute/cloudquant-backtrader"}
Root maps are JSON objects. MCP callers receive only root IDs and relative
paths; they cannot submit absolute paths or executable paths. A runtime root
must contain backtrader/__init__.py and have Git origin resolving to
github.com/cloudquant/backtrader; another fork or the public PyPI package is
rejected before a strategy run. If BACKTRADER_MCP_RUNTIMES is omitted, a
verified installed CloudQuant distribution is registered as default.
Before adding a host, export the same values in the installation shell and run
the read-only diagnostic. Quoting the JSON values prevents the shell from
interpreting them:
export BACKTRADER_MCP_STATE_ROOT='/absolute/private/state'
export BACKTRADER_MCP_SOURCE_ROOTS='{"market_data":"/absolute/read-only/csv"}'
export BACKTRADER_MCP_TARGET_ROOTS='{"strategies":"/absolute/generated/strategies"}'
export BACKTRADER_MCP_RUNTIMES='{"default":"/absolute/cloudquant-backtrader"}'
backtrader-mcp doctor | python -m json.tool
doctor.status must be passed. The report is stable JSON and includes the
installed product and dependency versions, installed-Backtrader provenance,
configured root checks, supported adapters/run profiles, and the actual
Backtrader module_file, version, Git commit, branch, provenance, and runtime
capabilities. An existing non-CloudQuant installed package is reported as a
warning; a configured non-CloudQuant runtime is an error. The CLI diagnostic
itself does not create the state root or write to a source/target root; normal
MCP server startup initializes its private state root before tools are
available.
Catalog modes
get_catalog_snapshot returns the slim header by default: counts, hashes,
provenance, and extensions.entry_count, without the 1,155-record entry list.
Set include_entries=true to page through entries with limit (1-100) and
offset; the response reports pagination.total/has_more/truncated.
Every record has source_available=false: search and provenance are
available, but inspect_strategy does not pretend that the original source
bytes were shipped. list_strategy_templates (tool and resource) independently
returns all 14 current-fork archetype/profile templates.
search_strategy_catalog reports total/has_more/offset pagination
metadata and actionable empty-result suggestions.
For an explicit source-attached rebuild, register the functional and package
corpora as two read-only IDs in BACKTRADER_MCP_SOURCE_ROOTS, then call:
{
"tool": "refresh_strategy_catalog",
"arguments": {
"source_root_id": "functional_corpus",
"package_root_id": "package_corpus"
}
}
The server scans metadata and hashes only; it never imports, executes, or
modifies a corpus file. The result reports fresh
functional_tests/strategy_packages/mapped counts, a content hash, and a
diagnostic if they differ from the verified 1,152/1,035/1,032 baseline.
Source-attached records use source_available=true; subsequent
inspect_strategy detects changed functional or package bytes. Supplying only
source_root_id preserves the smaller AST-only refresh for a registered
strategy target root.
Host setup
Replace every /ABSOLUTE/PATH placeholder in the matching file.
Claude Desktop / Claude Code
Copy examples/hosts/claude-desktop.json into the host's MCP configuration,
or replace every placeholder and run this complete Claude Code command:
claude mcp add-json --scope project backtrader '{
"type": "stdio",
"command": "/ABSOLUTE/PATH/backtrader-mcp/.runtime/bin/backtrader-mcp",
"args": ["serve"],
"env": {
"BACKTRADER_MCP_STATE_ROOT": "/ABSOLUTE/PATH/.backtrader-mcp-state",
"BACKTRADER_MCP_SOURCE_ROOTS": "{\"market_data\":\"/ABSOLUTE/PATH/data\"}",
"BACKTRADER_MCP_TARGET_ROOTS": "{\"strategies\":\"/ABSOLUTE/PATH/generated-strategies\"}",
"BACKTRADER_MCP_RUNTIMES": "{\"default\":\"/ABSOLUTE/PATH/cloudquant-backtrader\"}"
}
}'
claude mcp list
Restart Claude Desktop after editing its JSON. Claude Code can verify the
project-scoped server with claude mcp list and its interactive /mcp view.
Codex
Merge examples/hosts/codex-config.toml into ~/.codex/config.toml or a
trusted project's .codex/config.toml, then restart the Codex client. The
Codex app, Codex CLI, and Codex IDE extension share this configuration.
Codex's own approval_policy governs the host, but it does not replace either
of this product's trusted local approval records.
The equivalent CLI registration is:
codex mcp add \
--env BACKTRADER_MCP_STATE_ROOT=/ABSOLUTE/PATH/.backtrader-mcp-state \
--env 'BACKTRADER_MCP_SOURCE_ROOTS={"market_data":"/ABSOLUTE/PATH/data"}' \
--env 'BACKTRADER_MCP_TARGET_ROOTS={"strategies":"/ABSOLUTE/PATH/generated-strategies"}' \
--env 'BACKTRADER_MCP_RUNTIMES={"default":"/ABSOLUTE/PATH/cloudquant-backtrader"}' \
backtrader -- /ABSOLUTE/PATH/backtrader-mcp/.runtime/bin/backtrader-mcp serve
codex mcp list --json
OpenCode
Merge examples/hosts/opencode.json into the global or project OpenCode
configuration. The current configuration places each named local server
directly below mcp; the command is an argument vector and enabled is true.
Run opencode mcp list and require the backtrader server to be connected
before starting a strategy request.
OpenClaw
Edit and run examples/hosts/openclaw-add.sh, then keep the successful
openclaw mcp doctor backtrader --probe output as setup evidence.
First host verification
All four adapters start the same stdio server. A successful connection performs
MCP initialize; the host then discovers tools/list, resources/list, and
prompts/list. Use the host's MCP view/logs to confirm those discovery calls,
then submit this non-mutating first request:
Use only the backtrader MCP server. Call doctor, then call
get_catalog_snapshot. Return doctor.status, the default runtime's module_file,
version and commit, plus snapshot.extensions.entry_count. Do not create a
draft, write a target, or start a run.
Expected evidence is doctor.status=passed, a module_file below the
registered runtime, the expected Backtrader version/commit, and catalog
entry_count=1155. Use these host-specific discovery checks:
| Host |
Registration check |
Interactive discovery |
| Claude Code |
claude mcp list |
/mcp shows backtrader, then run the first request |
| Codex |
codex mcp list --json |
Start/restart Codex, inspect its MCP tools, then run the first request |
| OpenCode |
opencode mcp list |
Require backtrader connected, then run the first request |
| OpenClaw |
openclaw mcp doctor backtrader --probe |
Inspect the workspace MCP tools, then run the first request |
For raw protocol evidence independent of host UI wording, the isolated v2
protocol test performs initialize, tools/list, resources/list,
prompts/list, and a typed get_catalog_snapshot call.
Host configuration references:
Claude MCP,
Codex MCP,
OpenCode MCP, and
OpenClaw MCP.
Upgrade and uninstall
For a compatible 0.2.x upgrade, stop every connected host, back up the
private state root, activate the dedicated environment, and reinstall:
. .runtime/bin/activate
python -m pip install --upgrade -c constraints/requirements-v2.txt .
backtrader-mcp doctor | python -m json.tool
Restart the host and repeat its registration check and first request. Do not
reuse draft validation tokens, change/run tokens, or approvals across an
incompatible release. This product does not migrate pre-P0 state.
To uninstall, first remove the backtrader MCP registration from each host
(or delete only its matching configuration entry), stop active runs, then:
. .runtime/bin/activate
python -m pip uninstall backtrader-mcp
Uninstalling the wheel intentionally leaves the configured state, datasets,
generated strategies, and source files untouched. Archive or remove those
paths separately only after reviewing their contents. If .runtime was
dedicated solely to this product, it can be removed with the platform's file
manager after deactivation.
Closed-loop workflow
inspect_dataset reads headers and a bounded sample from a configured
source root.
register_dataset requires an explicit canonical column map and writes a
normalized immutable CSV to the CAS. Registration fails if the source
changes while read.
preview_dataset reads a bounded CAS preview.
derive_tabular_dataset runs only identity, dropna, returns, or
sma with typed parameters and an exact source-manifest hash. It creates a
new dataset ID; no DataFrame, callable, pickle, or in-memory object crosses
the protocol. returns/sma drop their warmup rows and register the
derived column as a pandas_custom_lines feature line, so a derived
dataset can feed precomputed_ml strategies directly.
search_strategy_catalog selects one of seven archetypes.
create_strategy_draft renders either single_test or python_bundle.
All seven archetypes support both profiles. The spec may declare an
allowlisted analyzer set (extensions.analyzers: sqn/calmar/vwr/
timereturn) whose typed metrics flow into the result's extra_metrics,
and an optional canonical seed that freezes into the run manifest and
seeds the candidate's random/numpy state for reproducible strategies.
update_strategy_draft requires the current revision and file hash.