@michaleffffff/mcp-trading-server 3.0.4 → 3.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/CHANGELOG.md +42 -6
  2. package/README.md +49 -414
  3. package/TOOL_EXAMPLES.md +63 -559
  4. package/dist/auth/resolveClient.js +19 -2
  5. package/dist/prompts/tradingGuide.js +16 -23
  6. package/dist/server.js +20 -2
  7. package/dist/services/balanceService.js +4 -4
  8. package/dist/services/marketService.js +48 -12
  9. package/dist/services/poolService.js +45 -44
  10. package/dist/services/tradeService.js +51 -23
  11. package/dist/tools/accountInfo.js +5 -134
  12. package/dist/tools/accountTransfer.js +7 -12
  13. package/dist/tools/adjustMargin.js +1 -1
  14. package/dist/tools/cancelOrders.js +71 -0
  15. package/dist/tools/checkAccountReady.js +75 -0
  16. package/dist/tools/checkApproval.js +1 -1
  17. package/dist/tools/closeAllPositions.js +9 -7
  18. package/dist/tools/closePosition.js +18 -11
  19. package/dist/tools/createPerpMarket.js +1 -1
  20. package/dist/tools/executeTrade.js +6 -6
  21. package/dist/tools/findPool.js +26 -0
  22. package/dist/tools/getAccountSnapshot.js +47 -0
  23. package/dist/tools/getAllTickers.js +5 -4
  24. package/dist/tools/getBaseDetail.js +1 -1
  25. package/dist/tools/getKline.js +7 -4
  26. package/dist/tools/getMyLpHoldings.js +3 -2
  27. package/dist/tools/getNetworkFee.js +1 -1
  28. package/dist/tools/getOrders.js +46 -0
  29. package/dist/tools/getPoolMetadata.js +95 -0
  30. package/dist/tools/getPositionsAll.js +80 -0
  31. package/dist/tools/{getMarketPrice.js → getPrice.js} +8 -5
  32. package/dist/tools/getUserTradingFeeRate.js +66 -3
  33. package/dist/tools/index.js +15 -19
  34. package/dist/tools/listPools.js +53 -0
  35. package/dist/tools/manageLiquidity.js +4 -4
  36. package/dist/tools/manageTpSl.js +234 -0
  37. package/dist/tools/openPositionSimple.js +27 -8
  38. package/dist/tools/searchTools.js +35 -0
  39. package/dist/utils/mappings.js +10 -7
  40. package/package.json +2 -2
  41. package/dist/tools/cancelAllOrders.js +0 -57
  42. package/dist/tools/cancelOrder.js +0 -22
  43. package/dist/tools/getAccountVipInfo.js +0 -20
  44. package/dist/tools/getKlineLatestBar.js +0 -28
  45. package/dist/tools/getOraclePrice.js +0 -22
  46. package/dist/tools/getPoolList.js +0 -17
  47. package/dist/tools/getPoolSymbolAll.js +0 -16
  48. package/dist/tools/getPositions.js +0 -77
  49. package/dist/tools/marketInfo.js +0 -88
  50. package/dist/tools/orderQueries.js +0 -51
  51. package/dist/tools/poolConfig.js +0 -22
  52. package/dist/tools/positionHistory.js +0 -28
  53. package/dist/tools/searchMarket.js +0 -21
  54. package/dist/tools/setTpSl.js +0 -50
  55. package/dist/tools/updateOrderTpSl.js +0 -34
package/CHANGELOG.md CHANGED
@@ -1,16 +1,52 @@
1
1
  # Changelog
2
2
 
