@michaleffffff/mcp-trading-server
v2.9.9
Published
A production-ready MCP (Model Context Protocol) server that exposes tools, resources, and prompts for AI agents.
Downloads
2,368
Readme
MYX MCP Trading Server v2
A production-ready MCP (Model Context Protocol) server that exposes tools, resources, and prompts for AI agents.
This server allows AI assistants (like Claude Desktop, Cursor, etc.) to securely autonomously trade, manage liquidity, and fetch real-time market data on MYX Finance—a decentralized perpetual exchange. It interacts with smart contracts entirely via terminal/backend without requiring API keys or browser extensions.
Features
- MCP compliant server
- AI-friendly tool design (Unit normalization, Automated ID resolution)
- Structured input/output schemas for Web3 execution
- Resource browsing support (
system://state) - Prompt templates for trading decisions
- Modular architecture
- Logging and error handling
Architecture
The project follows a modular architecture separating tools from trading services.
AI Agents ↓ MCP Server ↓ Tools → Services → MYX SDK → Web3 RPC (EVM)
Project structure:
src/
server.ts
tools/ # MCP exposed operations (e.g. executeTrade, searchMarket)
resources/ # MCP contextual data (e.g. systemStateResource)
prompts/ # MCP reusable templates (e.g. tradeAnalysisPrompt)
services/ # Business logic calling the MYX SDK
auth/ # Web3 wallet & client resolution
utils/ # logger.ts, errors.ts, units.ts
schemas/
examples/
tests/Installation
quick-start npx @michaleffffff/mcp-trading-server
Configuration
Copy the example configuration:
cp .env.example .envNon-Auth Mode (No AccessToken)
This MCP server runs in non-auth mode:
- It does not call
myxClient.auth()and does not manage AccessTokens. - All tools are designed to work without AccessToken authentication.
User Key Configuration (Safe Practices)
- Local dev: Put
PRIVATE_KEYin a local.env(ignored by.gitignore) and never commit it. - Production: Inject via environment variables or a secrets manager, never store in code or repo.
- Best practice: Use a dedicated low‑fund wallet, avoid reusing your main wallet, and rotate regularly.
Environment variables needed for the trading wallet:
# BNB Smart Chain (BSC Mainnet) (Default)
PRIVATE_KEY=0xYourPrivateKey
RPC_URL=https://bsc-dataseed.bnbchain.org
CHAIN_ID=56
BROKER_ADDRESS=0xEb8C74fF05e76F85791dD2E4B972E7E78F6287C3
QUOTE_TOKEN_ADDRESS=0x55d398326f99059fF775485246999027B3197955
QUOTE_TOKEN_DECIMALS=18
IS_TESTNET=false
MAX_TRADE_AMOUNT=5000 # Optional safety constraint limit for AITestnet quick mapping:
Arbitrum Sepolia (421614):BROKER_ADDRESS=0x8f3153C18f698166f5D6124d8ba5B567F5f120f9,QUOTE_TOKEN_ADDRESS=0x7E248Ec1721639413A280d9E82e2862Cae2E6E28Linea Sepolia (59141):BROKER_ADDRESS=0x0FB08D3A1Ea6bE515fe78D3e0CaEb6990b468Cf3,QUOTE_TOKEN_ADDRESS=0xD984fd34f91F92DA0586e1bE82E262fF27DC431b
Running the Server
Build and Start the MCP server:
npm run build
npm run startThe server will run using stdio transport and can be connected by any MCP-compatible client.
Quick Start for Regular Users
- Prepare a wallet: Use a testnet or a small dedicated wallet (avoid your main wallet).
- Configure env: Copy
.env.exampleto.envand fill inPRIVATE_KEY,RPC_URL, etc. - Start the server: Run
npm run buildthennpm run start(usenpm run devfor development). - Configure your MCP client: Set
command/args/envin your MCP client (see Claude Desktop example below). - Common flow: Use
search_marketto getpoolId, then optionallyget_market_price/get_oracle_priceto view prices, and finally useopen_position_simple(recommended) to open a position.
Minimal open position example:
{
"keyword": "BTC",
"direction": 0,
"collateralAmount": "100",
"leverage": 5,
"orderType": "MARKET",
"autoDeposit": false
}Dry run (no transaction) example:
{
"keyword": "BTC",
"direction": 0,
"collateralAmount": "100",
"leverage": 5,
"orderType": "MARKET",
"autoDeposit": false,
"dryRun": true
}Units & Precision
- Human by default: For trading tools (e.g.
open_position_simple), amounts like"100"mean human-readable units. - Raw units (explicit): Prefix with
raw:to pass raw units exactly (e.g.raw:100000000for 100 USDC with 6 decimals). - Price:
"price"is human by default and will be converted to 30-decimal format internally. Useraw:to pass a 30-decimal integer directly. - Slippage:
slippagePctuses 4-decimal raw units:100=1%,50=0.5%,1000=10%. - Note: Some account-transfer tools (e.g.
account_deposit,account_withdraw,check_approval) use raw integer strings.
Secure Deployment Template (Systemd Example)
1) Put secrets in a system env file (chmod 600)
# /etc/myx-mcp.env
PRIVATE_KEY=0xYourPrivateKey
RPC_URL=https://bsc-dataseed.bnbchain.org
CHAIN_ID=56
BROKER_ADDRESS=0xEb8C74fF05e76F85791dD2E4B972E7E78F6287C3
QUOTE_TOKEN_ADDRESS=0x55d398326f99059fF775485246999027B3197955
QUOTE_TOKEN_DECIMALS=18
IS_TESTNET=falsesudo chmod 600 /etc/myx-mcp.env2) Systemd service
# /etc/systemd/system/myx-mcp.service
[Unit]
Description=MYX MCP Trading Server
After=network.target
[Service]
Type=simple
User=myx
Group=myx
WorkingDirectory=/opt/myx-mcp-trading-server-v2
EnvironmentFile=/etc/myx-mcp.env
ExecStart=/usr/bin/node /opt/myx-mcp-trading-server-v2/dist/server.js
Restart=on-failure
[Install]
WantedBy=multi-user.target3) Start
sudo systemctl daemon-reload
sudo systemctl enable --now myx-mcpConnecting Claude Desktop (MacOS)
Add to ~/Library/Application Support/Claude/claude_desktop_config.json:
{
"mcpServers": {
"myx-trading-v2": {
"command": "node",
"args": [
"[/Absolute/Path/To/Your/Directory]/myx-mcp-trading-server-v2/dist/server.js"
],
"env": {
"PRIVATE_KEY": "0xYourPrivateKey"
}
}
}
}Tools
The server exposes 38 tools categorized for AI:
Trading Operations
- open_position_simple: High-level open position helper (recommended). Computes price/size/tradingFee internally.
- execute_trade: Execute a new trade or add to an existing position.
- close_position: Close an open position.
- close_all_positions: Emergency: close ALL open positions in a pool at once.
- cancel_order: Cancel an open order by its order ID.
- cancel_all_orders: Cancel multiple open orders by order IDs (use
get_open_ordersfirst to get IDs). - set_tp_sl: Set take profit and stop loss prices for an open position.
- adjust_margin: Adjust the margin (collateral) of an open position.
- get_user_trading_fee_rate: Query current maker/taker fee rates by asset class and risk tier.
- get_network_fee: Query estimated network fee requirements for a market.
Market Data
- search_market: Search for an active market (e.g., "BTC") to retrieve its unique
poolId(Crucial prerequisite). - get_market_price: Get the current ticker market price for a specific pool.
- get_oracle_price: Get the current EVM oracle price for a specific pool.
- get_kline_latest_bar: Get only the latest bar for an interval.
- get_all_tickers: Get all ticker snapshots in one request.
- get_market_list, get_market_list_raw, get_kline, get_pool_info...
- get_pool_symbol_all, get_base_detail, get_pool_level_config...
Account & Portfolio
- get_positions: Get all open positions for the current account.
- get_balances: Get the account balances for different tokens.
- get_account_vip_info: Query account VIP tier details.
- position_history, open_orders...
Liquidity Provision (LP)
- manage_liquidity: Add or withdraw liquidity from a BASE or QUOTE pool.
- create_perp_market: Create a new perpetual trading pair.
Resources
Resources provide contextual data that AI agents can read.
Available resources:
system://state
Description: Readonly contextual data about the active EVM network, connected wallet address, chain ID, and RPC health available to the AI.
Prompts
Reusable prompt templates for AI tasks.
analyze_positions
Analyze the user's current trading positions based on real-time market action.
Arguments:
marketContext(string, optional) - Provide the latest market insights or news to contextualize the analysis.
Returns: Messages including a stringified dump of the user's active portfolio on MYX ready to be sent to an LLM for trading advice.
Example Usage
Example MCP client usage workflow:
- Connect to the MCP server.
- Read the
system://stateresource to confirm wallet connectivity. - Call the
search_markettool (e.g.,keyword: "ETH") to retrieve thepoolId. - Call
open_position_simplepassing the retrievedpoolIdto open a 10x long position.
Example integration scripts are located in:
examples/basicUsage.ts
Development
Run in development mode (watcher):
npm run devRun tests:
npm test
npm run test:new-toolsExtending the Server
To add a new tool:
- Create a new file in
src/tools/myNewTool.ts - Define the Zod input schema and description
- Implement the
handler(args)executing the trading logic - Export and register it in
src/tools/index.ts
Contributing
Contributions are welcome.
Please open an issue or submit a pull request.
