Skip to main content

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


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:
    """
"description": "Abre una posición de mercado (compra/venta) a precio actual",
"inputSchema": {
  "type": "object",
  "properties": {
    "type": {
      "type": "string",
      "description": "Tipo de operación | string:buy|sell | buy, sell | requerido"
    },
    "symbol": {
      "type": "string",
      "description": "Símbolo de trading | string | EURUSD, XAUUSD | requerido"
    },
    "lot_size": {
      "type": "number",
      "description": "Volumen de la posición | double:0+ | 0.01, 0.1, 1.0 | requerido"
    },
    "price": {
      "type": "number",
      "description": "Precio de entrada (Ask para compras, Bid para ventas) | double:precio | 1.0850 | requerido"
    },
    "sl": {
      "type": "number",
      "description": "Stop Loss | double:precio | 1.0800 | 0.0"
    },
    "tp": {
      "type": "number",
      "description": "Take Profit | double:precio | 1.0900 | 0.0"
    },
    "magic": {
      "type": "integer",
      "description": "Número mágico para identificar órdenes | int:0+ | 12345 | 0"
    },
    "comment": {
      "type": "string",
      "description": "Comentario de la operación | string | Long bias signal | vacío"
    }
  },
  "required": ["type", "symbol", "lot_size", "price"]
}  
    """
    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: ToolsOptionsAllowed 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

Read Full License

By downloading or using this repository, you accept the license terms.


Documentation


Contact


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

mcp_mt5_conection-1.0.2.tar.gz (10.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

mcp_mt5_conection-1.0.2-py3-none-any.whl (11.2 kB view details)

Uploaded Python 3

File details

Details for the file mcp_mt5_conection-1.0.2.tar.gz.

File metadata

  • Download URL: mcp_mt5_conection-1.0.2.tar.gz
  • Upload date:
  • Size: 10.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.10.9

File hashes

Hashes for mcp_mt5_conection-1.0.2.tar.gz
Algorithm Hash digest
SHA256 0b7d59e24e43584c31b9b6af7875a987e3156fb8f2943d41d101a517a2caf498
MD5 1abc19fcd47b0cbc2ca6d2dd2602bcc6
BLAKE2b-256 f96554fc18e3630d71fa2d57c8ac4ac7baa26e32eb4e5576be53bef2d25c55cf

See more details on using hashes here.

File details

Details for the file mcp_mt5_conection-1.0.2-py3-none-any.whl.

File metadata

File hashes

Hashes for mcp_mt5_conection-1.0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 91acf04b769ae86d89ba38715e1bb6399e9991fbb22617d82d037ed07e86ffd5
MD5 35a8565909b0b81198fb61ba87855782
BLAKE2b-256 27c6f1c6773a0db5c05e2d230a889236f34a94306ff2d14ac933717abae569e2

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page