3
- ## 3.0.4 - 2026-03-17
3
+ ## 3.0.7 - 2026-03-18
4
+
5
+ ### Changed
6
+ - Updated server runtime version banner and MCP server version to `3.0.7`.
7
+ - Hardened `get_pool_metadata` warning output by compacting long low-level errors into concise warnings.
8
+ - Optimized `get_pool_info` read path:
9
+ - Prefer resolving a positive oracle/ticker market price and use it directly for pool info reads.
10
+ - Return clearer domain error for empty-liquidity / unresolved-price scenarios.
11
+ - Refined `get_user_trading_fee_rate` error handling:
12
+ - Return structured MCP error envelope (`INVALID_PARAM` / `SDK_READ_ERROR`) instead of raw error strings.
13
+ - Include normalized concise error messages and request context details.
14
+ - Enhanced `account_deposit` usability by making `tokenAddress` optional (defaults to `QUOTE_TOKEN_ADDRESS`).
15
+
16
+ ## 3.0.6 - 2026-03-18
17
+
18
+ ### Changed
19
+ - Upgraded SDK dependency to `@myx-trade/sdk@^1.0.2`.
20
+ - Updated client bootstrap to provide a viem-compatible `walletClient` shim (`json-rpc` account + `getAddresses/request/signMessage`) for SDK v1.0.2.
21
+ - Moved `get_trade_flow` to SDK v1.0.2 native path (`client.api.getTradeFlow`).
22
+ - Moved `account_withdraw` to SDK v1.0.2 native path (`account.updateAndWithdraw`).
23
+ - Normalized `baseToken` address before `pool.createPool` to satisfy stricter typed input.
24
+ - Updated account balance parsing to SDK v1.0.2 `getAccountInfo` fields (`freeMargin`, `walletBalance`).
25
+ - Hardened type guards for account snapshot and fee-rate parsing under SDK union return types.
26
+
27
+ ## 3.0.5 - 2026-03-18
28
+
29
+ ### Changed
30
+ - **Major Tool Consolidation**: Unified 40+ specialized tools into ~26 high-level semantic tools for easier AI steering.
31
+ - `get_market_price` & `get_oracle_price` → `get_price`
32
+ - `get_market_detail`, `get_pool_info`, `get_liquidity_info`, `get_pool_level_config` → `get_pool_metadata`
33
+ - `get_pool_list` & `get_pool_symbol_all` → `list_pools`
34
+ - `get_pool_by_symbol` & `search_market` → `find_pool` (Discovery)
35
+ - `cancel_order` & `cancel_all_orders` → `cancel_orders` (Batch support)
36
+ - `set_tp_sl` & `update_order_tp_sl` → `manage_tp_sl`
37
+ - `get_open_orders` & `get_order_history` → `get_orders`
38
+ - `get_positions` & `get_position_history` → `get_positions_all`
39
+ - `get_account` & `get_account_vip_info` → `get_account_snapshot`
40
+ - Updated `README.md` and `TOOL_EXAMPLES.md` to reflect the new unified toolset.
41
+ - Enhanced `trading_best_practices` prompt with updated v3.0.4 workflows.
42
+ - Improved `zodSchemaToJsonSchema` to correctly expose `Enum` values to LLMs.
43
+ - Removed 18+ obsolete tool files from the codebase.
44
+ - Verified build and server initialization with the new structure.
4
45
 
5
46
  ### Added
6
47
  - `get_my_lp_holdings` tool for listing all wallet LP balances with standardized naming.
7
48
  - Enriched `manage_liquidity` response with `lpAssetNames` (e.g., `mBTC.USDC`).
8
49
 
9
- ### Changed
10
- - Improved `close_all_positions` with more robust automated price fetching.
11
- - `get_liquidity_info` now accepts human-readable prices and `raw:` prefixes.
12
- - Updated `TOOL_EXAMPLES.md` to include LP holding and management samples.
13
-
14
50
  ## 3.0.3 - 2026-03-17
15
51
 
16
52
  ### Changed
package/README.md CHANGED
@@ -1,450 +1,85 @@
1
1
  # MYX MCP Trading Server
2
2
 
