# MCP MT4 Connector - Architecture **Version:** 0.1.0 **Date:** 2026-01-04 **System:** Trading Platform --- ## Overview The MCP MT4 Connector is a Model Context Protocol (MCP) server that exposes MetaTrader 4 trading capabilities as tools that AI agents can use. It acts as a bridge between MCP-compatible AI systems (like Claude) and the MT4 trading terminal. --- ## Architecture Diagram ``` ┌─────────────────────────────────────────────────────────────────────────┐ │ AI Agent (Claude) │ │ │ │ "Execute a buy order for 0.1 lots of XAUUSD with SL at 2640" │ └─────────────────────────────────────┬───────────────────────────────────┘ │ MCP Protocol ▼ ┌─────────────────────────────────────────────────────────────────────────┐ │ MCP MT4 Connector (Port 3605) │ │ │ │ ┌─────────────────────────────────────────────────────────────────┐ │ │ │ Express Server │ │ │ │ │ │ │ │ /health - Health check endpoint │ │ │ │ /tools - List available tools │ │ │ │ /tools/:name - Execute specific tool │ │ │ │ /mcp/* - MCP protocol endpoints │ │ │ └─────────────────────────────────────────────────────────────────┘ │ │ │ │ │ ┌─────────────────────────────────────────────────────────────────┐ │ │ │ Tool Handlers │ │ │ │ │ │ │ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌───────────┐ │ │ │ │ │ account.ts │ │positions.ts │ │ trading.ts │ │ quotes.ts │ │ │ │ │ └─────────────┘ └─────────────┘ └─────────────┘ └───────────┘ │ │ │ └─────────────────────────────────────────────────────────────────┘ │ │ │ │ │ ┌─────────────────────────────────────────────────────────────────┐ │ │ │ MT4 Client Service │ │ │ │ │ │ │ │ - HTTP client wrapper for mt4-gateway │ │ │ │ - Request/response handling │ │ │ │ - Error management │ │ │ └─────────────────────────────────────────────────────────────────┘ │ └─────────────────────────────────────┬───────────────────────────────────┘ │ HTTP/REST ▼ ┌─────────────────────────────────────────────────────────────────────────┐ │ MT4 Gateway (Port 8081) │ │ │ │ Python service that communicates with MT4 EA Bridge │ └─────────────────────────────────────┬───────────────────────────────────┘ │ Local Socket/HTTP ▼ ┌─────────────────────────────────────────────────────────────────────────┐ │ MT4 Terminal + EA Bridge │ │ │ │ Windows MT4 with Expert Advisor running │ └─────────────────────────────────────────────────────────────────────────┘ ``` --- ## Component Details ### 1. Express Server (`src/index.ts`) The main entry point that: - Hosts the MCP server on port 3605 - Provides REST endpoints for tool execution - Implements MCP protocol endpoints - Handles health checks and service discovery **Endpoints:** | Endpoint | Method | Description | |----------|--------|-------------| | `/health` | GET | Health check with MT4 connection status | | `/tools` | GET | List all available MCP tools | | `/tools/:name` | GET | Get specific tool schema | | `/tools/:name` | POST | Execute tool with parameters | | `/mcp/initialize` | POST | MCP initialization handshake | | `/mcp/tools/list` | POST | MCP tool listing | | `/mcp/tools/call` | POST | MCP tool execution | ### 2. Tool Handlers (`src/tools/`) Individual tool implementations following the MCP tool pattern: | File | Tools | Description | |------|-------|-------------| | `account.ts` | `mt4_get_account` | Account information retrieval | | `positions.ts` | `mt4_get_positions`, `mt4_close_position` | Position management | | `trading.ts` | `mt4_execute_trade`, `mt4_modify_position` | Trade execution | | `quotes.ts` | `mt4_get_quote` | Price data retrieval | Each tool handler: - Defines Zod validation schemas - Implements the core logic - Formats responses for MCP protocol - Handles errors gracefully ### 3. MT4 Client Service (`src/services/mt4-client.ts`) HTTP client wrapper that: - Manages connection to mt4-gateway - Handles authentication (Bearer token) - Provides typed interfaces for all operations - Manages request timeouts and retries --- ## Data Flow ### Example: Execute Trade ``` 1. Agent Request POST /mcp/tools/call { "name": "mt4_execute_trade", "arguments": { "symbol": "XAUUSD", "action": "buy", "lots": 0.1, "stopLoss": 2640, "takeProfit": 2680 } } 2. Tool Handler (trading.ts) - Validates input with Zod schema - Checks MT4 connection status - Validates SL/TP logic - Calls MT4Client.executeTrade() 3. MT4 Client Service - Formats request payload - Sends HTTP POST to mt4-gateway - Receives and parses response 4. MT4 Gateway - Forwards to EA Bridge - EA executes trade on MT4 - Returns result 5. Response to Agent { "content": [{ "type": "text", "text": "Trade Executed Successfully\n..." }] } ``` --- ## Configuration ### Environment Variables | Variable | Default | Description | |----------|---------|-------------| | `PORT` | 3605 | MCP server port | | `MT4_GATEWAY_HOST` | localhost | MT4 Gateway host | | `MT4_GATEWAY_PORT` | 8081 | MT4 Gateway port | | `MT4_GATEWAY_AUTH_TOKEN` | secret | Authentication token | | `REQUEST_TIMEOUT` | 10000 | Request timeout (ms) | | `LOG_LEVEL` | info | Logging level | --- ## Error Handling ### Error Types 1. **Connection Errors** - MT4 Gateway unreachable - MT4 Terminal disconnected 2. **Validation Errors** - Invalid parameters (Zod) - Invalid SL/TP configuration 3. **Trading Errors** - Insufficient margin - Market closed - Invalid symbol ### Error Response Format ```json { "success": false, "error": "Error message description" } ``` --- ## Security Considerations 1. **Authentication** - Bearer token for mt4-gateway communication - No external network exposure by default 2. **Validation** - All inputs validated with Zod schemas - Type-safe throughout the codebase 3. **Rate Limiting** - Consider adding rate limiting for production - Respect MT4 order frequency limits --- ## Dependencies | Package | Purpose | |---------|---------| | `express` | HTTP server | | `axios` | HTTP client | | `zod` | Input validation | | `dotenv` | Environment configuration | | `@modelcontextprotocol/sdk` | MCP protocol types | --- ## Deployment ### Development ```bash npm install cp .env.example .env # Edit .env with your configuration npm run dev ``` ### Production ```bash npm run build npm start ``` ### Docker (Future) ```dockerfile FROM node:20-alpine WORKDIR /app COPY package*.json ./ RUN npm ci --only=production COPY dist ./dist EXPOSE 3605 CMD ["node", "dist/index.js"] ``` --- ## References - MCP Protocol: https://modelcontextprotocol.io - MT4 Bridge Client: `apps/mt4-gateway/src/providers/mt4_bridge_client.py` - Trading Platform: `projects/trading-platform/` - SIMCO-MCP Directive: `orchestration/directivas/simco/SIMCO-MCP.md`