mcp-mt5
This server provides an offline MetaTrader 4/5 development harness for LLM agents, enabling compile, deploy, backtest, analysis, and log inspection without touching the UI or trading live.
Discovery & terminal selection:
env_info,list_terminals,select_terminalBuild & deploy: compile, compile_and_deploy, deploy (EA/Include), smoke_test, list_experts
Source analysis & lint: inspect_source (inputs, includes, docs, symbols, magic collisions), analyze_mql (structural lint, deprecated calls, metrics), validate_tester_ini
Format & refactor: format_mql, rename_symbol, extract_function
Strategy Tester: patch_tester_ini, gen_tester_inputs, run_backtest (foreground), start/get/cancel_backtest (background), read_tester_report, compare_reports, read_optimization, kill_terminal
Logs & snapshots: tail_log (live/journal/tester), snapshot_sources, list_snapshots
MCP resources:
mt5://log/{mode}andmt5://report/{id}for raw log/report access
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@mcp-mt5 compile and deploy the moving average EA"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
mcp-mt5
Model Context Protocol server for the MetaTrader 4/5 build pipeline. Compile MQL sources, deploy compiled EAs, run Strategy Tester, parse reports, tail logs — all driven by an LLM agent without touching the MetaTrader UI.
What this is — and what it isn't
✅ This server | ❌ Not this server |
MetaTrader dev harness — compile, deploy, backtest, parse | Live trading (orders, positions, quotes) |
Wraps | Wraps the |
Runs entirely offline against installed terminal | Connects to a broker server |
Iterates strategies before they go live | Executes strategies in production |
Use case: an LLM agent edits
.mq5source → compiles → deploys → runs Strategy Tester → reads report → adjusts → repeats. No broker login, no human in the loop, no risk of real-money execution.
For runtime trading, pair this with a live-trading MCP — they target different layers and compose well.
Related MCP server: Meta-Trader-MCP
Tools
27 tools (plus 16 deprecated aliases until 0.6.0) and 2 resource templates. Every tool carries MCP annotations (read-only / destructive hints), a typed output schema and per-parameter descriptions; failures are reported as tool errors, never as a normal result with an error key.
🔍 Discovery & terminal selection
Tool | Description |
| Resolved paths, terminal hash, edition, and missing-component issues |
| Every MT4/5 terminal data folder under |
| Switch the active terminal data folder mid-session by origin path, hash, or install dir |
🔨 Build & deploy
Tool | Description |
| MetaEditor CLI on a |
| Compile, then copy the fresh |
| Copy a compiled binary into |
| Compile + deploy + 1-day headless backtest + journal scan for runtime errors |
| Enumerate |
🔎 Source analysis & lint
Tool | Description |
|
|
| Structural lint (missing |
| Required keys, date format, numeric ranges; cross-checks |
✏️ Format & refactor
Tool | Description |
|
|
| Whole-word rename across a tree, |
| Brace-aware extraction of a line range into a helper (inline or into a |
📊 Strategy Tester
Tool | Description |
| Update |
| Build a |
| Launch |
| Background runs: launch and get a |
| Parse an MT5/MT4 report into a ~50-field |
| Diff two reports key by key with absolute/percent deltas; pass |
| Read a |
| Kill terminals launched by this server ( |
📝 Logs & snapshots
Tool | Description |
| Tail |
| Freeze source files into a timestamped folder with a |
📡 MCP resources
URI | Description |
| Last 500 lines of |
| Full HTML of a report returned by |
Deprecated aliases (removed in 0.6.0)
The pre-0.5.0 tool names still work in 0.5.x as thin wrappers whose descriptions start with DEPRECATED. Set MCP_MT5_LEGACY_TOOLS=0 to hide them and shrink the tool catalogue to the 27 tools above.
Deprecated name | Use instead |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Quick start
Install
pip install mcp-mt5Requires Windows + an installed MetaTrader 4 or 5 terminal.
Register with an MCP client
Most MCP clients accept a JSON entry under mcpServers. The server inherits its configuration from environment variables:
{
"mcpServers": {
"mt5": {
"command": "mcp-mt5",
"env": {
"MT5_INSTALL": "C:\\Program Files\\MetaTrader 5"
}
}
}
}Refer to your client's documentation for the exact config file location.
Verify the install
Once registered, ask your agent to call env_info:
{
"edition": "mt5",
"install": "C:\\Program Files\\MetaTrader 5",
"terminal_hash": "<32-char-hex-hash>",
"metaeditor": "C:\\Program Files\\MetaTrader 5\\MetaEditor64.exe",
"experts_dir": "C:\\Users\\<you>\\AppData\\Roaming\\MetaQuotes\\Terminal\\<hash>\\MQL5\\Experts",
"issues": []
}An empty issues array means everything is wired up correctly.
Configuration
Resolution priority for the MetaTrader install + data folder:
Explicit env vars (below)
Auto-scan of
%APPDATA%\MetaQuotes\Terminal\*\origin.txtfor a folder whose origin matchesMT5_INSTALLPortable mode fallback (data colocated with install dir)
Env var | Default | Notes |
|
| Install dir containing |
| (auto-detected) |
|
| (auto-detected) | 32-char folder name |
|
| Set to |
Running the server from WSL
The server can run inside WSL and drive the Windows MetaTrader install through WSL interop.
The install (/mnt/c/Program Files/MetaTrader 5) and the data folder (scanned under
/mnt/*/Users/*/AppData/Roaming/MetaQuotes/Terminal, matched through origin.txt) are
auto-detected; MT5_INSTALL / MT5_DATA override them. Paths handed to MetaEditor/terminal are
translated with wslpath -w automatically. Interop must be enabled
(/etc/wsl.conf [interop] enabled=true, then wsl --shutdown).
MT4 support
Set MT5_EDITION=mt4 and point MT5_INSTALL at your MT4 install. The server switches to metaeditor.exe (32-bit), terminal.exe, and the MQL4/ data tree automatically.
Example workflow
A typical LLM-driven iteration loop:
1. env_info → verify paths
2. compile_and_deploy source="C:\\...\\MyEA.mq5" → 0 errors, .ex5 deployed ✅
3. patch_tester_ini config="tester.ini" updates={
"Tester.Symbol": "EURUSD",
"Tester.FromDate": "2025.01.01",
"TesterInputs.RiskPct": "1.5"
}
4. run_backtest config="tester.ini" wait=true
5. read_tester_report path=<report_path from step 4> → summary.net_profit = 1234.56
summary.profit_factor = 1.45
6. tail_log mode="tester" lines=200 structured=true → diagnose journal warnings
7. <edit Signal.mqh based on findings>
8. → loop back to step 2A sample tester.ini
; Launch: terminal64.exe /config:tester.ini
; Period codes: M1=1, M5=5, M15=15, H1=16385, H4=16388, D1=16408
; Model: 0=Every tick, 1=1 min OHLC, 4=Real ticks
[Tester]
Expert=MyEA
Symbol=EURUSD
Period=M15
Model=1
FromDate=2024.01.01
ToDate=2024.12.31
Deposit=10000
Currency=USD
Leverage=500
Visual=0
ShutdownTerminal=1 ; required so run_backtest can wait for the run to finish
Report=tester_report
[TesterInputs]
; ParamName=value||start||step||stop||(N=fixed|Y=optimize)
; RiskPct=1.0||0.1||0.1||3.0||NA more complete sample lives at examples/tester.ini.
Development
git clone https://github.com/PHUICMT/mcp-mt5
cd mcp-mt5
pip install -e ".[dev]"
pytest # runs the test suite (no MetaTrader needed)
ruff check src tests # lintsCI runs on Windows for Python 3.10, 3.11, and 3.12 against every push to main. Tagging a release (e.g. v0.2.0) triggers an OIDC publish to PyPI.
Project layout
mcp-mt5/
├── src/mcp_mt5/
│ ├── server.py # FastMCP tool definitions
│ ├── paths.py # Layout detection + origin.txt scan
│ ├── parsers.py # Compile log, tester report/journal parsers, encoding helpers
│ ├── analysis.py, lint.py, formatting.py, refactor.py, ast_refactor.py
│ ├── optimization.py # .opt cache reader (documented TesterOptCache layout)
│ ├── reports.py, snapshot.py, smoke.py, workdir.py
├── tests/ # pytest suite, no live MT5 required
├── examples/ # Sample tester.ini + client config
└── .github/workflows/ # CI + PyPI releaseLimitations
Windows-only. MetaTrader CLI binaries don't ship for Linux/macOS. Wine ports may work but are untested.
No live broker access. This server intentionally never authenticates to a broker. Use a separate MCP server for runtime trading.
Tester report parsing is best-effort. MetaTrader's HTML output isn't a stable schema; the raw HTML is also returned alongside the parsed structure so you can fall back to text inspection when needed.
Optimisation caches (
Tester/cache/*.opt) are parsed with the layout MetaQuotes published in MQL5 Programming for Traders. Files with an unrecognised record layout are reported as such rather than guessed.
Roadmap
All v0.3.x roadmap items shipped in v0.4.0. Future ideas:
Real tree-sitter MQL grammar for
extract_function(current implementation is brace-counting + regex)WebSocket transport for long-lived sessions (currently stdio only)
Linux/Wine port for non-Windows agents
License
MIT © 2026 PHUICMT
Available Tools
43 toolsanalyze_mqlARead-onlyIdempotent
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.
Inputs: root, checks, source. Returns: object
cancel_backtestADestructive
Kill the terminal of a running background backtest. No report is produced for a cancelled run.
Inputs: run_id (required). Returns: object
check_deprecatedARead-onlyIdempotent
DEPRECATED (removed in 0.6.0): use analyze_mql(source, checks=["deprecated"]).
Inputs: source (required). Returns: object
code_metricsARead-onlyIdempotent
DEPRECATED (removed in 0.6.0): use analyze_mql(source or root, checks=["metrics"]).
Inputs: root, source. Returns: object
compare_reportsARead-onlyIdempotent
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.
Inputs: baseline (required), candidate (required), guards. Returns: object
compileA
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.
Inputs: source (required), include, log_file, syntax_only, +1 more. Returns: object
compile_and_deployADestructive
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).
Inputs: source (required), ea_name. Returns: object
deployADestructive
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.
Inputs: file (required), name. Returns: object
deploy_eaADestructive
DEPRECATED (removed in 0.6.0): use deploy(file, name).
Inputs: source_ex (required), name. Returns: object
env_infoARead-onlyIdempotent
Resolve and report MT4/5 paths, terminal hash, and missing-component issues.
Inputs: no named parameters. Returns: object
extract_docARead-onlyIdempotent
DEPRECATED (removed in 0.6.0): use inspect_source(source, aspects=["docs"]).
Inputs: source (required). Returns: object
extract_functionADestructive
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.
Inputs: source (required), line_end (required), new_name (required), line_start (required), +3 more. Returns: object
extract_inputsARead-onlyIdempotent
DEPRECATED (removed in 0.6.0): use inspect_source(source, aspects=["inputs"]).
Inputs: source (required). Returns: object
find_magic_collisionARead-onlyIdempotent
DEPRECATED (removed in 0.6.0): use inspect_source(root=..., aspects=["magic"]).
Inputs: root (required), var_pattern. Returns: object
find_symbolARead-onlyIdempotent
DEPRECATED (removed in 0.6.0): use inspect_source(root=..., symbol=...).
Inputs: root (required), symbol (required), exts, limit. Returns: object
format_checkARead-onlyIdempotent
DEPRECATED (removed in 0.6.0): use format_mql(source) (dry run by default).
Inputs: source (required), style. Returns: object
format_mqlADestructive
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.
Inputs: source (required), style, write. Returns: object
gen_tester_inputsADestructive
Generate a [TesterInputs] block from EA inputs.
If write_to points at a tester.ini, the block is appended/replaced in-place.
Inputs: source (required), write_to. Returns: object
get_backtestARead-onlyIdempotent
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.
Inputs: run_id, tail_lines. Returns: object
inspect_sourceARead-onlyIdempotent
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.
Inputs: root, limit, source, symbol, +3 more. Returns: object
install_includeADestructive
DEPRECATED (removed in 0.6.0): use deploy(file, name) with a .mqh file.
Inputs: source (required), target_name. Returns: object
kill_terminalADestructive
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).
Inputs: all_instances. Returns: object
lint_basicARead-onlyIdempotent
DEPRECATED (removed in 0.6.0): use analyze_mql(source, checks=["lint"]).
Inputs: source (required). Returns: object
list_backtestsARead-onlyIdempotent
DEPRECATED (removed in 0.6.0): use get_backtest() without run_id.
Inputs: no named parameters. Returns: object
list_expertsARead-onlyIdempotent
List compiled EAs in Experts/ (defaults to *.ex5 for MT5, *.ex4 for MT4).
Inputs: pattern, recurse. Returns: object
list_snapshotsARead-onlyIdempotent
List all snapshot folders under dest.
Inputs: dest (required). Returns: object
list_terminalsARead-onlyIdempotent
Enumerate all MetaTrader terminal data folders under %APPDATA%\MetaQuotes\Terminal.
Inputs: no named parameters. Returns: object
parse_optimizationDRead-onlyIdempotent
DEPRECATED (removed in 0.6.0): use read_optimization(...).
Inputs: path, expert, period, sample, +1 more. Returns: object
patch_tester_iniADestructive
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.
Inputs: config (required), updates (required). Returns: object
read_optimizationARead-onlyIdempotent
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.
Inputs: path, top_n, expert, period, +3 more. Returns: object
read_tester_reportARead-onlyIdempotent
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.
Inputs: path, max_trades, raw_truncate, response_format. Returns: object
regression_checkARead-onlyIdempotent
DEPRECATED (removed in 0.6.0): use compare_reports(baseline, candidate, guards=...).
Inputs: baseline (required), candidate (required), guards. Returns: object
rename_symbolADestructive
Rename a symbol across MQL files (whole-word match). dry_run=True previews only.
Inputs: new (required), old (required), root (required), dry_run. Returns: object
resolve_includesCRead-onlyIdempotent
DEPRECATED (removed in 0.6.0): use inspect_source(source, aspects=["includes"]).
Inputs: source (required), mql_root. Returns: object
run_backtestA
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 the ini), latest_tester_log and journal_notes/warnings;
if warnings mentions start_time_changed the tester moved FromDate because history was
missing, so the report is not comparable with other runs.
Inputs: config (required), wait, portable, timeout_sec. Returns: object
select_terminalA
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.
Inputs: hash, origin, edition, install. Returns: object
smoke_testADestructive
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.
Inputs: source (required), days, period, symbol, +2 more. Returns: object
snapshot_sourcesAIdempotent
Freeze a copy of source files into a timestamped folder under dest.
Inputs: dest (required), sources (required), label. Returns: object
start_backtestA
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.
Inputs: config (required), portable, timeout_sec. Returns: object
syntax_checkA
DEPRECATED (removed in 0.6.0): use compile(source, syntax_only=true).
Inputs: source (required), timeout_sec. Returns: object
tail_logARead-onlyIdempotent
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.
Inputs: date, mode, lines, structured. Returns: object
top_passesARead-onlyIdempotent
DEPRECATED (removed in 0.6.0): use read_optimization(criterion=..., top_n=...).
Inputs: n, expert, period, symbol, +3 more. Returns: object
validate_tester_iniARead-onlyIdempotent
Sanity-check a tester.ini. If source given, cross-check inputs vs EA declarations.
Inputs: config (required), source. Returns: object
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 43 tools
The active tools are mostly distinct, but the 16 deprecated aliases duplicate the same operations as active tools (e.g., extract_inputs vs inspect_source, parse_optimization vs read_optimization), creating confusion. Some overlap also exists between compile/compile_and_deploy/deploy and run_backtest/start_backtest/smoke_test, though descriptions help clarify boundaries.
Most tool names follow a clear verb_noun pattern (list_snapshots, run_backtest, read_tester_report, validate_tester_ini). Minor deviations like env_info, compile_and_deploy, and smoke_test are understandable exceptions, and deprecated names also generally follow similar conventions.
With 43 tools, the surface is far too large, even though 16 are deprecated. The active count of 27 is still heavy, and several active tools are composites (compile_and_deploy, smoke_test) that could be consolidated without losing capability.
The server covers the major MT5 automation lifecycle: terminal selection, compile/deploy, backtest launch and monitoring, report parsing, source inspection, static analysis, formatting, optimization reading, and snapshots. Minor gaps exist (no explicit tester.ini creation tool, no undeploy/removal tool), but workflows do not hit dead ends.
Maintenance
Related MCP Connectors
Hosted MCP server for MT4 and MT5: read accounts, prices and candles, and place or close orders.
MCP server exposing the Backtest360 engine API as tools for AI agents.
MCP server for OpenMM — exposes market data, account, trading, and strategy tools to AI agents
A comprehensive Model Context Protocol (MCP) server that enables AI assistants to interact with yo…
Related MCP Servers
- FlicenseNot gradedqualityDmaintenanceA standalone Model Context Protocol (MCP) server that enables AI assistants to interact with the cTrader trading platform.15-
- AlicenseNot gradedqualityAmaintenanceExposes a unified AI interface to MetaTrader 5 over the Model Context Protocol, enabling live quotes, historical data, technical indicators, order execution, position management, and headless backtests.134 PyPIMIT
- AlicenseNot gradedqualityCmaintenanceA local-first MCP server that bridges AI coding agents with MetaTrader 5 for inspection, market data, MQL5 development, compiling, Strategy Tester review, workspace sync, logs, audit trails, demo trading, and carefully gated live trading.MIT
- FlicenseNot gradedqualityDmaintenanceUniversal MCP server that enables AI assistants to control MetaTrader 5 directly, executing trades, managing data, and automating MT5 operations through natural language.4-