3
- A production-ready MCP (Model Context Protocol) server that exposes tools, resources, and prompts for AI agents.
4
-
5
- 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.
3
+ A production-ready MCP (Model Context Protocol) server for deep integration with **MYX Finance**—a decentralized perpetual exchange. It allows AI assistants to autonomously trade, manage liquidity, and analyze markets via terminal/backend using pure on-chain logic.
6
4
 
7
5
  ---
8
6
 
9
7
  # Release Notes
10
8
 
11
- - Current release: **3.0.0**
12
- - Breaking change: `get_account_info`, `get_balances`, and `get_margin_balance` were removed.
13
- - Replacement: use `get_account` for unified wallet + trading-account balance view.
14
- - Detailed history: `CHANGELOG.md`
9
+ - **Current release: 3.0.7**
10
+ - **SDK baseline**: `@myx-trade/sdk@^1.0.2` compatibility completed.
11
+ - **Refinement**: Consolidated 40+ specialized tools into ~26 high-level unified tools.
12
+ - **Improved UX**: Enhanced AI parameter parsing, automated unit conversion, and structured error reporting.
13
+ - **Breaking changes**: Many low-level tools (e.g., `get_market_price`, `get_oracle_price`, `get_open_orders`) have been merged into unified counterparts.
15
14
 
16
15
  ---
17
16
 
18
17
  # Features
19
18
 
20
- * MCP compliant server
21
- * AI-friendly tool design (Unit normalization, Automated ID resolution)
22
- * Structured input/output schemas for Web3 execution
23
- * Resource browsing support (`system://state`)
24
- * Prompt templates for trading decisions
25
- * Modular architecture
26
- * Logging and error handling
27
-
28
- ---
29
-
30
- # Architecture
31
-
32
- The project follows a modular architecture separating tools from trading services.
33
-
34
- AI Agents
35
-
36
- MCP Server
37
-
38
- Tools → Services → MYX SDK → Web3 RPC (EVM)
39
-
40
- Project structure:
41
-
42
- ```text
43
- src/
44
- server.ts
45
-
46
- tools/ # MCP exposed operations (e.g. executeTrade, searchMarket)
47
- resources/ # MCP contextual data (e.g. systemStateResource)
48
- prompts/ # MCP reusable templates (e.g. tradeAnalysisPrompt)
49
- services/ # Business logic calling the MYX SDK
50
- auth/ # Web3 wallet & client resolution
51
- utils/ # logger.ts, errors.ts, units.ts
52
-
53
- schemas/
54
- examples/
55
- tests/
56
- ```
57
-
58
- ---
59
-
60
- # Installation
61
-
62
- quick-start `npx @michaleffffff/mcp-trading-server`
19
+ * **Unified Toolset**: High-level semantic tools for simpler AI steering.
20
+ * **AI-First Design**: Automated Pool ID resolution and flexible unit handling (`human:` vs `raw:`).
21
+ * **Deep Liquidity Support**: Tools for both traders and liquidity providers.
22
+ * **Production Ready**: Robust error handling with actionable hints for LLMs.
23
+ * **Compliant**: Full Model Context Protocol (MCP) support.
63
24
 
64
25
  ---
65
26
 
66
27
  # Configuration
67
28
 
68
- Copy the example configuration:
29
+ Copy `.env.example` to `.env` and configure your trading wallet:
69
30
 
