mcp-mt5
v0.5.0MCP server for MetaTrader 4/5 build pipeline — compile, deploy, backtest, parse reports
These tools were reported by the server itself during our smoke test (tools/list), not copied from the README.
env_info
Resolve and report MT4/5 paths, terminal hash, and missing-component issues.
list_terminals
Enumerate all MetaTrader terminal data folders under %APPDATA%\MetaQuotes\Terminal.
compile
Compile one MQL source with MetaEditor and return structured diagnostics. `ok` is true only when the log has a `Result:` line with 0 errors AND (unless `syntax_only`) a fresh .ex5/.ex4 was produced (`binary_fresh`). Fix every entry in `errors` (file, line, col, code, message) and call again; warnings do not block deployment. Takes 1-30 s. To also copy the binary into Experts/ use `compile_and_deploy`.
| Parameter | Type | Description |
|---|---|---|
source * | string | Absolute Windows path to the .mq4/.mq5/.mqh source file. |
include | MQL root folder (parent of Include/) if different from the active terminal's. | |
log_file | Explicit path for the compile log; defaults to .mt5tmp/<stem>.compile.log next to the source. | |
syntax_only | boolean | true = MetaEditor /s syntax check only: faster, produces no binary. |
timeout_sec | integer | Give up after this many seconds. |
run_backtest
Run a Strategy Tester backtest headlessly from a tester.ini and wait for it to finish. Requires the EA to be deployed first (`compile_and_deploy` / `deploy_ea`) and `ShutdownTerminal=1` in the ini, otherwise the call runs until `timeout_sec`. Typically 1-30 minutes; progress notifications are sent every few seconds while waiting. If the tester reports "cannot synchronize history" (first headless start after login), the run is retried once automatically. For long runs prefer `start_backtest` + `get_backtest`. Returns `run_id`, `report_path` (resolved from `Report=` in t…
| Parameter | Type | Description |
|---|---|---|
config * | string | Absolute path to the tester.ini file. |
portable | boolean | Pass /portable so the terminal uses its install folder as data folder. |
timeout_sec | integer | Give up (and kill the terminal) after this many seconds. |
wait | boolean | true = block until the terminal exits (needs ShutdownTerminal=1); false = launch and return a run_id for get_backtest. |
start_backtest
Launch a backtest in the background and return immediately with a `run_id`. Poll `get_backtest(run_id)` until `status` is no longer "running"; the final record carries `report_path` and `journal_notes`. Runs are also written to `.mt5tmp/runs/<run_id>.json` next to the ini. Only one terminal per install can test at a time.
| Parameter | Type | Description |
|---|---|---|
config * | string | Absolute path to the tester.ini file. |
portable | boolean | Pass /portable so the terminal uses its install folder as data folder. |
timeout_sec | integer | Kill the terminal if it has not exited after this many seconds. |
get_backtest
Status of a background backtest (running / completed / timeout / cancelled) with report path and journal notes when done; without run_id, lists all runs newest first.
| Parameter | Type | Description |
|---|---|---|
run_id | Identifier returned by start_backtest / run_backtest; omit to list every run of this server process. | |
tail_lines | integer | While running, include this many trailing lines of the tester journal. |
cancel_backtest
Kill the terminal of a running background backtest. No report is produced for a cancelled run.
| Parameter | Type | Description |
|---|---|---|
run_id * | string | Identifier returned by start_backtest / run_backtest. |
kill_terminal
Force-kill terminal processes launched by this server (run_backtest / smoke_test). By default only PIDs this server started are killed, so a live-trading terminal on the same machine is never touched. Pass `all_instances=True` to `taskkill` every terminal64.exe/terminal.exe of the configured edition (destructive).
| Parameter | Type | Description |
|---|---|---|
all_instances | boolean | false = only terminals launched by this server; true = taskkill every terminal of this edition (may hit a live-trading terminal). |
tail_log
Tail a MetaTrader log: the EA's LiveLog.txt, the daily Experts journal, or the latest tester journal. Use mode="tester" right after a backtest to see runtime errors and the effective test period.
| Parameter | Type | Description |
|---|---|---|
date | Journal date as YYYYMMDD; defaults to today. | |
lines | integer | Number of lines from the end of the file. |
mode | string | "live" = MQL5/Files/LiveLog.txt written by the EA, "journal" = MQL5/Logs/YYYYMMDD.log (Experts tab), "terminal" = logs/YYYYMMDD.log (Journal tab: connection, tester start), "tester" = newest Tester/lo… |
structured | boolean | Parse journal lines into {ts, source, message} records (journal/tester modes). |
list_experts
List compiled EAs in Experts/ (defaults to *.ex5 for MT5, *.ex4 for MT4).
| Parameter | Type | Description |
|---|---|---|
pattern | Glob pattern; defaults to *.ex5 on MT5 and *.ex4 on MT4. | |
recurse | boolean | Include subfolders of Experts/. |
read_tester_report
Parse a Strategy Tester HTML report (MT5 or MT4) into `summary` metrics; the full HTML stays behind `report_uri`. Prefer passing the `report_path` returned by `run_backtest`/`get_backtest`; without `path` the newest report on disk is used, which may belong to an older run. `summary` values are the strings printed in the report ("10 000.00", "359.61 (3.34%)"); use `compare_reports` / `regression_check` for numeric comparison. Read the `mt5://report/{id}` resource only when you need the original HTML.
| Parameter | Type | Description |
|---|---|---|
max_trades | integer | Max trade rows to return in `trades` when response_format="detailed". |
path | Absolute path to a report .htm; defaults to the newest report found on disk. | |
raw_truncate | integer | Characters of raw HTML to inline (0 = none; read report_uri instead). |
response_format | string | "concise" = summary metrics + counts + report_uri; "detailed" adds the parsed trade rows. |
patch_tester_ini
Set keys in a tester.ini in place, keeping the file's encoding and other lines. `updates` maps "Section.Key" to a value, e.g. {"Tester.Symbol": "EURUSD", "Tester.FromDate": "2025.01.01", "TesterInputs.RiskPct": "1.5"}. Missing sections/keys are added. Run `validate_tester_ini` afterwards; always set Deposit, Currency, Leverage, Model, Optimization, Visual, UseLocal/UseRemote/UseCloud and Report explicitly so a run does not inherit the machine's last UI state.
| Parameter | Type | Description |
|---|---|---|
config * | string | Absolute path to the tester.ini file. |
updates * | object | Mapping of "Section.Key" to new value, e.g. {"Tester.Symbol": "EURUSD"}. |
compile_and_deploy
Compile a source and, if it succeeds, copy the fresh binary into the terminal's Experts/ folder. Use this before `run_backtest` or `smoke_test`. Returns the `compile` result plus `deploy`; `ok` is false if either stage failed (compile errors are in `compile.errors`).
| Parameter | Type | Description |
|---|---|---|
source * | string | Absolute Windows path to the .mq4/.mq5/.mqh source file. |
ea_name | File name for the binary inside Experts/; defaults to <stem>.ex5. |
deploy
Copy a compiled EA into the terminal's Experts/ folder or a .mqh header into Include/, chosen by extension. Overwrites an existing file of the same name. Use `compile_and_deploy` to build and copy in one step.
| Parameter | Type | Description |
|---|---|---|
file * | string | Absolute path to a compiled .ex4/.ex5 (goes to Experts/) or a .mqh header (goes to Include/). |
name | File name to use in the target folder; defaults to the source file name. |
inspect_source
Read-only facts about MQL source: `input` declarations, #include tree (with missing files), MetaEditor doc blocks, symbol usages, duplicate magic numbers. Replaces extract_inputs / resolve_includes / extract_doc / find_symbol / find_magic_collision.
| Parameter | Type | Description |
|---|---|---|
aspects | array | Which analyses to run; defaults to inputs, includes and docs for a source, plus symbol when `symbol` is given and magic when only `root` is given. |
limit | integer | Max symbol matches to return. |
mql_root | MQL root used to resolve <angle> includes; defaults to the active terminal. | |
root | Absolute project folder to scan (for symbol, magic); defaults to the source file folder. | |
source | Absolute path to one .mq4/.mq5/.mqh file (for inputs, includes, docs). | |
symbol | Identifier to grep for (whole word, comments and strings skipped); enables the "symbol" aspect. | |
var_pattern | string | Substring identifying magic-number variables for the "magic" aspect. |
analyze_mql
Static checks on MQL source without compiling: structural lint (missing OnInit/OnTick, unused inputs, hardcoded magic/symbol), MT4-style deprecated API calls with MT5 replacements, and size/nesting metrics. Replaces lint_basic / check_deprecated / code_metrics. Use `compile(syntax_only=true)` for real compiler diagnostics.
| Parameter | Type | Description |
|---|---|---|
checks | array | Which checks to run; default all. |
root | Absolute folder to aggregate metrics over every MQL file (metrics check only). | |
source | Absolute path to one .mq4/.mq5/.mqh file. |
read_optimization
Read an MT5 optimisation cache (.opt): header, optimised inputs, pass count and the top N passes by `criterion`. Ranking uses every pass in the cache. The best pass of a genetic run is a biased sample; prefer robust neighbourhoods over the single top row. Replaces parse_optimization / top_passes.
| Parameter | Type | Description |
|---|---|---|
criterion | string | Pass field to rank by: profit, profit_factor, expected_payoff, recovery_factor, sharpe_ratio, maxdrawdown, trades, custom_fitness. |
descending | boolean | true = highest first; use false for drawdown-style metrics. |
expert | Expert name (file stem) used to select the matching cache file. | |
path | Absolute path to a Tester/cache/*.opt file; defaults to the newest cache matching expert/symbol/period. | |
period | Timeframe code such as M15, H1, D1. | |
symbol | Symbol name as shown in Market Watch, e.g. EURUSD. | |
top_n | integer | How many best passes to return. |
compare_reports
Diff two tester reports key by key (absolute and percent deltas), optionally checking guard thresholds. With `guards`, a profit-style metric below its threshold or a drawdown/loss metric above it is a violation. Accepting only improvements across many iterations is selection bias; treat guards as a sanity gate, not proof of robustness. Replaces regression_check.
| Parameter | Type | Description |
|---|---|---|
baseline * | string | Absolute path to the baseline tester report (.htm). |
candidate * | string | Absolute path to the candidate tester report (.htm). |
guards | Optional percent thresholds per summary key, e.g. {"net_profit": -5, "profit_factor": -10, "max_drawdown": 25}; when given, `violations` and `ok` are added. |
gen_tester_inputs
Generate a `[TesterInputs]` block from EA inputs. If `write_to` points at a tester.ini, the block is appended/replaced in-place.
| Parameter | Type | Description |
|---|---|---|
source * | string | Absolute Windows path to the .mq4/.mq5/.mqh source file. |
write_to | Optional tester.ini path; when given the [TesterInputs] block is written into it. |
validate_tester_ini
Sanity-check a tester.ini. If `source` given, cross-check inputs vs EA declarations.
| Parameter | Type | Description |
|---|---|---|
config * | string | Absolute path to the tester.ini file. |
source | Optional EA source; when given, [TesterInputs] keys are cross-checked against its input declarations. |
format_mql
Format an MQL file with clang-format (MQL literals such as D'…' and `input group` lines are protected). Default is a dry run reporting whether the file would change; pass `write=true` to apply. Replaces format_check.
| Parameter | Type | Description |
|---|---|---|
source * | string | Absolute Windows path to the .mq4/.mq5/.mqh source file. |
style | clang-format style string; defaults to an MQL-friendly LLVM-based profile. | |
write | boolean | false = report/diff only (default); true = overwrite the file in its original encoding. |
rename_symbol
Rename a symbol across MQL files (whole-word match). `dry_run=True` previews only.
| Parameter | Type | Description |
|---|---|---|
new * | string | New identifier. |
old * | string | Identifier to rename (whole-word match). |
root * | string | Absolute path to the project folder to scan recursively for MQL files. |
dry_run | boolean | true = preview the change and write nothing; false = apply it to the files. |
snapshot_sources
Freeze a copy of source files into a timestamped folder under `dest`.
| Parameter | Type | Description |
|---|---|---|
dest * | string | Absolute path to the folder that holds snapshots. |
sources * | array | Absolute paths of the source files to freeze. |
label | Folder name for this snapshot; defaults to a timestamp. |
list_snapshots
List all snapshot folders under `dest`.
| Parameter | Type | Description |
|---|---|---|
dest * | string | Absolute path to the folder that holds snapshots. |
select_terminal
Switch the active terminal data folder for this session. Provide one of: `origin` (install path stored in origin.txt), `hash` (32-char folder name), or `install` (auto-scan for the matching origin). Subsequent tool calls will use the new layout until the server restarts.
| Parameter | Type | Description |
|---|---|---|
edition | string | "mt5" or "mt4". |
hash | 32-character terminal data folder name under %APPDATA%\\MetaQuotes\\Terminal. | |
install | Install folder containing terminal64.exe; its data folder is found by scanning origin.txt files. | |
origin | Install path stored in the terminal's origin.txt, e.g. C:\\Program Files\\MetaTrader 5. |
smoke_test
One-call health check for an EA: compile, deploy, run a 1-day headless backtest, scan the journal. Catches problems that compile cleanly but fail at runtime (OnInit errors, array out of range, divide by zero). `ok` is true only if every stage passes; `stage` tells where it stopped. Overwrites the EA of the same name in Experts/. Takes 1-10 minutes.
| Parameter | Type | Description |
|---|---|---|
source * | string | Absolute Windows path to the .mq4/.mq5/.mqh source file. |
days | integer | Length of the backtest window in days (ends 2 days ago). |
expert_name | Name to use in Expert= of the generated ini; defaults to the binary's stem. | |
period | string | Timeframe code such as M15, H1, D1. |
symbol | string | Symbol name as shown in Market Watch, e.g. EURUSD. |
timeout_sec | integer | Give up after this many seconds. |
extract_function
Extract a contiguous block of lines into a new helper function. Brace-counting + regex param detection — not a full AST parser. Returns the proposed helper, call site, and parameter list. Set `dry_run=False` to write.
| Parameter | Type | Description |
|---|---|---|
line_end * | integer | Last line (1-based, inclusive) of the block to extract. |
line_start * | integer | First line (1-based, inclusive) of the block to extract. |
new_name * | string | Name of the new helper function. |
source * | string | Absolute Windows path to the .mq4/.mq5/.mqh source file. |
dry_run | boolean | true = preview the change and write nothing; false = apply it to the files. |
return_type | string | Return type of the helper, e.g. void or double. |
target_file | Optional .mqh path to append the helper to; defaults to inserting above the enclosing function. |
syntax_check
DEPRECATED (removed in 0.6.0): use compile(source, syntax_only=true).
| Parameter | Type | Description |
|---|---|---|
source * | string | Absolute Windows path to the .mq4/.mq5/.mqh source file. |
timeout_sec | integer | Give up after this many seconds. |
deploy_ea
DEPRECATED (removed in 0.6.0): use deploy(file, name).
| Parameter | Type | Description |
|---|---|---|
source_ex * | string | Absolute path to the compiled .ex4/.ex5 binary. |
name | File name to use inside Experts/. |
install_include
DEPRECATED (removed in 0.6.0): use deploy(file, name) with a .mqh file.
| Parameter | Type | Description |
|---|---|---|
source * | string | Absolute Windows path to the .mq4/.mq5/.mqh source file. |
target_name | File name to use inside Include/. |
extract_inputs
DEPRECATED (removed in 0.6.0): use inspect_source(source, aspects=["inputs"]).
| Parameter | Type | Description |
|---|---|---|
source * | string | Absolute Windows path to the .mq4/.mq5/.mqh source file. |
resolve_includes
DEPRECATED (removed in 0.6.0): use inspect_source(source, aspects=["includes"]).
| Parameter | Type | Description |
|---|---|---|
source * | string | Absolute Windows path to the .mq4/.mq5/.mqh source file. |
mql_root | MQL root for <angle> includes. |
extract_doc
DEPRECATED (removed in 0.6.0): use inspect_source(source, aspects=["docs"]).
| Parameter | Type | Description |
|---|---|---|
source * | string | Absolute Windows path to the .mq4/.mq5/.mqh source file. |
find_symbol
DEPRECATED (removed in 0.6.0): use inspect_source(root=..., symbol=...).
| Parameter | Type | Description |
|---|---|---|
root * | string | Absolute path to the project folder to scan recursively. |
symbol * | string | Identifier to search for. |
exts | File extensions to search. | |
limit | integer | Stop after this many matches. |
find_magic_collision
DEPRECATED (removed in 0.6.0): use inspect_source(root=..., aspects=["magic"]).
| Parameter | Type | Description |
|---|---|---|
root * | string | Absolute path to the project folder to scan recursively. |
var_pattern | string | Substring identifying magic-number variables. |
lint_basic
DEPRECATED (removed in 0.6.0): use analyze_mql(source, checks=["lint"]).
| Parameter | Type | Description |
|---|---|---|
source * | string | Absolute Windows path to the .mq4/.mq5/.mqh source file. |
check_deprecated
DEPRECATED (removed in 0.6.0): use analyze_mql(source, checks=["deprecated"]).
| Parameter | Type | Description |
|---|---|---|
source * | string | Absolute Windows path to the .mq4/.mq5/.mqh source file. |
code_metrics
DEPRECATED (removed in 0.6.0): use analyze_mql(source or root, checks=["metrics"]).
| Parameter | Type | Description |
|---|---|---|
root | Absolute folder to aggregate over. | |
source | Absolute path of one source file. |
format_check
DEPRECATED (removed in 0.6.0): use format_mql(source) (dry run by default).
| Parameter | Type | Description |
|---|---|---|
source * | string | Absolute Windows path to the .mq4/.mq5/.mqh source file. |
style | clang-format style string. |
parse_optimization
DEPRECATED (removed in 0.6.0): use read_optimization(...).
| Parameter | Type | Description |
|---|---|---|
expert | Expert name to select the cache. | |
path | Absolute path to a .opt cache. | |
period | Timeframe to select the cache. | |
sample | integer | Passes to include in passes_sample. |
symbol | Symbol to select the cache. |
top_passes
DEPRECATED (removed in 0.6.0): use read_optimization(criterion=..., top_n=...).
| Parameter | Type | Description |
|---|---|---|
criterion | string | Pass field to rank by. |
descending | boolean | true = highest first. |
expert | Expert name to select the cache. | |
n | integer | How many passes to return. |
opt_path | Absolute path to a .opt cache. | |
period | Timeframe to select the cache. | |
symbol | Symbol to select the cache. |
regression_check
DEPRECATED (removed in 0.6.0): use compare_reports(baseline, candidate, guards=...).
| Parameter | Type | Description |
|---|---|---|
baseline * | string | Absolute path to the baseline report. |
candidate * | string | Absolute path to the candidate report. |
guards | Percent thresholds per summary key. |
list_backtests
DEPRECATED (removed in 0.6.0): use get_backtest() without run_id.