@michaleffffff/mcp-trading-server 3.0.2 → 3.0.3
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.
- package/CHANGELOG.md +7 -0
- package/README.md +7 -5
- package/TOOL_EXAMPLES.md +50 -18
- package/dist/prompts/tradingGuide.js +3 -1
- package/dist/server.js +2 -2
- package/dist/services/marketService.js +2 -2
- package/dist/tools/createPerpMarket.js +1 -1
- package/dist/tools/executeTrade.js +1 -1
- package/dist/tools/getMyLpHoldings.js +265 -0
- package/dist/tools/index.js +1 -2
- package/dist/tools/manageLiquidity.js +76 -8
- package/package.json +1 -1
- package/dist/tools/getMarketList.js +0 -20
- package/dist/tools/getMarketListRaw.js +0 -16
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,12 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 3.0.3 - 2026-03-17
|
|
4
|
+
|
|
5
|
+
### Changed
|
|
6
|
+
- Enhanced `create_perp_market` tool description to better explain `marketId` requirements.
|
|
7
|
+
- Added usage hints to `execute_trade` schema for improved AI coordination.
|
|
8
|
+
- Internal: `resolvePool` now supports `chainIdOverride` for more flexible market resolution.
|
|
9
|
+
|
|
3
10
|
## 3.0.2 - 2026-03-17
|
|
4
11
|
|
|
5
12
|
### Added
|
package/README.md
CHANGED
|
@@ -124,7 +124,7 @@ The server will run using `stdio` transport and can be connected by any MCP-comp
|
|
|
124
124
|
2. **Configure env**: Copy `.env.example` to `.env` and fill in `PRIVATE_KEY`, `RPC_URL`, etc.
|
|
125
125
|
3. **Start the server**: Run `npm run build` then `npm run start` (use `npm run dev` for development).
|
|
126
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 `
|
|
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
128
|
6. **Tool examples**: See `TOOL_EXAMPLES.md` for practical examples for every tool, common workflows, and parameter-unit guidance.
|
|
129
129
|
|
|
130
130
|
**Minimal open position example:**
|
|
@@ -200,7 +200,7 @@ Common error codes:
|
|
|
200
200
|
Search behavior in P0:
|
|
201
201
|
- `search_market` now accepts empty `keyword` and returns active markets.
|
|
202
202
|
- When `search_market` returns empty/unstable data, server-side fallback uses SDK `api.getMarketList()` and `api.getPoolList()` to rebuild active-market results.
|
|
203
|
-
- For robust discovery, you can also call `
|
|
203
|
+
- For robust discovery, you can also call `get_pool_list` directly.
|
|
204
204
|
|
|
205
205
|
Example:
|
|
206
206
|
|
|
@@ -285,7 +285,7 @@ Add to `~/Library/Application Support/Claude/claude_desktop_config.json`:
|
|
|
285
285
|
|
|
286
286
|
# Tools
|
|
287
287
|
|
|
288
|
-
The server exposes
|
|
288
|
+
The server exposes tools categorized for AI:
|
|
289
289
|
|
|
290
290
|
For practical tool-by-tool examples, see: `TOOL_EXAMPLES.md`
|
|
291
291
|
|
|
@@ -308,12 +308,13 @@ For practical tool-by-tool examples, see: `TOOL_EXAMPLES.md`
|
|
|
308
308
|
* **get_oracle_price**: Get the current EVM oracle price for a specific pool.
|
|
309
309
|
* **get_kline_latest_bar**: Get only the latest bar for an interval.
|
|
310
310
|
* **get_all_tickers**: Get all ticker snapshots in one request.
|
|
311
|
-
* **
|
|
311
|
+
* **get_kline**, **get_pool_info**... (`get_pool_info` auto-retries with oracle/ticker price on divide-by-zero reads)
|
|
312
312
|
* **get_pool_symbol_all**, **get_base_detail**, **get_pool_level_config**...
|
|
313
313
|
|
|
314
314
|
### Account & Portfolio
|
|
315
315
|
* **get_positions**: Get all open positions for the current account.
|
|
316
316
|
* **get_account**: Unified account snapshot. Clearly separates **wallet balance** and **trading-account balance** (provide `poolId` for full trading-account metrics).
|
|
317
|
+
* **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`).
|
|
317
318
|
* **get_account_vip_info**: Query account VIP tier details.
|
|
318
319
|
* **get_position_history**, **get_open_orders**, **get_order_history**...
|
|
319
320
|
|
|
@@ -323,7 +324,8 @@ For practical tool-by-tool examples, see: `TOOL_EXAMPLES.md`
|
|
|
323
324
|
- If one section fails (wallet or trading-account), the tool may return a **partial** snapshot with `meta.partial=true` and section-level `error` details.
|
|
324
325
|
|
|
325
326
|
### Liquidity Provision (LP)
|
|
326
|
-
* **manage_liquidity**: Add or withdraw liquidity from a BASE or QUOTE pool (aliases: `add/remove/increase/decrease` are supported).
|
|
327
|
+
* **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`).
|
|
328
|
+
- Example (`BTC/USDC`, `poolType=QUOTE`): `operatedLpAssetName = mUSDC.BTC`.
|
|
327
329
|
* **create_perp_market**: Create a new perpetual trading pair.
|
|
328
330
|
|
|
329
331
|
---
|
package/TOOL_EXAMPLES.md
CHANGED
|
@@ -296,24 +296,6 @@ Success payload includes normalized raw amount under `data.normalized.adjustAmou
|
|
|
296
296
|
```
|
|
297
297
|
Note: this tool may internally fallback to SDK `api.getMarketList()` / `api.getPoolList()` when direct search is empty.
|
|
298
298
|
|
|
299
|
-
### `get_market_list`
|
|
300
|
-
```json
|
|
301
|
-
{
|
|
302
|
-
"name": "get_market_list",
|
|
303
|
-
"arguments": {
|
|
304
|
-
"limit": 50
|
|
305
|
-
}
|
|
306
|
-
}
|
|
307
|
-
```
|
|
308
|
-
|
|
309
|
-
### `get_market_list_raw`
|
|
310
|
-
```json
|
|
311
|
-
{
|
|
312
|
-
"name": "get_market_list_raw",
|
|
313
|
-
"arguments": {}
|
|
314
|
-
}
|
|
315
|
-
```
|
|
316
|
-
|
|
317
299
|
### `get_pool_list`
|
|
318
300
|
```json
|
|
319
301
|
{
|
|
@@ -455,6 +437,31 @@ If one section fails, check `data.meta.partial` and section-level `error` fields
|
|
|
455
437
|
}
|
|
456
438
|
```
|
|
457
439
|
|
|
440
|
+
### `get_my_lp_holdings`
|
|
441
|
+
```json
|
|
442
|
+
{
|
|
443
|
+
"name": "get_my_lp_holdings",
|
|
444
|
+
"arguments": {}
|
|
445
|
+
}
|
|
446
|
+
```
|
|
447
|
+
LP asset naming rule in each item:
|
|
448
|
+
- `baseLpAssetName`: `mBASE.QUOTE` (e.g. `mBTC.USDC`)
|
|
449
|
+
- `quoteLpAssetName`: `mQUOTE.BASE` (e.g. `mUSDC.BTC`)
|
|
450
|
+
Include zero-balance pools and optional filtering:
|
|
451
|
+
```json
|
|
452
|
+
{
|
|
453
|
+
"name": "get_my_lp_holdings",
|
|
454
|
+
"arguments": {
|
|
455
|
+
"includeZero": true,
|
|
456
|
+
"poolIds": [
|
|
457
|
+
"0xPOOL_ID_1",
|
|
458
|
+
"0xPOOL_ID_2"
|
|
459
|
+
],
|
|
460
|
+
"maxPools": 50
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
```
|
|
464
|
+
|
|
458
465
|
### `get_positions`
|
|
459
466
|
```json
|
|
460
467
|
{
|
|
@@ -563,6 +570,31 @@ Alias action example (`remove` == `withdraw`):
|
|
|
563
570
|
}
|
|
564
571
|
```
|
|
565
572
|
If operation fails, check `error.message` for concrete reasons (for example `Insufficient Balance`) instead of generic `undefined`.
|
|
573
|
+
`poolId` must be valid on the target `chainId`; if uncertain, resolve with `search_market` / `get_pool_list` first.
|
|
574
|
+
Success response includes `data.lpAssetNames`:
|
|
575
|
+
- `baseLpAssetName`: `mBASE.QUOTE` (e.g. `mBTC.USDC`)
|
|
576
|
+
- `quoteLpAssetName`: `mQUOTE.BASE` (e.g. `mUSDC.BTC`)
|
|
577
|
+
- `operatedLpAssetName`: LP asset name matching current `poolType`
|
|
578
|
+
Example success payload (abridged):
|
|
579
|
+
```json
|
|
580
|
+
{
|
|
581
|
+
"status": "success",
|
|
582
|
+
"data": {
|
|
583
|
+
"confirmation": {
|
|
584
|
+
"confirmed": true,
|
|
585
|
+
"txHash": "0x..."
|
|
586
|
+
},
|
|
587
|
+
"lpAssetNames": {
|
|
588
|
+
"baseSymbol": "BTC",
|
|
589
|
+
"quoteSymbol": "USDC",
|
|
590
|
+
"baseLpAssetName": "mBTC.USDC",
|
|
591
|
+
"quoteLpAssetName": "mUSDC.BTC",
|
|
592
|
+
"operatedPoolType": "QUOTE",
|
|
593
|
+
"operatedLpAssetName": "mUSDC.BTC"
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
```
|
|
566
598
|
|
|
567
599
|
### `get_lp_price`
|
|
568
600
|
```json
|
|
@@ -17,7 +17,7 @@ export const tradingGuidePrompt = {
|
|
|
17
17
|
You are an expert crypto trader using the MYX Protocol. To ensure successful execution and safe handling of user funds, follow these patterns:
|
|
18
18
|
|
|
19
19
|
## 1. The Standard Workflow
|
|
20
|
-
1. **Discovery**: Use \`search_market\` with a keyword (or empty keyword) to find active \`poolId\` values. If needed, fallback to \`
|
|
20
|
+
1. **Discovery**: Use \`search_market\` with a keyword (or empty keyword) to find active \`poolId\` values. If needed, fallback to \`get_pool_list\`.
|
|
21
21
|
2. **Context**: Use \`get_market_price\` and \`get_account\` (with \`poolId\`) to check market state, wallet balance, and trading-account margin.
|
|
22
22
|
3. **Execution**: Prefer \`open_position_simple\` for new trades. It handles unit conversions and pool resolution automatically.
|
|
23
23
|
4. **Validation**: Always check the \`verification.verified\` flag in the output. If \`false\`, read the \`cancelReason\` to explain the failure to the user.
|
|
@@ -31,6 +31,8 @@ You are an expert crypto trader using the MYX Protocol. To ensure successful exe
|
|
|
31
31
|
- **Fees**: Use \`get_user_trading_fee_rate\` to estimate fees before large trades.
|
|
32
32
|
- **execute_trade**: Has built-in preflight normalization and can auto-compute \`tradingFee\` when omitted.
|
|
33
33
|
- **Balances**: Use \`get_account\` to clearly separate wallet balance vs trading-account balance (pass \`poolId\` for trading-account metrics).
|
|
34
|
+
- **LP Holdings**: Use \`get_my_lp_holdings\` to scan base/quote LP token balances across pools on the current chain; naming convention is \`baseLpAssetName=mBASE.QUOTE\`, \`quoteLpAssetName=mQUOTE.BASE\` (e.g., \`mBTC.USDC\`, \`mUSDC.BTC\`).
|
|
35
|
+
- **Liquidity Mutation Output**: \`manage_liquidity\` success output includes \`data.lpAssetNames\` with \`baseLpAssetName\`, \`quoteLpAssetName\`, and \`operatedLpAssetName\`.
|
|
34
36
|
- **Adjust Margin**: \`adjust_margin.adjustAmount\` supports human amount (e.g. "1"), and also supports exact raw amount via \`raw:\` prefix.
|
|
35
37
|
- **TP/SL Updates**: \`update_order_tp_sl\` accepts boolean-like values for \`useOrderCollateral\` and \`isTpSlOrder\`, but pending LIMIT/STOP orders can still be rejected by protocol rules; after fill, prefer \`set_tp_sl\`.
|
|
36
38
|
- **Pool Reads**: \`get_pool_info\` auto-retries with oracle/ticker price when direct on-chain read returns divide-by-zero.
|
package/dist/server.js
CHANGED
|
@@ -352,7 +352,7 @@ function zodSchemaToJsonSchema(zodSchema) {
|
|
|
352
352
|
};
|
|
353
353
|
}
|
|
354
354
|
// ─── MCP Server ───
|
|
355
|
-
const server = new Server({ name: "myx-mcp-trading-server", version: "3.0.
|
|
355
|
+
const server = new Server({ name: "myx-mcp-trading-server", version: "3.0.3" }, { capabilities: { tools: {}, resources: {}, prompts: {} } });
|
|
356
356
|
// List tools
|
|
357
357
|
server.setRequestHandler(ListToolsRequestSchema, async () => {
|
|
358
358
|
return {
|
|
@@ -473,7 +473,7 @@ server.setRequestHandler(GetPromptRequestSchema, async (request) => {
|
|
|
473
473
|
async function main() {
|
|
474
474
|
const transport = new StdioServerTransport();
|
|
475
475
|
await server.connect(transport);
|
|
476
|
-
logger.info("🚀 MYX Trading MCP Server v3.0.
|
|
476
|
+
logger.info("🚀 MYX Trading MCP Server v3.0.3 running (stdio, pure on-chain, prod ready)");
|
|
477
477
|
}
|
|
478
478
|
main().catch((err) => {
|
|
479
479
|
logger.error("Fatal Server Startup Error", err);
|
|
@@ -162,8 +162,8 @@ export async function getPoolLevelConfig(client, poolId, chainIdOverride) {
|
|
|
162
162
|
/**
|
|
163
163
|
* 智能解析 Pool ID (支持 ID 校验与关键词回退)
|
|
164
164
|
*/
|
|
165
|
-
export async function resolvePool(client, poolId, keyword) {
|
|
166
|
-
const chainId = getChainId();
|
|
165
|
+
export async function resolvePool(client, poolId, keyword, chainIdOverride) {
|
|
166
|
+
const chainId = chainIdOverride ?? getChainId();
|
|
167
167
|
let pid = poolId?.trim();
|
|
168
168
|
// 1. 如果提供了 poolId,先尝试验证其是否存在
|
|
169
169
|
if (pid) {
|
|
@@ -4,7 +4,7 @@ import { resolveClient } from "../auth/resolveClient.js";
|
|
|
4
4
|
import { finalizeMutationResult } from "../utils/mutationResult.js";
|
|
5
5
|
export const createPerpMarketTool = {
|
|
6
6
|
name: "create_perp_market",
|
|
7
|
-
description: "Create a new perpetual contract pool on MYX. IMPORTANT: marketId cannot be randomly generated. It must be a valid 66-character config hash (0x...) tied to a supported quote token (like USDC). Use
|
|
7
|
+
description: "Create a new perpetual contract pool on MYX. IMPORTANT: marketId cannot be randomly generated. It must be a valid 66-character config hash (0x...) tied to a supported quote token (like USDC). Use get_market_detail (after search_market/get_pool_list) to fetch an existing marketId if you don't have a specific newly allocated one.",
|
|
8
8
|
schema: {
|
|
9
9
|
baseToken: z.string().describe("Base token contract address (e.g., 0xb40aaadc43...)"),
|
|
10
10
|
marketId: z.string().describe("MUST be a valid 66-char config hash (e.g., existing USDC marketId: 0x7f6727d8026fd2c87ccc745846c83cd0b68e886c73e1e05a54a675bcadd8adb6). Do NOT generate randomly."),
|
|
@@ -35,7 +35,7 @@ export const executeTradeTool = {
|
|
|
35
35
|
tradingFee: z.union([z.string(), z.number()]).optional().describe("Trading fee in quote token units. Supports human/raw prefix. Optional: auto-computed via get_user_trading_fee_rate."),
|
|
36
36
|
assetClass: z.coerce.number().int().nonnegative().optional().describe("Optional fee lookup assetClass (default from pool config or 1)."),
|
|
37
37
|
riskTier: z.coerce.number().int().nonnegative().optional().describe("Optional fee lookup riskTier (default from pool config or 1)."),
|
|
38
|
-
marketId: z.string().describe("Specific Market Config Hash. Fetch via
|
|
38
|
+
marketId: z.string().describe("Specific Market Config Hash. Fetch via get_market_detail (resolve poolId first with search_market/get_pool_list)."),
|
|
39
39
|
},
|
|
40
40
|
handler: async (args) => {
|
|
41
41
|
try {
|
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { resolveClient, getChainId } from "../auth/resolveClient.js";
|
|
3
|
+
import { COMMON_LP_AMOUNT_DECIMALS } from "@myx-trade/sdk";
|
|
4
|
+
import { Contract, formatUnits } from "ethers";
|
|
5
|
+
import { extractErrorMessage } from "../utils/errorMessage.js";
|
|
6
|
+
const ADDRESS_RE = /^0x[a-fA-F0-9]{40}$/;
|
|
7
|
+
const ERC20_BALANCE_ABI = ["function balanceOf(address owner) view returns (uint256)"];
|
|
8
|
+
function collectRows(input) {
|
|
9
|
+
if (Array.isArray(input))
|
|
10
|
+
return input.flatMap(collectRows);
|
|
11
|
+
if (!input || typeof input !== "object")
|
|
12
|
+
return [];
|
|
13
|
+
if (input.poolId || input.pool_id)
|
|
14
|
+
return [input];
|
|
15
|
+
return Object.values(input).flatMap(collectRows);
|
|
16
|
+
}
|
|
17
|
+
function readAddress(value) {
|
|
18
|
+
const text = String(value ?? "").trim();
|
|
19
|
+
if (!text || !ADDRESS_RE.test(text))
|
|
20
|
+
return null;
|
|
21
|
+
return text;
|
|
22
|
+
}
|
|
23
|
+
function normalizePoolId(value) {
|
|
24
|
+
return String(value ?? "").trim();
|
|
25
|
+
}
|
|
26
|
+
function normalizeAssetSymbol(value) {
|
|
27
|
+
const text = String(value ?? "").trim();
|
|
28
|
+
if (!text)
|
|
29
|
+
return "";
|
|
30
|
+
return text.replace(/\s+/g, "").replace(/\//g, "").toUpperCase();
|
|
31
|
+
}
|
|
32
|
+
function parsePairSymbols(value) {
|
|
33
|
+
const text = String(value ?? "").trim();
|
|
34
|
+
if (!text)
|
|
35
|
+
return null;
|
|
36
|
+
const parts = text
|
|
37
|
+
.split(/[\/:_-]/)
|
|
38
|
+
.map((item) => normalizeAssetSymbol(item))
|
|
39
|
+
.filter(Boolean);
|
|
40
|
+
if (parts.length >= 2) {
|
|
41
|
+
return { base: parts[0], quote: parts[1] };
|
|
42
|
+
}
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
function resolveBaseQuoteSymbols(row, detail) {
|
|
46
|
+
const baseCandidates = [
|
|
47
|
+
row?.baseSymbol,
|
|
48
|
+
detail?.baseSymbol,
|
|
49
|
+
row?.base_symbol,
|
|
50
|
+
detail?.base_symbol,
|
|
51
|
+
];
|
|
52
|
+
const quoteCandidates = [
|
|
53
|
+
row?.quoteSymbol,
|
|
54
|
+
detail?.quoteSymbol,
|
|
55
|
+
row?.quote_symbol,
|
|
56
|
+
detail?.quote_symbol,
|
|
57
|
+
];
|
|
58
|
+
let baseSymbol = baseCandidates.map((item) => normalizeAssetSymbol(item)).find(Boolean) || "";
|
|
59
|
+
let quoteSymbol = quoteCandidates.map((item) => normalizeAssetSymbol(item)).find(Boolean) || "";
|
|
60
|
+
if (!baseSymbol || !quoteSymbol) {
|
|
61
|
+
const pairCandidate = row?.baseQuoteSymbol ??
|
|
62
|
+
detail?.baseQuoteSymbol ??
|
|
63
|
+
row?.symbol ??
|
|
64
|
+
detail?.symbol ??
|
|
65
|
+
row?.symbolName ??
|
|
66
|
+
detail?.symbolName;
|
|
67
|
+
const parsed = parsePairSymbols(pairCandidate);
|
|
68
|
+
if (parsed) {
|
|
69
|
+
baseSymbol = baseSymbol || parsed.base;
|
|
70
|
+
quoteSymbol = quoteSymbol || parsed.quote;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return {
|
|
74
|
+
baseSymbol: baseSymbol || null,
|
|
75
|
+
quoteSymbol: quoteSymbol || null,
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
function buildLpAssetNames(baseSymbol, quoteSymbol) {
|
|
79
|
+
if (!baseSymbol || !quoteSymbol) {
|
|
80
|
+
return { baseLpAssetName: null, quoteLpAssetName: null };
|
|
81
|
+
}
|
|
82
|
+
return {
|
|
83
|
+
baseLpAssetName: `m${baseSymbol}.${quoteSymbol}`,
|
|
84
|
+
quoteLpAssetName: `m${quoteSymbol}.${baseSymbol}`,
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
function normalizePoolIdsInput(input) {
|
|
88
|
+
if (Array.isArray(input)) {
|
|
89
|
+
return input.map((item) => normalizePoolId(item)).filter(Boolean);
|
|
90
|
+
}
|
|
91
|
+
if (typeof input !== "string")
|
|
92
|
+
return [];
|
|
93
|
+
const text = input.trim();
|
|
94
|
+
if (!text)
|
|
95
|
+
return [];
|
|
96
|
+
if (text.startsWith("[") && text.endsWith("]")) {
|
|
97
|
+
try {
|
|
98
|
+
const parsed = JSON.parse(text);
|
|
99
|
+
if (Array.isArray(parsed)) {
|
|
100
|
+
return parsed.map((item) => normalizePoolId(item)).filter(Boolean);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
catch {
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
if (text.includes(",")) {
|
|
107
|
+
return text.split(",").map((item) => normalizePoolId(item)).filter(Boolean);
|
|
108
|
+
}
|
|
109
|
+
return [text];
|
|
110
|
+
}
|
|
111
|
+
function toSymbol(row) {
|
|
112
|
+
const baseQuote = String(row?.baseQuoteSymbol ?? row?.symbol ?? "").trim();
|
|
113
|
+
if (baseQuote)
|
|
114
|
+
return baseQuote;
|
|
115
|
+
const base = String(row?.baseSymbol ?? "").trim();
|
|
116
|
+
const quote = String(row?.quoteSymbol ?? "").trim();
|
|
117
|
+
if (base && quote)
|
|
118
|
+
return `${base}/${quote}`;
|
|
119
|
+
if (base)
|
|
120
|
+
return base;
|
|
121
|
+
return normalizePoolId(row?.poolId ?? row?.pool_id);
|
|
122
|
+
}
|
|
123
|
+
function sumRaw(baseRaw, quoteRaw) {
|
|
124
|
+
return BigInt(baseRaw || "0") + BigInt(quoteRaw || "0");
|
|
125
|
+
}
|
|
126
|
+
async function readErc20Balance(provider, tokenAddress, holder) {
|
|
127
|
+
const contract = new Contract(tokenAddress, ERC20_BALANCE_ABI, provider);
|
|
128
|
+
const balance = await contract.balanceOf(holder);
|
|
129
|
+
return BigInt(balance).toString();
|
|
130
|
+
}
|
|
131
|
+
export const getMyLpHoldingsTool = {
|
|
132
|
+
name: "get_my_lp_holdings",
|
|
133
|
+
description: "List your LP holdings across pools on the current chain by reading base/quote LP token balances. Includes standardized LP asset names: base LP `mBASE.QUOTE`, quote LP `mQUOTE.BASE`.",
|
|
134
|
+
schema: {
|
|
135
|
+
includeZero: z.coerce.boolean().optional().describe("If true, include pools with zero LP balances (default false)."),
|
|
136
|
+
poolIds: z.union([z.array(z.string()).min(1), z.string().min(1)]).optional().describe("Optional poolId filter. Supports array, JSON-array string, comma string, or single poolId."),
|
|
137
|
+
maxPools: z.coerce.number().int().positive().max(2000).optional().describe("Optional cap for scanned pools (default all)."),
|
|
138
|
+
},
|
|
139
|
+
handler: async (args) => {
|
|
140
|
+
try {
|
|
141
|
+
const { client, address, signer } = await resolveClient();
|
|
142
|
+
const chainId = getChainId();
|
|
143
|
+
const provider = signer?.provider;
|
|
144
|
+
if (!provider) {
|
|
145
|
+
throw new Error("Provider is unavailable for LP balance reads.");
|
|
146
|
+
}
|
|
147
|
+
const includeZero = !!args.includeZero;
|
|
148
|
+
const poolIdsFilter = normalizePoolIdsInput(args.poolIds);
|
|
149
|
+
const filterSet = new Set(poolIdsFilter.map((item) => item.toLowerCase()));
|
|
150
|
+
const maxPools = Number.isFinite(Number(args.maxPools)) ? Math.floor(Number(args.maxPools)) : null;
|
|
151
|
+
const poolListRes = await client.api.getPoolList();
|
|
152
|
+
const rows = collectRows(poolListRes?.data ?? poolListRes);
|
|
153
|
+
const deduped = new Map();
|
|
154
|
+
for (const row of rows) {
|
|
155
|
+
const poolId = normalizePoolId(row?.poolId ?? row?.pool_id);
|
|
156
|
+
if (!poolId)
|
|
157
|
+
continue;
|
|
158
|
+
if (filterSet.size > 0 && !filterSet.has(poolId.toLowerCase()))
|
|
159
|
+
continue;
|
|
160
|
+
if (!deduped.has(poolId.toLowerCase())) {
|
|
161
|
+
deduped.set(poolId.toLowerCase(), row);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
const selectedRows = Array.from(deduped.values());
|
|
165
|
+
const scannedRows = maxPools ? selectedRows.slice(0, maxPools) : selectedRows;
|
|
166
|
+
const items = [];
|
|
167
|
+
const warnings = [];
|
|
168
|
+
let totalBaseLpRaw = 0n;
|
|
169
|
+
let totalQuoteLpRaw = 0n;
|
|
170
|
+
for (const row of scannedRows) {
|
|
171
|
+
const poolId = normalizePoolId(row?.poolId ?? row?.pool_id);
|
|
172
|
+
let basePoolToken = readAddress(row?.basePoolToken ?? row?.base_pool_token);
|
|
173
|
+
let quotePoolToken = readAddress(row?.quotePoolToken ?? row?.quote_pool_token);
|
|
174
|
+
let detail = null;
|
|
175
|
+
if (!basePoolToken || !quotePoolToken) {
|
|
176
|
+
try {
|
|
177
|
+
const detailRes = await client.markets.getMarketDetail({ chainId, poolId });
|
|
178
|
+
detail = detailRes?.data || (detailRes?.marketId ? detailRes : null);
|
|
179
|
+
basePoolToken = basePoolToken ?? readAddress(detail?.basePoolToken ?? detail?.base_pool_token);
|
|
180
|
+
quotePoolToken = quotePoolToken ?? readAddress(detail?.quotePoolToken ?? detail?.quote_pool_token);
|
|
181
|
+
}
|
|
182
|
+
catch (error) {
|
|
183
|
+
warnings.push(`pool ${poolId}: failed to enrich pool detail (${extractErrorMessage(error)})`);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
const { baseSymbol, quoteSymbol } = resolveBaseQuoteSymbols(row, detail);
|
|
187
|
+
const { baseLpAssetName, quoteLpAssetName } = buildLpAssetNames(baseSymbol, quoteSymbol);
|
|
188
|
+
let baseLpRaw = "0";
|
|
189
|
+
let quoteLpRaw = "0";
|
|
190
|
+
if (basePoolToken) {
|
|
191
|
+
try {
|
|
192
|
+
baseLpRaw = await readErc20Balance(provider, basePoolToken, address);
|
|
193
|
+
}
|
|
194
|
+
catch (error) {
|
|
195
|
+
warnings.push(`pool ${poolId}: failed to read base LP balance (${extractErrorMessage(error)})`);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
if (quotePoolToken) {
|
|
199
|
+
try {
|
|
200
|
+
quoteLpRaw = await readErc20Balance(provider, quotePoolToken, address);
|
|
201
|
+
}
|
|
202
|
+
catch (error) {
|
|
203
|
+
warnings.push(`pool ${poolId}: failed to read quote LP balance (${extractErrorMessage(error)})`);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
const hasAnyLp = BigInt(baseLpRaw) > 0n || BigInt(quoteLpRaw) > 0n;
|
|
207
|
+
if (!includeZero && !hasAnyLp)
|
|
208
|
+
continue;
|
|
209
|
+
totalBaseLpRaw += BigInt(baseLpRaw);
|
|
210
|
+
totalQuoteLpRaw += BigInt(quoteLpRaw);
|
|
211
|
+
items.push({
|
|
212
|
+
poolId,
|
|
213
|
+
symbol: toSymbol(row),
|
|
214
|
+
state: row?.state ?? row?.poolState ?? null,
|
|
215
|
+
baseSymbol,
|
|
216
|
+
quoteSymbol,
|
|
217
|
+
baseLpAssetName,
|
|
218
|
+
quoteLpAssetName,
|
|
219
|
+
basePoolToken: basePoolToken ?? null,
|
|
220
|
+
quotePoolToken: quotePoolToken ?? null,
|
|
221
|
+
baseLpBalanceRaw: baseLpRaw,
|
|
222
|
+
baseLpBalance: formatUnits(baseLpRaw, COMMON_LP_AMOUNT_DECIMALS),
|
|
223
|
+
quoteLpBalanceRaw: quoteLpRaw,
|
|
224
|
+
quoteLpBalance: formatUnits(quoteLpRaw, COMMON_LP_AMOUNT_DECIMALS),
|
|
225
|
+
hasAnyLp,
|
|
226
|
+
});
|
|
227
|
+
}
|
|
228
|
+
items.sort((left, right) => {
|
|
229
|
+
const leftSum = sumRaw(left.baseLpBalanceRaw, left.quoteLpBalanceRaw);
|
|
230
|
+
const rightSum = sumRaw(right.baseLpBalanceRaw, right.quoteLpBalanceRaw);
|
|
231
|
+
if (leftSum === rightSum)
|
|
232
|
+
return 0;
|
|
233
|
+
return rightSum > leftSum ? 1 : -1;
|
|
234
|
+
});
|
|
235
|
+
const payload = {
|
|
236
|
+
meta: {
|
|
237
|
+
address,
|
|
238
|
+
chainId,
|
|
239
|
+
includeZero,
|
|
240
|
+
requestedPoolIds: poolIdsFilter,
|
|
241
|
+
scannedPools: scannedRows.length,
|
|
242
|
+
totalDiscoveredPools: selectedRows.length,
|
|
243
|
+
maxPools: maxPools ?? null,
|
|
244
|
+
},
|
|
245
|
+
summary: {
|
|
246
|
+
heldPools: items.length,
|
|
247
|
+
totalBaseLpRaw: totalBaseLpRaw.toString(),
|
|
248
|
+
totalBaseLp: formatUnits(totalBaseLpRaw, COMMON_LP_AMOUNT_DECIMALS),
|
|
249
|
+
totalQuoteLpRaw: totalQuoteLpRaw.toString(),
|
|
250
|
+
totalQuoteLp: formatUnits(totalQuoteLpRaw, COMMON_LP_AMOUNT_DECIMALS),
|
|
251
|
+
},
|
|
252
|
+
items,
|
|
253
|
+
};
|
|
254
|
+
if (warnings.length > 0) {
|
|
255
|
+
payload.warnings = warnings.slice(0, 100);
|
|
256
|
+
}
|
|
257
|
+
return {
|
|
258
|
+
content: [{ type: "text", text: JSON.stringify({ status: "success", data: payload }, (_, value) => typeof value === "bigint" ? value.toString() : value, 2) }],
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
catch (error) {
|
|
262
|
+
return { content: [{ type: "text", text: `Error: ${extractErrorMessage(error)}` }], isError: true };
|
|
263
|
+
}
|
|
264
|
+
},
|
|
265
|
+
};
|
package/dist/tools/index.js
CHANGED
|
@@ -31,7 +31,6 @@ export { getPositionsTool } from "./getPositions.js";
|
|
|
31
31
|
export { getOpenOrdersTool, getOrderHistoryTool } from "./orderQueries.js";
|
|
32
32
|
export { getPositionHistoryTool } from "./positionHistory.js";
|
|
33
33
|
export { getAccountTool, getTradeFlowTool } from "./accountInfo.js";
|
|
34
|
+
export { getMyLpHoldingsTool } from "./getMyLpHoldings.js";
|
|
34
35
|
export { getAccountVipInfoTool } from "./getAccountVipInfo.js";
|
|
35
36
|
export { accountDepositTool, accountWithdrawTool } from "./accountTransfer.js";
|
|
36
|
-
export { getMarketListTool } from "./getMarketList.js";
|
|
37
|
-
export { getMarketListRawTool } from "./getMarketListRaw.js";
|
|
@@ -1,12 +1,53 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
2
|
import { quoteDeposit, quoteWithdraw, baseDeposit, baseWithdraw, getLpPrice, } from "../services/poolService.js";
|
|
3
|
-
import { resolveClient } from "../auth/resolveClient.js";
|
|
3
|
+
import { resolveClient, getChainId } from "../auth/resolveClient.js";
|
|
4
4
|
import { resolvePool } from "../services/marketService.js";
|
|
5
5
|
import { finalizeMutationResult } from "../utils/mutationResult.js";
|
|
6
6
|
import { extractErrorMessage } from "../utils/errorMessage.js";
|
|
7
|
+
function normalizeAssetSymbol(value) {
|
|
8
|
+
const text = String(value ?? "").trim();
|
|
9
|
+
if (!text)
|
|
10
|
+
return "";
|
|
11
|
+
return text.replace(/\s+/g, "").replace(/\//g, "").toUpperCase();
|
|
12
|
+
}
|
|
13
|
+
function parsePairSymbols(value) {
|
|
14
|
+
const text = String(value ?? "").trim();
|
|
15
|
+
if (!text)
|
|
16
|
+
return null;
|
|
17
|
+
const parts = text
|
|
18
|
+
.split(/[\/:_-]/)
|
|
19
|
+
.map((item) => normalizeAssetSymbol(item))
|
|
20
|
+
.filter(Boolean);
|
|
21
|
+
if (parts.length >= 2) {
|
|
22
|
+
return { base: parts[0], quote: parts[1] };
|
|
23
|
+
}
|
|
24
|
+
return null;
|
|
25
|
+
}
|
|
26
|
+
function resolveLpAssetNames(detail) {
|
|
27
|
+
let baseSymbol = normalizeAssetSymbol(detail?.baseSymbol ?? detail?.base_symbol);
|
|
28
|
+
let quoteSymbol = normalizeAssetSymbol(detail?.quoteSymbol ?? detail?.quote_symbol);
|
|
29
|
+
if (!baseSymbol || !quoteSymbol) {
|
|
30
|
+
const pairCandidate = detail?.baseQuoteSymbol ?? detail?.symbol ?? detail?.symbolName;
|
|
31
|
+
const parsed = parsePairSymbols(pairCandidate);
|
|
32
|
+
if (parsed) {
|
|
33
|
+
baseSymbol = baseSymbol || parsed.base;
|
|
34
|
+
quoteSymbol = quoteSymbol || parsed.quote;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
const normalizedBase = baseSymbol || null;
|
|
38
|
+
const normalizedQuote = quoteSymbol || null;
|
|
39
|
+
const baseLpAssetName = normalizedBase && normalizedQuote ? `m${normalizedBase}.${normalizedQuote}` : null;
|
|
40
|
+
const quoteLpAssetName = normalizedBase && normalizedQuote ? `m${normalizedQuote}.${normalizedBase}` : null;
|
|
41
|
+
return {
|
|
42
|
+
baseSymbol: normalizedBase,
|
|
43
|
+
quoteSymbol: normalizedQuote,
|
|
44
|
+
baseLpAssetName,
|
|
45
|
+
quoteLpAssetName,
|
|
46
|
+
};
|
|
47
|
+
}
|
|
7
48
|
export const manageLiquidityTool = {
|
|
8
49
|
name: "manage_liquidity",
|
|
9
|
-
description: "Add or withdraw liquidity from a BASE or QUOTE pool.",
|
|
50
|
+
description: "Add or withdraw liquidity from a BASE or QUOTE pool. Success response includes LP naming metadata: base `mBASE.QUOTE`, quote `mQUOTE.BASE`, plus `operatedLpAssetName` based on poolType.",
|
|
10
51
|
schema: {
|
|
11
52
|
action: z.enum(["deposit", "withdraw", "add", "remove", "increase", "decrease"]).describe("'deposit' or 'withdraw' (aliases: add, remove, increase, decrease)"),
|
|
12
53
|
poolType: z.enum(["BASE", "QUOTE"]).describe("'BASE' or 'QUOTE'"),
|
|
@@ -20,23 +61,31 @@ export const manageLiquidityTool = {
|
|
|
20
61
|
const { client, signer } = await resolveClient();
|
|
21
62
|
let { action, poolType, poolId } = args;
|
|
22
63
|
const { amount, slippage } = args;
|
|
64
|
+
const chainId = args.chainId ?? getChainId();
|
|
23
65
|
// 1. Action Alias Mapping
|
|
24
66
|
if (action === "add" || action === "increase")
|
|
25
67
|
action = "deposit";
|
|
26
68
|
if (action === "remove" || action === "decrease")
|
|
27
69
|
action = "withdraw";
|
|
28
70
|
// 2. Smart Pool Resolution (Handles PoolId, Token Address, or Keywords)
|
|
29
|
-
poolId = await resolvePool(client, poolId);
|
|
71
|
+
poolId = await resolvePool(client, poolId, undefined, chainId);
|
|
72
|
+
// 3. Preflight pool validation for target chain (avoid opaque SDK "Invalid Params")
|
|
73
|
+
const detailRes = await client.markets.getMarketDetail({ chainId, poolId }).catch(() => null);
|
|
74
|
+
const detail = detailRes?.data || (detailRes?.marketId ? detailRes : null);
|
|
75
|
+
if (!detail?.marketId) {
|
|
76
|
+
throw new Error(`Pool ${poolId} not found on chainId ${chainId}. ` +
|
|
77
|
+
`Please query a valid active pool via search_market/get_pool_list first.`);
|
|
78
|
+
}
|
|
30
79
|
let raw;
|
|
31
80
|
if (poolType === "QUOTE") {
|
|
32
81
|
raw = action === "deposit"
|
|
33
|
-
? await quoteDeposit(poolId, amount, slippage,
|
|
34
|
-
: await quoteWithdraw(poolId, amount, slippage,
|
|
82
|
+
? await quoteDeposit(poolId, amount, slippage, chainId)
|
|
83
|
+
: await quoteWithdraw(poolId, amount, slippage, chainId);
|
|
35
84
|
}
|
|
36
85
|
else {
|
|
37
86
|
raw = action === "deposit"
|
|
38
|
-
? await baseDeposit(poolId, amount, slippage,
|
|
39
|
-
: await baseWithdraw(poolId, amount, slippage,
|
|
87
|
+
? await baseDeposit(poolId, amount, slippage, chainId)
|
|
88
|
+
: await baseWithdraw(poolId, amount, slippage, chainId);
|
|
40
89
|
}
|
|
41
90
|
if (!raw) {
|
|
42
91
|
throw new Error(`SDK returned an empty result for liquidity ${action}. This usually occurs if the pool is not in an Active state (state: 2) or if there is a contract-level restriction. Please check pool_info.`);
|
|
@@ -45,7 +94,26 @@ export const manageLiquidityTool = {
|
|
|
45
94
|
throw new Error(`Liquidity ${action} failed: ${extractErrorMessage(raw)}`);
|
|
46
95
|
}
|
|
47
96
|
const data = await finalizeMutationResult(raw, signer, "manage_liquidity");
|
|
48
|
-
|
|
97
|
+
const lpAssetNames = resolveLpAssetNames(detail);
|
|
98
|
+
const operatedLpAssetName = poolType === "BASE" ? lpAssetNames.baseLpAssetName : lpAssetNames.quoteLpAssetName;
|
|
99
|
+
const payload = data && typeof data === "object" && !Array.isArray(data)
|
|
100
|
+
? {
|
|
101
|
+
...data,
|
|
102
|
+
lpAssetNames: {
|
|
103
|
+
...lpAssetNames,
|
|
104
|
+
operatedPoolType: poolType,
|
|
105
|
+
operatedLpAssetName,
|
|
106
|
+
},
|
|
107
|
+
}
|
|
108
|
+
: {
|
|
109
|
+
result: data,
|
|
110
|
+
lpAssetNames: {
|
|
111
|
+
...lpAssetNames,
|
|
112
|
+
operatedPoolType: poolType,
|
|
113
|
+
operatedLpAssetName,
|
|
114
|
+
},
|
|
115
|
+
};
|
|
116
|
+
return { content: [{ type: "text", text: JSON.stringify({ status: "success", data: payload }, (_, v) => typeof v === 'bigint' ? v.toString() : v, 2) }] };
|
|
49
117
|
}
|
|
50
118
|
catch (error) {
|
|
51
119
|
return { content: [{ type: "text", text: `Error: ${extractErrorMessage(error)}` }], isError: true };
|
package/package.json
CHANGED
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
import { resolveClient } from "../auth/resolveClient.js";
|
|
2
|
-
import { searchMarket } from "../services/marketService.js";
|
|
3
|
-
import { z } from "zod";
|
|
4
|
-
export const getMarketListTool = {
|
|
5
|
-
name: "get_market_list",
|
|
6
|
-
description: "Get tradable markets/pools (state=2 Active). Supports configurable result limit; backend may still enforce its own cap.",
|
|
7
|
-
schema: {
|
|
8
|
-
limit: z.coerce.number().int().positive().optional().describe("Max results to request (default 1000)."),
|
|
9
|
-
},
|
|
10
|
-
handler: async (args) => {
|
|
11
|
-
try {
|
|
12
|
-
const { client } = await resolveClient();
|
|
13
|
-
const activeMarkets = await searchMarket(client, "", args.limit ?? 1000);
|
|
14
|
-
return { content: [{ type: "text", text: JSON.stringify({ status: "success", data: activeMarkets }, (_, v) => typeof v === 'bigint' ? v.toString() : v, 2) }] };
|
|
15
|
-
}
|
|
16
|
-
catch (error) {
|
|
17
|
-
return { content: [{ type: "text", text: `Error: ${error.message}` }], isError: true };
|
|
18
|
-
}
|
|
19
|
-
},
|
|
20
|
-
};
|
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
import { resolveClient } from "../auth/resolveClient.js";
|
|
2
|
-
export const getMarketListRawTool = {
|
|
3
|
-
name: "get_market_list_raw",
|
|
4
|
-
description: "Get raw market list directly from MYX API without MCP-side filtering.",
|
|
5
|
-
schema: {},
|
|
6
|
-
handler: async () => {
|
|
7
|
-
try {
|
|
8
|
-
const { client } = await resolveClient();
|
|
9
|
-
const result = await client.api.getMarketList();
|
|
10
|
-
return { content: [{ type: "text", text: JSON.stringify({ status: "success", data: result }, (_, v) => typeof v === "bigint" ? v.toString() : v, 2) }] };
|
|
11
|
-
}
|
|
12
|
-
catch (error) {
|
|
13
|
-
return { content: [{ type: "text", text: `Error: ${error.message}` }], isError: true };
|
|
14
|
-
}
|
|
15
|
-
},
|
|
16
|
-
};
|