70
31
  ```bash
71
- cp .env.example .env
72
- ```
73
-
74
- ## Non-Auth Mode (No AccessToken)
75
-
76
- This MCP server runs in **non-auth mode**:
77
-
78
- - It does **not** call `myxClient.auth()` and does **not** manage AccessTokens.
79
- - All tools are designed to work without AccessToken authentication.
80
-
81
- ## User Key Configuration (Safe Practices)
82
-
83
- - **Local dev**: Put `PRIVATE_KEY` in a local `.env` (ignored by `.gitignore`) and never commit it.
84
- - **Production**: Inject via environment variables or a secrets manager, never store in code or repo.
85
- - **Best practice**: Use a dedicated low‑fund wallet, avoid reusing your main wallet, and rotate regularly.
86
-
87
- Environment variables needed for the trading wallet:
88
-
89
- ```bash
90
- # BNB Smart Chain (BSC Mainnet) (Default)
91
- PRIVATE_KEY=0xYourPrivateKey
32
+ PRIVATE_KEY=0x...
92
33
  RPC_URL=https://bsc-dataseed.bnbchain.org
93
34
  CHAIN_ID=56
94
- BROKER_ADDRESS=0xEb8C74fF05e76F85791dD2E4B972E7E78F6287C3
95
- QUOTE_TOKEN_ADDRESS=0x55d398326f99059fF775485246999027B3197955
35
+ BROKER_ADDRESS=0x...
36
+ QUOTE_TOKEN_ADDRESS=0x...
96
37
  QUOTE_TOKEN_DECIMALS=18
97
- IS_TESTNET=false
98
- MAX_TRADE_AMOUNT=5000 # Optional safety constraint limit for AI
99
38
  ```
100
39
 
101
- Testnet quick mapping:
102
-
103
- - `Arbitrum Sepolia (421614)`: `BROKER_ADDRESS=0x8f3153C18f698166f5D6124d8ba5B567F5f120f9`, `QUOTE_TOKEN_ADDRESS=0x7E248Ec1721639413A280d9E82e2862Cae2E6E28`
104
- - `Linea Sepolia (59141)`: `BROKER_ADDRESS=0x0FB08D3A1Ea6bE515fe78D3e0CaEb6990b468Cf3`, `QUOTE_TOKEN_ADDRESS=0xD984fd34f91F92DA0586e1bE82E262fF27DC431b`
105
-
106
40
  ---
107
41
 
108
- # Running the Server
109
-
110
- Build and Start the MCP server:
111
-
112
- ```bash
113
- npm run build
114
- npm run start
115
- ```
116
-
117
- The server will run using `stdio` transport and can be connected by any MCP-compatible client.
42
+ # Core Tools Reference
43
+
44
+ ### 📈 Market Analysis
45
+ * **`find_pool`**: Discover active markets by keyword/symbol (e.g., "BTC", "ETH").
46
+ * **`list_pools`**: List all tradable assets on the current chain.
47
+ * **`get_price`**: Fetch real-time prices (Impact Market Price or Oracle Price).
48
+ * **`get_pool_metadata`**: Comprehensive metrics (Fees, Open Interest, Liquidity Depth).
49
+ * **`get_kline`**: Fetch candlestick data for technical analysis.
50
+
51
+ ### ⚔️ Trading Operations
52
+ * **`open_position_simple`**: The recommended entry point for new trades. Handles size/price/fee computation. Supports Stop-Loss/Take-Profit.
53
+ * **`execute_trade`**: Low-level trade execution (Increase orders).
54
+ * **`close_position`**: Strategy-based closing of specific positions.
55
+ * **`close_all_positions`**: Emergency exit for all positions in a specific pool.
56
+ * **`cancel_orders`**: Unified cancellation (Single ID, Pool-wide, or Account-wide).
57
+ * **`manage_tp_sl`**: Adjust protection orders for active positions or pending orders.
58
+ * **`adjust_margin`**: Add or remove collateral to manage liquidation risk.
59
+
60
+ ### 📁 Account & Portfolio
61
+ * **`get_account_snapshot`**: Unified overview of balances, trading metrics, and VIP tier.
62
+ * **`get_orders`**: Historical and active order ledger.
63
+ * **`get_positions_all`**: Currently open and recently closed positions.
64
+ * **`get_trade_flow`**: Granular transaction history.
65
+ * **`check_account_ready`**: Pre-trade balance validator with auto-deposit support.
118
66
 
119
67
  ---
120
68
 
121
- ## Quick Start for Regular Users
69
+ # Quick Start Flow
122
70
 
