MCP Server Framework for MetaTrader 5. Build HTTP and stdio servers with automatic tool registration and MT5 socket communication
Project description
MCP Servers for MT5
Overview
mcp-mt5-conection is a Python library that bridges MetaTrader 5 (MT5) with the Model Context Protocol (MCP). It provides a simple and extensible framework to create tools that communicate between Python and MT5 via socket connections. Define your tools once in Python, and expose them through either FastMCP (for Claude and MCP clients) or HTTP (for custom integrations).
Main Features
Library Capabilities
- Simple Tool Registration: Use Python decorators to define MCP tools with minimal boilerplate
- Dual Protocol Support: Expose tools via FastMCP (for Claude) or HTTP API simultaneously
- Socket-Based Communication: Reliable TCP socket connection between Python and MT5 with JSON serialization
- Extensible Architecture: Abstract base classes allow custom implementations (MCP, HTTP, or custom protocols)
- MT5 Function Access: Call any MT5 function from Python through registered tools (trading, data, charts, etc.)
Repository Structure
McpServer/
├── Src/ # MQL5 Backend Functions
├── mcp_mt5_conection/ # Python MCP Server Package
└── Configuration & metadata files
Requirements
- Py requeriements and MQL5 Dependencies: dependencies.json
- McpServer requerid a EX5 Library, pucharse in: TheBotPlace - McpServerByLeo
Installation of repo code
cd "C:\Users\YOUR USER\AppData\Roaming\MetaQuotes\Terminal\YOUR ID\MQL5\Shared Projects"
tsndep install "https://forge.mql5.io/nique_372/McpServer.git"
- For use tsndep command requerid tsndep pacakage (avaible in pypi).. This command automatically downloads all dependencies and installs all requirements from the repositories.
- If any part of the system is private, then it will fail... contact me so I can give you access (if it's a product, you can buy it; if you have any questions, don't hesitate to contact me).
Quick Start (for final users)
1. Install Package
pip install mcp-mt5-conection
2. Create Configuration File
Create a JSON configuration file (e.g., mt5_mcp_config.json):
{
"general_config": {
"host": "localhost",
"port": 9999,
"mode": "fast_mcp"
},
"fast_mcp": {
"name": "MT5McpServer"
},
"http": {
"http_port": 8000,
"name": "MT5 HTTP Server",
"tools_namespace": "tools"
}
}
3. Create Your Server Script
Create a Python file with your custom tools (based on mcp_mt5_conection/server_template.py):
from mcp_mt5_conection import CMt5McpConection, CToolRegisterMCP
import json
from typing import Dict, Any
# Load configuration
config : dict = None
with open("mt5_mcp_config.json", "r") as f:
config = json.load(f)
# Initialize connection and server
mt5_conn = CMt5McpConection(
config["general_config"]["host"],
config["general_config"]["port"]
)
server = CToolRegisterMCP(config, mt5_conn)
# Register your custom tools using the decorator
@server.register_tool()
def open_trade(payload: Dict[str, Any]) -> str:
"""Open a new trade position"""
pass
# Run the server
if __name__ == "__main__":
server.run()
4. Part of MQL5
- Functions include
#include <TSN\\Mcp\\Main.mqh>
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
class CMcpFuncTradeTrade : public CMcpFunction
{
protected:
CTrade* m_trade;
public:
CMcpFuncTradeTrade(CTrade* tr)
: CMcpFunction(0, false, "open_trade"),
m_trade(tr)
{}
~CMcpFuncTradeTrade(void) {}
//---
void Run(CJsonNode& param, string& res) override final;
};
//+------------------------------------------------------------------+
void CMcpFuncTradeTrade::Run(CJsonNode& param, string& res)
{
::ResetLastError();
res = "";
m_trade.SetExpertMagicNumber(ulong(param["magic"].ToInt(0)));
const bool result = (param["type"].ToString("") == "buy")
? m_trade.Buy(param["lot_size"].ToDouble(0.00), param["symbol"].ToString(NULL), param["price"].ToDouble(0.000), param["sl"].ToDouble(0.000), param["tp"].ToDouble(0.0000), param["comment"].ToString(""))
: m_trade.Sell(param["lot_size"].ToDouble(0.00), param["symbol"].ToString(NULL), param["price"].ToDouble(0.000), param["sl"].ToDouble(0.000), param["tp"].ToDouble(0.0000), param["comment"].ToString(""));
if(!result)
res = StringFormat("{\"ok\":false,\"error\":\"trade_failed, last mt5 error = %d\"}", ::GetLastError());
else
res = StringFormat("{\"ok\":true,\"result\":%lu}", m_trade.ResultOrder());
}
- Main EA
#include "Functions.mqh"
//+------------------------------------------------------------------+
//| Inputs |
//+------------------------------------------------------------------+
input string InpSoketAdres = "127.0.0.1";
input uint InpSoketPort = 9999;
input int InpMsPool = 100;
input int InpMsTimeoutReadNoTls = 10000;
//+------------------------------------------------------------------+
//| Global variables |
//+------------------------------------------------------------------+
IMcpBase* g_mcp_server;
CTrade g_trade;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//---
#ifdef TSN_MCPSERVER_FUNC_CTS
g_mcp_server = TSN_MCPSERVER_FUNC_CTS(THE_BOT_PLACE_USER_ID);
#else
g_mcp_server = McpServerByLeo_Create(THE_BOT_PLACE_USER_ID);
#endif // TSN_MCPSERVER_FUNC_CTS
//---
::EventSetMillisecondTimer(InpMsPool);
g_mcp_server.AddLogFlags(LOG_ALL);
//--- Graphics / Objects
g_mcp_server.AddItemFast(new CMcpFuncObjectCreate());
g_mcp_server.AddItemFast(new CMcpFuncObjectCreate());
//---
g_mcp_server.Set(InpMsPool, InpMsTimeoutReadNoTls);
if(!g_mcp_server.Conectar(InpSoketAdres, InpSoketPort, (10 * 1000))) // 10 segundos de espera para conectarse
return INIT_FAILED;
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//---
if(CheckPointer(g_mcp_server) == POINTER_DYNAMIC)
delete g_mcp_server;
//---
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
//---
}
//+------------------------------------------------------------------+
//| Timer function |
//+------------------------------------------------------------------+
void OnTimer(void)
{
g_mcp_server.TimerEvent();
}
//+------------------------------------------------------------------+
5. Configure MetaTrader 5
In MT5: Tools → Options → Allowed URLs for WebRequest
- Add
127.0.0.1(or your configured host) - Enable AutoTrading and DLL imports
6. Run Server and Connect EA
- Start your Python server:
python your_server.py --config mt5_mcp_config.json - In MetaTrader 5, compile and attach the McpServer EA to your chart
- Configure EA parameters to match your host/port settings
7. Use in Claude Desktop
Add to your claude_desktop_config.json:
{
"mcpServers": {
"mt5_mcp": {
"command": "python",
"args": ["your_server.py", "--config", "mt5_mcp_config.json"]
}
}
}
Now you can use Claude to interact with MT5 through natural language.
License
By downloading or using this repository, you accept the license terms.
Documentation
Contact
- Platform: MQL5 Community
- Profile: https://www.mql5.com/es/users/nique_372/news
Copyright © 2026 Niquel Mendoza (nique_372).
TSN Trading Systems ecosystem.
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file mcp_mt5_conection-1.0.1.tar.gz.
File metadata
- Download URL: mcp_mt5_conection-1.0.1.tar.gz
- Upload date:
- Size: 9.9 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.10.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
0ac43eac30ea774a09b49b04e5e70e15549b9a9c3aaa5e50d7cd8f92fbf1abbc
|
|
| MD5 |
97496fdaadc699b6277ad336fa750b3b
|
|
| BLAKE2b-256 |
1066847270c780311bfa8061089bbcc465567d091b4340811bf7bdc85df9005e
|
File details
Details for the file mcp_mt5_conection-1.0.1-py3-none-any.whl.
File metadata
- Download URL: mcp_mt5_conection-1.0.1-py3-none-any.whl
- Upload date:
- Size: 10.6 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.10.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
d095e144f3823033811be334ec2a0130641c7ab137883529e18de354ff30de68
|
|
| MD5 |
93e3e2018d6aae5fc7527d07d8d1aee5
|
|
| BLAKE2b-256 |
f7466e3344f7447a6abd79dfe35756aa3f130ee467c5cfd6e46adcb2d0d2a57a
|