123
- 1. **Prepare a wallet**: Use a testnet or a small dedicated wallet (avoid your main wallet).
124
- 2. **Configure env**: Copy `.env.example` to `.env` and fill in `PRIVATE_KEY`, `RPC_URL`, etc.
125
- 3. **Start the server**: Run `npm run build` then `npm run start` (use `npm run dev` for development).
126
- 4. **Configure your MCP client**: Set `command/args/env` in your MCP client (see Claude Desktop example below).
127
- 5. **Common flow**: Use `search_market` (or `get_pool_list`) to get `poolId`, then optionally `get_market_price` / `get_oracle_price` to view prices, and finally use `open_position_simple` (recommended) to open a position.
128
- Note: `open_position_simple` does not accept `tpPrice` / `tpSize` / `slPrice` / `slSize`. Use `set_tp_sl` (for positions) or `update_order_tp_sl` (for orders).
129
- 6. **Tool examples**: See `TOOL_EXAMPLES.md` for practical examples for every tool, common workflows, and parameter-unit guidance.
130
-
131
- **Minimal open position example:**
132
-
133
- ```json
134
- {
135
- "keyword": "BTC",
136
- "direction": 0,
137
- "collateralAmount": "100",
138
- "leverage": 5,
139
- "orderType": "MARKET",
140
- "autoDeposit": false
141
- }
142
- ```
143
-
144
- **Dry run (no transaction) example:**
145
-
146
- ```json
147
- {
148
- "keyword": "BTC",
149
- "direction": 0,
150
- "collateralAmount": "100",
151
- "leverage": 5,
152
- "orderType": "MARKET",
153
- "autoDeposit": false,
154
- "dryRun": true
155
- }
156
- ```
157
-
158
- ## Units & Precision
159
-
160
- - **Human by default**: For trading tools (e.g. `open_position_simple`), amounts like `"100"` mean **human-readable units**.
161
- - **Raw units (explicit)**: Prefix with `raw:` to pass raw units exactly (e.g. `raw:100000000` for 100 USDC with 6 decimals).
162
- - **Price**: `"price"` is human by default and will be converted to **30-decimal** format internally. Use `raw:` to pass a 30-decimal integer directly.
163
- - **Slippage**: `slippagePct` uses 4-decimal raw units: `100` = `1%`, `50` = `0.5%`, `1000` = `10%`.
164
- - **close_all_positions slippage**: Supports raw 4dp (`100`) and human percent strings (`"1.0"` or `"1%"`).
165
- - **get_liquidity_info marketPrice**: Supports raw 30-dec integer, `raw:...`, and human price inputs (`"2172.5"` / `human:2172.5`).
166
- - **close_position full-close helper**: `size` and `collateralAmount` accept `ALL` / `FULL` / `MAX` to auto-use exact live raw values.
167
- - **manage_liquidity action**: Case-insensitive (`ADD`, `add`, `Increase` all supported).
168
- - **account_deposit approval**: `account_deposit` now supports `autoApprove` and `approveMax` to auto-handle allowance when required.
169
- - **Note**: `check_approval.amount` still expects **raw integer strings**.
170
- - **`adjust_margin` units**: human amount is supported (e.g. `"1"` means 1 quote token). For exact atomic amount, use `raw:` (e.g. `"raw:1"`).
171
-
172
- ## P0 Reliability Contract (AI-friendly)
173
-
174
- Starting with P0, tool failures are normalized to a structured JSON envelope:
175
-
176
- ```json
177
- {
178
- "status": "error",
179
- "error": {
180
- "tool": "execute_trade",
181
- "code": "INVALID_PARAM",
182
- "message": "Invalid arguments for tool \"execute_trade\".",
183
- "hint": "Fix \"positionId\": positionId must be empty string for new position, or a bytes32 hex string.",
184
- "action": "Call list_tools and resend valid arguments.",
185
- "details": {
186
- "issues": [
187
- {
188
- "field": "positionId",
189
- "code": "custom",
190
- "message": "positionId must be empty string for new position, or a bytes32 hex string."
191
- }
192
- ]
193
- }
194
- }
195
- }
196
- ```
197
-
198
- Common error codes:
199
- - `INVALID_PARAM`: input schema/field error.
200
- - `INSUFFICIENT_BALANCE`: wallet or trading-account amount is not enough.
201
- - `INSUFFICIENT_ALLOWANCE`: token approval/allowance is insufficient.
202
- - `NOT_FOUND`: bad tool name or bad identifiers (`poolId`, `orderId`, `marketId`).
203
- - `TIMEOUT`: tx confirmation/query timeout.
204
- - `NETWORK_ERROR`: RPC or network issue.
205
-
206
- Search behavior in P0:
207
- - `search_market` now accepts empty `keyword` and returns active markets.
208
- - When `search_market` returns empty/unstable data, server-side fallback uses SDK `api.getMarketList()` and `api.getPoolList()` to rebuild active-market results.
209
- - For robust discovery, you can also call `get_pool_list` directly.
210
-
211
- Example:
212
-
213
- ```json
214
- {
215
- "name": "search_market",
216
- "arguments": {
217
- "keyword": "",
218
- "limit": 20
219
- }
220
- }
221
- ```
71
+ 1. **Find Target**: `find_pool(keyword="BTC")`
72
+ 2. **Check State**: `get_account_snapshot(poolId="...")`
73
+ 3. **Execute**: `open_position_simple(poolId="...", direction="LONG", leverage=5, collateralAmount="100")`
74
+ 4. **Monitor**: `get_positions_all(status="OPEN")`
222
75
 
223
76
  ---
224
77
 
225
- ## Secure Deployment Template (Systemd Example)
226
-
227
- **1) Put secrets in a system env file (chmod 600)**
78
+ # Documentation
228
79
 
229
- ```bash
230
- # /etc/myx-mcp.env
231
- PRIVATE_KEY=0xYourPrivateKey
232
- RPC_URL=https://bsc-dataseed.bnbchain.org
233
- CHAIN_ID=56
234
- BROKER_ADDRESS=0xEb8C74fF05e76F85791dD2E4B972E7E78F6287C3
235
- QUOTE_TOKEN_ADDRESS=0x55d398326f99059fF775485246999027B3197955
236
- QUOTE_TOKEN_DECIMALS=18
237
- IS_TESTNET=false
238
- ```
239
-
240
- ```bash
241
- sudo chmod 600 /etc/myx-mcp.env
242
- ```
243
-
244
- **2) Systemd service**
245
-
246
- ```ini
247
- # /etc/systemd/system/myx-mcp.service
248
- [Unit]
249
- Description=MYX MCP Trading Server
250
- After=network.target
251
-
252
- [Service]
253
- Type=simple
254
- User=myx
255
- Group=myx
256
- WorkingDirectory=/opt/myx-mcp-trading-server-v2
257
- EnvironmentFile=/etc/myx-mcp.env
258
- ExecStart=/usr/bin/node /opt/myx-mcp-trading-server-v2/dist/server.js
259
- Restart=on-failure
260
-
261
- [Install]
262
- WantedBy=multi-user.target
263
- ```
264
-
265
- **3) Start**
266
-
267
- ```bash
268
- sudo systemctl daemon-reload
269
- sudo systemctl enable --now myx-mcp
270
- ```
271
-
272
- ### Connecting Claude Desktop (MacOS)
273
- Add to `~/Library/Application Support/Claude/claude_desktop_config.json`:
274
- ```json
275
- {
276
- "mcpServers": {
277
- "myx-trading-v2": {
278
- "command": "node",
279
- "args": [
280
- "[/Absolute/Path/To/Your/Directory]/myx-mcp-trading-server-v2/dist/server.js"
281
- ],
282
- "env": {
283
- "PRIVATE_KEY": "0xYourPrivateKey"
284
- }
285
- }
286
- }
287
- }
288
- ```
289
-
290
- ---
291
-
292
- # Tools
293
-
294
- The server exposes tools categorized for AI:
295
-
296
- For practical tool-by-tool examples, see: `TOOL_EXAMPLES.md`
297
-
298
- ### Trading Operations
299
- * **open_position_simple**: High-level open position helper (recommended). Computes price/size/tradingFee internally. It only handles open/increase parameters and does **not** accept TP/SL fields (`tpPrice`, `tpSize`, `slPrice`, `slSize`); unknown keys are rejected by strict schema validation.
300
- * **execute_trade**: Execute a new trade or add to an existing position (includes parameter preflight, supports `human:`/`raw:` amount prefixes, auto-computes `tradingFee` when omitted).
301
- * **close_position**: Close an open position.
302
- * **close_all_positions**: Emergency: close ALL open positions in a pool at once.
303
- * **cancel_order**: Cancel an open order by its order ID.
304
- * **cancel_all_orders**: Cancel open orders by IDs (supports array, JSON-array string, comma string, or single ID; use `get_open_orders` first).
305
- * **set_tp_sl**: Set take profit and stop loss prices for an open position.
306
- * **update_order_tp_sl**: Update TP/SL fields for an existing order. Accepts boolean-like values for `useOrderCollateral` / `isTpSlOrder`.
307
- * **adjust_margin**: Adjust the margin (collateral) of an open position.
308
- * **get_user_trading_fee_rate**: Query current maker/taker fee rates by asset class and risk tier.
309
- * **get_network_fee**: Query estimated network fee requirements for a market.
310
-
311
- ### Market Data
312
- * **search_market**: Search for an active market (e.g., "BTC") to retrieve its unique `poolId` (Crucial prerequisite).
313
- * **get_market_price**: Get the current ticker market price for a specific pool.
314
- * **get_oracle_price**: Get the current EVM oracle price for a specific pool.
315
- * **get_kline_latest_bar**: Get only the latest bar for an interval.
316
- * **get_all_tickers**: Get all ticker snapshots in one request.
317
- * **get_kline**, **get_pool_info**... (`get_pool_info` auto-retries with oracle/ticker price on divide-by-zero reads)
318
- * **get_pool_symbol_all**, **get_base_detail**, **get_pool_level_config**...
319
-
320
- ### Account & Portfolio
321
- * **get_positions**: Get all open positions for the current account.
322
- * **get_account**: Unified account snapshot. Clearly separates **wallet balance** and **trading-account balance** (provide `poolId` for full trading-account metrics).
323
- * **get_my_lp_holdings**: Scan pools and return your base/quote LP token balances on the current chain, with standardized LP asset names (`base: mBASE.QUOTE`, `quote: mQUOTE.BASE`).
324
- * **get_account_vip_info**: Query account VIP tier details.
325
- * **get_position_history**, **get_open_orders**, **get_order_history**...
326
-
327
- `get_account` note:
328
- - `poolId` omitted: wallet-focused snapshot only.
329
- - `poolId` provided: wallet + trading-account + margin snapshot.
330
- - If one section fails (wallet or trading-account), the tool may return a **partial** snapshot with `meta.partial=true` and section-level `error` details.
331
-
332
- ### Liquidity Provision (LP)
333
- * **manage_liquidity**: Add or withdraw liquidity from a BASE or QUOTE pool (aliases: `add/remove/increase/decrease` are supported). `poolId` is pre-validated on target `chainId` for clearer errors. Response includes LP naming metadata (`baseLpAssetName=mBASE.QUOTE`, `quoteLpAssetName=mQUOTE.BASE`, `operatedLpAssetName`).
334
- - Example (`BTC/USDC`, `poolType=QUOTE`): `operatedLpAssetName = mUSDC.BTC`.
335
- * **create_perp_market**: Create a new perpetual trading pair.
336
-
337
- ---
338
-
339
- # Resources
340
-
341
- Resources provide contextual data that AI agents can read.
342
-
343
- Available resources:
344
-
345
- **`system://state`**
346
-
347
- Description:
348
- Readonly contextual data about the active EVM network, connected wallet address, chain ID, and RPC health available to the AI.
349
-
350
- ---
351
-
352
- # Prompts
353
-
354
- Reusable prompt templates for AI tasks.
355
-
356
- ## `analyze_positions`
357
-
358
- Analyze the user's current trading positions based on real-time market action.
359
-
360
- **Arguments:**
361
-
362
- * `marketContext` (string, optional) - Provide the latest market insights or news to contextualize the analysis.
363
-
364
- **Returns:**
365
- Messages including a stringified dump of the user's active portfolio on MYX ready to be sent to an LLM for trading advice.
366
-
367
- ---
368
-
369
- # Example Usage
370
-
371
- Example MCP client usage workflow:
372
-
373
- 1. Connect to the MCP server.
374
- 2. Read the `system://state` resource to confirm wallet connectivity.
375
- 3. Call the `search_market` tool (e.g., `keyword: "ETH"`) to retrieve the `poolId`.
376
- 4. Call `open_position_simple` passing the retrieved `poolId` to open a 10x long position.
377
-
378
- ## Limit Order Lifecycle (P0)
379
-
380
- Use this query/mutation loop for limit-order management:
381
-
382
- 1. Place order with `execute_trade` (`orderType=LIMIT`).
383
- 2. Query active orders with `get_open_orders`.
384
- 3. If still pending, you can cancel/update order-level fields; if filled into a position, prefer `set_tp_sl` for position TP/SL.
385
- 4. Check historical fills/cancellations with `get_order_history`.
386
- 5. Cancel one order via `cancel_order` or batch via `cancel_all_orders`.
387
-
388
- ## Unit Safety (P0)
389
-
390
- - Monetary fields in major mutation tools support `human:` and `raw:` prefixes.
391
- - Default behavior is human-readable units (e.g. `1` means `1.0` token), while `raw:<int>` enforces exact raw units.
392
- - `execute_trade` and `adjust_margin` responses include normalized raw values for auditability.
393
-
394
- Minimal query examples:
395
-
396
- ```json
397
- {
398
- "name": "get_open_orders",
399
- "arguments": {}
400
- }
401
- ```
402
-
403
- ```json
404
- {
405
- "name": "get_order_history",
406
- "arguments": {
407
- "poolId": "0x...",
408
- "limit": 20
409
- }
410
- }
411
- ```
412
-
413
- Example integration scripts are located in:
414
- `examples/basicUsage.ts`
415
-
416
- ---
417
-
418
- # Development
419
-
420
- Run in development mode (watcher):
421
-
422
- ```bash
423
- npm run dev
424
- ```
425
-
426
- Run tests:
427
-
428
- ```bash
429
- npm test
430
- npm run test:new-tools
431
- ```
80
+ For detailed implementation examples and parameter guides, see:
81
+ * **[TOOL_EXAMPLES.md](./TOOL_EXAMPLES.md)**: Payload examples for every tool.
82
+ * **[CHANGELOG.md](./CHANGELOG.md)**: Version history and migration paths.
83
+ * **[mcp_config_guide.md](./mcp_config_guide.md)**: Client setup instructions.
432
84
 
433
85
  ---
434
-
435
- # Extending the Server
436
-
437
- To add a new tool:
438
-
439
- 1. Create a new file in `src/tools/myNewTool.ts`
440
- 2. Define the Zod input schema and description
441
- 3. Implement the `handler(args)` executing the trading logic
442
- 4. Export and register it in `src/tools/index.ts`
443
-
444
- ---
445
-
446
- # Contributing
447
-
448
- Contributions are welcome.
449
-
450
- Please open an issue or submit a pull request.