### Install dependencies Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/README.md Install the required project dependencies using pnpm. ```bash pnpm install ``` -------------------------------- ### Initialize environment configuration Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/README.md Create the .env file from the provided example template. ```bash cp .env.example .env ``` -------------------------------- ### Example MCP Request for okx_get_supported_chains Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/dex-tools.md Example JSON payload for invoking the okx_get_supported_chains tool. ```json { "name": "okx_get_supported_chains" } ``` -------------------------------- ### Get Orders MCP Requests Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/trade-tools.md Example requests for retrieving specific or all orders. ```json { "name": "okx_get_orders", "arguments": { "instId": "BTC-USDT", "ordId": "12345678" } } ``` ```json { "name": "okx_get_orders", "arguments": { "instId": "BTC-USDT" } } ``` -------------------------------- ### Example MCP Requests for okx_get_token_list Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/dex-tools.md Example JSON payloads for invoking the okx_get_token_list tool with and without filters. ```json { "name": "okx_get_token_list" } ``` ```json { "name": "okx_get_token_list", "arguments": { "chainIndex": "1" } } ``` -------------------------------- ### Start the MCP Server Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/README.md Commands to launch the server in production or development mode. ```bash pnpm start # or development mode pnpm dev ``` -------------------------------- ### Get Deposit Address Response Example Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/funding-tools.md Example of the text-formatted JSON response containing address details. ```json { "content": [{ "type": "text", "text": "{\"addr\":\"1A1z7agoat6Rt8D5h1SnFz7QCp6ai4JRSM\",\"chain\":\"BTC\",\"memo\":\"\",...}" }] } ``` -------------------------------- ### Example MCP Request for okx_get_quote Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/dex-tools.md Example JSON payload for invoking the okx_get_quote tool. ```json { "name": "okx_get_quote", "arguments": { "chainIndex": "1", "fromTokenAddress": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", "toTokenAddress": "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2", "amount": "1000000000", "slippage": "1" } } ``` -------------------------------- ### MCP Initialization cURL Request Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/endpoints.md Example command to initialize a new MCP session. ```bash curl -X POST http://localhost:3000/mcp \ -H "Content-Type: application/json" \ -d '{"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {...}}' ``` -------------------------------- ### get(path, params) Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/okx-dex-service.md Sends a generic GET request to the OKX DEX API. ```APIDOC ## GET [path] ### Description Sends a GET request to the OKX DEX API with optional query parameters. ### Parameters - **path** (string) - Required - API path (e.g., /aggregator/quote) - **params** (Object) - Optional - Query parameters as key-value pairs ### Response - **Promise** - Response data from the DEX API ``` -------------------------------- ### Validate Configuration on Startup Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/configuration.md Check for the presence of required OKX API credentials before starting the server. ```javascript if (!config.okx.apiKey || !config.okx.secretKey || !config.okx.passphrase) { console.error("FATAL ERROR: OKX API Key, Secret Key, or Passphrase is not defined..."); process.exit(1); } ``` -------------------------------- ### Get Deposit History MCP Requests Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/funding-tools.md Examples for fetching all deposits or filtering by specific currency and status. ```json { "name": "okx_get_deposit_history" } ``` ```json { "name": "okx_get_deposit_history", "arguments": { "ccy": "BTC", "state": "2" } } ``` -------------------------------- ### Request okx_get_balance Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/dex-tools.md Example MCP request to fetch token balances. ```json { "name": "okx_get_balance", "arguments": { "address": "0x1234567890123456789012345678901234567890", "chains": "1,137" } } ``` -------------------------------- ### Error response structure examples Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/utilities.md JSON examples of error responses with and without additional details. ```json { "success": false, "error": { "mcp_error_code": "NOT_FOUND", "message": "The requested endpoint POST /invalid does not exist." } } ``` ```json { "success": false, "error": { "mcp_error_code": "OKX_API_ERROR", "message": "Order does not exist", "details": { "okx_api_code": "50001", "okx_api_message": "Order does not exist", "okx_error_data": [] } } } ``` -------------------------------- ### Place Order MCP Requests Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/trade-tools.md Example JSON requests for placing market and limit orders. ```json { "name": "okx_place_order", "arguments": { "instId": "BTC-USDT", "tdMode": "cash", "side": "buy", "ordType": "market", "sz": "0.1" } } ``` ```json { "name": "okx_place_order", "arguments": { "instId": "ETH-USDT", "tdMode": "cash", "side": "sell", "ordType": "limit", "sz": "1.0", "px": "2000" } } ``` -------------------------------- ### Request okx_get_price Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/dex-tools.md Example MCP request to fetch the latest token price. ```json { "name": "okx_get_price", "arguments": { "chainIndex": "1", "tokenContractAddress": "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2" } } ``` -------------------------------- ### Example MCP Request for Order History Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/trade-tools.md A sample JSON payload for invoking the okx_get_order_history tool. ```json { "name": "okx_get_order_history", "arguments": { "instType": "SPOT", "instId": "BTC-USDT" } } ``` -------------------------------- ### Request okx_get_kline Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/dex-tools.md Example MCP request to fetch K-line data. ```json { "name": "okx_get_kline", "arguments": { "chainIndex": "1", "tokenContractAddress": "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2", "bar": "1H", "limit": "24" } } ``` -------------------------------- ### Example response transformation Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/utilities.md Demonstrates how raw OKX API data is transformed into the standardized MCP success format. ```javascript // If OKX API returns: { "code": "0", "msg": "", "data": [ { "totalEq": "9999.99", "isoEq": "0", "adjEq": "9999.99", ... } ] } // mcpSuccessResponse wraps the data array: { "success": true, "data": [ { "totalEq": "9999.99", ... } ] } ``` -------------------------------- ### Get Deposit Address MCP Request Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/funding-tools.md Example request to retrieve deposit addresses for Bitcoin. ```json { "name": "okx_get_deposit_address", "arguments": { "ccy": "BTC" } } ``` -------------------------------- ### Example Request Logging Output Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/README.md Sample output format for MCP request and response logging when LOG_LEVEL is set to debug or info. ```text MCP Request IN <-- POST /mcp from 127.0.0.1 MCP Response OUT --> POST /mcp 200 45.123ms ``` -------------------------------- ### Usage of mcpSuccessResponse in controllers Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/utilities.md Example of wrapping OKX API results before sending them to the client. ```javascript const { mcpSuccessResponse } = require('./utils/mcpResponse'); // In a controller const result = await okxService.request('GET', '/api/v5/account/balance'); res.json(mcpSuccessResponse(result.data)); ``` -------------------------------- ### Execute GET Request Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/okx-dex-service.md Sends a GET request to the DEX API. Use this for retrieving market data or supported chains. ```javascript async get(path, params = {}) ``` ```javascript const service = require('./services/okxDexService'); const chains = await service.get('/market/supported/chain'); console.log('Supported chains:', chains); ``` -------------------------------- ### Request Logger Output Examples Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/middleware.md Sample log output generated by the request logger at different log levels. ```text INFO: MCP Request IN <-- POST /mcp from 127.0.0.1 DEBUG: MCP Request Body: {"jsonrpc":"2.0","id":1,...} INFO: MCP Response OUT --> POST /mcp 200 45.123ms ``` -------------------------------- ### OKX Account Info MCP Request Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/account-tools.md Example JSON request for the okx_get_account_info tool. ```json { "name": "okx_get_account_info" } ``` -------------------------------- ### OKX Positions MCP Request Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/account-tools.md Example JSON request for the okx_get_positions tool. ```json { "name": "okx_get_positions", "arguments": { "instType": "SWAP", "instId": "BTC-USDT-SWAP" } } ``` -------------------------------- ### Example OKX Swap MCP Request Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/dex-tools.md JSON payload for invoking the okx_swap tool. ```json { "name": "okx_swap", "arguments": { "chainId": "1", "fromTokenAddress": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", "toTokenAddress": "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2", "amount": "1000000000", "slippage": "1", "userWalletAddress": "0x1234567890123456789012345678901234567890" } } ``` -------------------------------- ### Perform authenticated OKX API requests Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/okx-service.md Examples of fetching account balance and placing a market order using the request method. ```javascript const okxService = require('./services/okxService'); // Get account balance try { const balance = await okxService.request('GET', '/api/v5/account/balance', {}); console.log('Balance:', balance.data); } catch (error) { if (error.isOkxApiError) { console.error(`OKX Error ${error.okxErrorCode}: ${error.okxErrorMessage}`); } else if (error.isNetworkError) { console.error(`Network Error: ${error.message}`); } } // Place a market order try { const order = await okxService.request( 'POST', '/api/v5/trade/order', {}, { instId: 'BTC-USDT', tdMode: 'cash', side: 'buy', ordType: 'market', sz: '0.1' } ); console.log('Order placed:', order.data); } catch (error) { console.error('Order placement failed:', error); } ``` -------------------------------- ### Get Orders Input Schema Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/trade-tools.md Input schema for retrieving order information. ```javascript { instId: { type: "string", description: "Product ID", required: true }, ordId: { type: "string", description: "Order ID" } } ``` -------------------------------- ### Request okx_approve_transaction Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/dex-tools.md Example MCP request to generate an approval transaction. ```json { "name": "okx_approve_transaction", "arguments": { "tokenContractAddress": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", "approveAmount": "1000000000" } } ``` -------------------------------- ### OKX Balance MCP Requests Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/account-tools.md Example JSON requests for the okx_get_balance tool, including specific currency and all-currency variants. ```json { "name": "okx_get_balance", "arguments": { "ccy": "BTC" } } ``` ```json { "name": "okx_get_balance" } ``` -------------------------------- ### Example OKX Cross-Chain Swap MCP Request Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/dex-tools.md JSON payload for invoking the okx_cross_chain_swap tool. ```json { "name": "okx_cross_chain_swap", "arguments": { "fromChainId": "1", "toChainId": "137", "fromTokenAddress": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", "toTokenAddress": "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174", "amount": "1000000000", "slippage": "1.5", "userWalletAddress": "0x1234567890123456789012345678901234567890" } } ``` -------------------------------- ### Define Zod schemas Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/types.md Basic examples of defining string, optional, passthrough, and object schemas using Zod. ```javascript const { z } = require("zod"); // String type z.string() // Optional string z.string().optional() // Passthrough (no validation) z.object({}).passthrough() // Full schema z.object({ field1: z.string(), field2: z.string().optional() }) ``` -------------------------------- ### Request Tradable Instruments Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/market-tools.md Examples of MCP requests for retrieving lists of tradable instruments. ```json { "name": "okx_get_instruments", "arguments": { "instType": "SPOT" } } ``` ```json { "name": "okx_get_instruments", "arguments": { "instType": "SWAP", "uly": "BTC-USD" } } ``` ```json { "name": "okx_get_instruments", "arguments": { "instType": "FUTURES", "uly": "BTC-USD" } } ``` -------------------------------- ### GET /sse Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/endpoints.md Establishes an SSE connection for streaming MCP responses, used in conjunction with the /messages endpoint. ```APIDOC ## GET /sse ### Description Establishes an SSE connection for streaming MCP responses. Used with the /messages endpoint for message submission. ### Method GET ### Endpoint /sse ### Response - **Content-Type** (text/event-stream) - HTTP 200 with server-sent events streamed as data: {...MCP protocol message...}\n\n ``` -------------------------------- ### MCP Subsequent cURL Request Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/endpoints.md Example command to perform an action within an existing session using the mcp-session-id header. ```bash curl -X POST http://localhost:3000/mcp \ -H "Content-Type: application/json" \ -H "mcp-session-id: 550e8400-e29b-41d4-a716-446655440000" \ -d '{"jsonrpc": "2.0", "id": 2, "method": "call_tool", "params": {...}}' ``` -------------------------------- ### Get Deposit History Input Schema Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/funding-tools.md Defines optional filters for currency and deposit status. ```javascript { ccy: { type: "string", description: "Currency" }, state: { type: "string", description: "Status: 0(Waiting for confirmation) 1(Confirmed) 2(Deposit successful)" } } ``` -------------------------------- ### Request K-line Data Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/market-tools.md Examples of MCP requests for retrieving K-line data with different parameters. ```json { "name": "okx_get_kline", "arguments": { "instId": "BTC-USDT", "bar": "1h" } } ``` ```json { "name": "okx_get_kline", "arguments": { "instId": "ETH-USDT", "bar": "1d", "limit": "30" } } ``` -------------------------------- ### Get Deposit Address Input Schema Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/funding-tools.md Defines the required currency parameter for fetching deposit addresses. ```javascript { ccy: { type: "string", description: "Currency, e.g. BTC", required: true } } ``` -------------------------------- ### Usage of mcpErrorResponse in application Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/utilities.md Examples of handling 404s, API errors, and input validation errors using mcpErrorResponse. ```javascript const { mcpErrorResponse } = require('./utils/mcpResponse'); // In app.js for 404 errors res.status(404).json(mcpErrorResponse( 'NOT_FOUND', `The requested endpoint ${req.method} ${req.originalUrl} does not exist.` )); // In error handler res.status(400).json(mcpErrorResponse( 'OKX_API_ERROR', err.okxErrorMessage || 'An error occurred with the OKX API.', { okx_api_code: err.okxErrorCode, okx_api_message: err.okxErrorMessage, okx_error_data: err.okxErrorData } )); // In controller for input validation res.status(400).json(mcpErrorResponse( 'INVALID_MCP_INPUT', 'instrument_id is required.', { expected: 'string', received: 'undefined' }, 400 )); ``` -------------------------------- ### .env.example Template Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/configuration.md Template file containing required OKX API credentials, trading mode, and server settings. ```text # OKX API Configuration OKX_API_KEY=your_okx_api_key OKX_SECRET_KEY=your_okx_secret_key OKX_PASSPHRASE=your_okx_api_password OKX_API_BASE_URL=https://www.okx.com OKX_DEX_API_BASE=https://web3.okx.com/api/v5/dex # Simulated trading: 0 for live trading, 1 for demo account SIMULATED_TRADING=0 # Server Configuration SERVER_PORT=3000 LOG_LEVEL=info ``` -------------------------------- ### Initialize OkxDexService Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/okx-dex-service.md Instantiates the service, which automatically configures the base URL from environment variables or defaults. ```javascript constructor() ``` -------------------------------- ### Initialize MCP server instance Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/mcp-server.md Instantiates the server and prepares it for transport connection. ```javascript const { createServer } = require('./server'); const server = createServer(); // Server is now ready to be connected to a transport (HTTP, SSE, etc.) ``` -------------------------------- ### createServer() Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/mcp-server.md Instantiates and configures a new MCP server instance with all trading, market, and DEX tools registered. ```APIDOC ## createServer() ### Description Creates and configures a new MCP server instance. It registers all available tools across account, funding, market data, trading, and DEX categories, preparing the server to handle requests from MCP clients. ### Signature `function createServer(): McpServer` ### Returns - **McpServer** - A fully initialized MCP server instance with all tools registered and ready to handle requests. ### Example Usage ```javascript const { createServer } = require('./server'); const server = createServer(); ``` ``` -------------------------------- ### Configure environment variables Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/README.md Define OKX API credentials, base URLs, and server settings in the .env file. ```text # OKX API Configuration OKX_API_KEY=your_okx_api_key OKX_SECRET_KEY=your_okx_secret_key OKX_PASSPHRASE=your_okx_api_password OKX_API_BASE_URL=https://www.okx.com OKX_DEX_API_BASE=https://web3.okx.com/api/v5/dex # Simulated trading: 0 for live trading, 1 for demo account SIMULATED_TRADING=0 SERVER_PORT=3000 LOG_LEVEL=info ``` -------------------------------- ### Initiate swap operation Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/okx-dex-service.md Simulates a swap on the OKX DEX. Requires a wallet signature for actual execution. ```javascript async swap(params) ``` -------------------------------- ### GET /health Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/CONTENTS.txt Healthcheck endpoint to verify server status. ```APIDOC ## GET /health ### Description Returns the health status of the server. ### Method GET ### Endpoint /health ``` -------------------------------- ### Configure Development Environment Variables Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/configuration.md Use these settings for demo account testing with simulated trading enabled. ```text OKX_API_KEY=dev-api-key OKX_SECRET_KEY=dev-secret OKX_PASSPHRASE=dev-passphrase SIMULATED_TRADING=1 SERVER_PORT=3000 LOG_LEVEL=debug ``` -------------------------------- ### Cancel Order MCP Request Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/trade-tools.md Example request to cancel a specific order. ```json { "name": "okx_cancel_order", "arguments": { "instId": "BTC-USDT", "ordId": "12345678" } } ``` -------------------------------- ### registerFundingTools(server) Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/funding-tools.md Registers the funding-related MCP tools to the provided server instance, enabling deposit and withdrawal management capabilities. ```APIDOC ## registerFundingTools(server) ### Description Registers all funding-related MCP tools to the server instance. This function configures input validation, descriptions, and error handling for deposit and withdrawal management tools. ### Parameters - **server** (McpServer) - Required - The MCP server instance from @modelcontextprotocol/sdk to which the tools will be registered. ### Usage ```javascript registerFundingTools(server); ``` ``` -------------------------------- ### GET /health Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/endpoints.md Returns server status and current timestamp for monitoring and load balancing. ```APIDOC ## GET /health ### Description Returns server status and current timestamp. ### Method GET ### Endpoint /health ### Response #### Success Response (200) - **status** (string) - Server status (e.g., UP) - **timestamp** (string) - Current timestamp ``` -------------------------------- ### Configure OKX API Key Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/configuration.md Set the OKX V5 API Key for authentication. ```text OKX_API_KEY=your-api-key-here ``` -------------------------------- ### Retrieve Token Price Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/okx-dex-service.md Gets the latest price for a specific token on a given chain. ```javascript async getPrice(params) ``` -------------------------------- ### Configure Production Environment Variables Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/configuration.md Use these settings for live account operations with simulated trading disabled. ```text OKX_API_KEY=prod-api-key OKX_SECRET_KEY=prod-secret OKX_PASSPHRASE=prod-passphrase SIMULATED_TRADING=0 SERVER_PORT=3000 LOG_LEVEL=info ``` -------------------------------- ### Visualize 0xAuto OKX MCP Server Architecture Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/README.md A structural overview of the server's components, including transport layers, application middleware, service clients, and tool registries. ```text 0xAuto OKX MCP Server │ ├─ HTTP Layer │ ├─ StreamableHTTPServerTransport (MCP protocol over HTTP) │ ├─ SSEServerTransport (legacy support) │ └─ Session management │ ├─ Application Layer (Express.js) │ ├─ Middleware │ │ ├─ Request Logger │ │ └─ Global Error Handler │ ├─ Routes │ │ ├─ POST /mcp (main endpoint) │ │ ├─ GET /sse (legacy) │ │ ├─ POST /messages (legacy) │ │ └─ GET /health │ └─ Tools Registry │ ├─ Account tools (3) │ ├─ Trade tools (4) │ ├─ Market tools (3) │ ├─ Funding tools (3) │ └─ DEX tools (9) │ ├─ Service Layer │ ├─ okxService (CEX API client) │ │ ├─ Request signing (HMAC-SHA256) │ │ ├─ Authentication header management │ │ └─ Error transformation │ │ │ └─ okxDexService (DEX API client) │ ├─ Quote retrieval │ ├─ Token listing │ ├─ Price queries │ └─ Swap coordination │ ├─ Controller Layer │ ├─ accountController │ ├─ tradeController │ ├─ fundingController │ └─ marketController │ ├─ Tool Layer │ ├─ accountTools.js │ ├─ tradeTools.js │ ├─ fundingTools.js │ ├─ marketTools.js │ ├─ dexTools.js (orchestration) │ └─ dex/ (9 tool classes) │ └─ Configuration & Utilities ├─ config (environment variables) ├─ mcpResponse (response formatting) └─ constants (API paths) ``` -------------------------------- ### Register Funding Tools Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/funding-tools.md Registers the funding-related MCP tools to the provided server instance. ```javascript function registerFundingTools(server) ``` -------------------------------- ### Withdraw MCP Requests Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/funding-tools.md Examples for performing on-chain withdrawals and internal account transfers. ```json { "name": "okx_withdraw", "arguments": { "ccy": "BTC", "amt": "0.1", "dest": "3", "toAddr": "1A1z7agoat6Rt8D5h1SnFz7QCp6ai4JRSM", "chain": "BTC" } } ``` ```json { "name": "okx_withdraw", "arguments": { "ccy": "USDT", "amt": "1000", "dest": "4", "toAddr": "another_okx_account@example.com" } } ``` -------------------------------- ### Export Singleton Instance Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/okx-dex-service.md Exports the OkxDexService instance as a singleton module. ```javascript module.exports = new OkxDexService(); ``` -------------------------------- ### Enable Simulated Trading Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/configuration.md Set to 1 to enable demo account mode for simulated trading. ```text SIMULATED_TRADING=1 ``` -------------------------------- ### Project File Structure Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/README.md Visual representation of the source directory layout, highlighting the separation of services, controllers, and tool definitions. ```text src/ ├── index.js # Server startup ├── app.js # Express app ├── server.js # MCP server creation ├── config/ │ └── index.js # Configuration loading ├── services/ │ ├── okxService.js # CEX API client │ └── okxDexService.js # DEX API client ├── controllers/ │ ├── accountController.js # Account operations │ ├── tradeController.js # Order operations │ ├── fundingController.js # Deposit/withdrawal │ └── marketController.js # Market data ├── tools/ │ ├── accountTools.js # Account tool registration │ ├── tradeTools.js # Trade tool registration │ ├── fundingTools.js # Funding tool registration │ ├── marketTools.js # Market tool registration │ ├── dexTools.js # DEX tool orchestration │ └── dex/ │ ├── quoteTool.js # Quote tool │ ├── supportedChainsTool.js │ ├── tokenListTool.js │ ├── priceTool.js │ ├── klineTool.js │ ├── balanceTool.js │ ├── approveTool.js │ ├── swapTool.js │ └── crossChainSwapTool.js ├── middleware/ │ ├── requestLogger.js # Request/response logging │ └── errorHandler.js # Error formatting └── utils/ ├── mcpResponse.js # Response helpers └── constants.js # API paths ``` -------------------------------- ### Request Ticker Data Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/market-tools.md Example MCP request to retrieve ticker data for a specific instrument. ```json { "name": "okx_get_ticker", "arguments": { "instId": "BTC-USDT" } } ``` -------------------------------- ### Configure OKX API Base URL Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/configuration.md Set the base URL for the OKX V5 API. ```text OKX_API_BASE_URL=https://www.okx.com ``` -------------------------------- ### Register Account Tools Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/account-tools.md Registers all account-related MCP tools to the provided server instance. ```javascript function registerAccountTools(server) ``` -------------------------------- ### Implement Controller Response Pattern Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/utilities.md Standard pattern for extracting parameters, calling services, and wrapping results in a success response. ```javascript async function controllerMethod(req, res, next) { try { // 1. Extract parameters from request const { param1, param2 } = req.query; // 2. Call service/OKX API const result = await okxService.request('GET', path, params); // 3. Wrap with mcpSuccessResponse res.json(mcpSuccessResponse(result.data)); } catch (error) { // 4. Pass error to error handler next(error); } } ``` -------------------------------- ### Configure Server Port Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/configuration.md Set the port for the HTTP server. ```text SERVER_PORT=3000 ``` -------------------------------- ### Get approval transaction Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/okx-dex-service.md Retrieves transaction details for token approval. Ensure the amount includes the correct token decimals. ```javascript async getApproveTransaction(params) ``` -------------------------------- ### Access Configuration Singleton Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/configuration.md Retrieve configuration values from the loaded singleton object. ```javascript const config = require('./config'); // Access CEX settings config.okx.apiKey config.okx.secretKey config.okx.passphrase config.okx.baseUrl config.okx.simulatedTrading // String: "0" or "1" config.okx.dexApiBase // Access server settings config.server.port // Access logging settings config.log.level ``` -------------------------------- ### Retrieve Supported Chains Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/okx-dex-service.md Returns a list of all chains currently supported by the OKX DEX. ```javascript async getSupportedChains() ``` -------------------------------- ### swap(params) Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/okx-dex-service.md Initiates a swap operation on the OKX DEX. ```APIDOC ## swap(params) ### Description Initiates a swap operation on the OKX DEX. ### Parameters - **params** (Object) - Required - **chainId** (string) - Required - Chain ID - **fromTokenAddress** (string) - Required - Source token contract address - **toTokenAddress** (string) - Required - Target token contract address - **amount** (string) - Required - Amount to swap (must include decimals) - **slippage** (string) - Optional - Slippage tolerance as percentage - **userWalletAddress** (string) - Required - User's wallet address ### Returns - **Promise** - Swap transaction information (simulation; actual execution requires wallet signature) ``` -------------------------------- ### Method Not Allowed Error Response Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/endpoints.md JSON response returned when using unsupported HTTP methods like GET or DELETE on the /mcp endpoint. ```json { "success": false, "error": { "mcp_error_code": "METHOD_NOT_ALLOWED", "message": "Method not allowed." } } ``` -------------------------------- ### Configure OKX DEX API Base URL Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/configuration.md Set the base URL for the public OKX DEX API. ```text OKX_DEX_API_BASE=https://web3.okx.com/api/v5/dex ``` -------------------------------- ### Configure Log Level Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/configuration.md Set the logging verbosity level. ```text LOG_LEVEL=debug ``` -------------------------------- ### Configuration Object Schema Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/types.md Configuration structure defined in src/config/index.js for OKX, server, and logging settings. ```javascript { okx: { apiKey: string, secretKey: string, passphrase: string, baseUrl: string, simulatedTrading: string, // "0" or "1" dexApiBase: string }, server: { port: number | string }, log: { level: string // "debug" or "info" } } ``` -------------------------------- ### Register Market Tools Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/market-tools.md Registers all market data-related MCP tools to the server instance. ```javascript function registerMarketTools(server) ``` -------------------------------- ### okx_swap Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/dex-tools.md Initiates a simulation of an OKX DEX token swap. Returns transaction data, estimated output, gas estimates, and ABI-encoded call data. ```APIDOC ## okx_swap ### Description Initiates an OKX DEX swap simulation. This call provides the necessary transaction data to perform a swap, which must then be signed and submitted by the user's wallet. ### Parameters - **chainId** (string) - Required - Chain ID for the swap - **fromTokenAddress** (string) - Required - Source token contract address - **toTokenAddress** (string) - Required - Target token contract address - **amount** (string) - Required - Amount to swap (with decimals) - **slippage** (string) - Optional - Slippage tolerance as percentage - **userWalletAddress** (string) - Required - User's wallet address ### Request Example { "name": "okx_swap", "arguments": { "chainId": "1", "fromTokenAddress": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", "toTokenAddress": "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2", "amount": "1000000000", "slippage": "1", "userWalletAddress": "0x1234567890123456789012345678901234567890" } } ``` -------------------------------- ### post(path, data) Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/okx-dex-service.md Sends a generic POST request to the OKX DEX API. ```APIDOC ## POST [path] ### Description Sends a POST request to the OKX DEX API with a request body. ### Parameters - **path** (string) - Required - API path (e.g., /aggregator/swap) - **data** (Object) - Optional - Request body to send ### Response - **Promise** - Response data from the DEX API ``` -------------------------------- ### Define okx_get_supported_chains Input Schema Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/dex-tools.md Zod schema definition for the okx_get_supported_chains tool. ```javascript z.object({}).passthrough() ``` -------------------------------- ### request(method, path, queryParams, body) Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/okx-service.md Sends an authenticated HTTP request to the OKX V5 API with automatic signature generation and header management. ```APIDOC ## request(method, path, queryParams, body) ### Description Sends an authenticated HTTP request to the OKX V5 API. It handles timestamp generation, request signing (HMAC-SHA256), and authentication header management. ### Parameters - **method** (string) - Required - HTTP method: 'GET' or 'POST' - **path** (string) - Required - API path (e.g., '/api/v5/account/balance') - **queryParams** (Object) - Optional - Query string parameters as key-value pairs - **body** (Object) - Optional - Request body for POST requests ### Returns - **Promise** - Response data in OKX format: { code: "0", msg: "", data: [...] } ### Error Handling - **OKX API Error**: Throws object with isOkxApiError: true containing okxErrorCode, okxErrorMessage, and okxErrorData - **Network Error**: Throws object with isNetworkError: true containing HTTP status and response data ``` -------------------------------- ### Initiate cross-chain swap Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/okx-dex-service.md Simulates a cross-chain swap operation. Requires valid chain IDs and token addresses for both source and destination. ```javascript async crossChainSwap(params) ``` -------------------------------- ### getSupportedChains() Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/okx-dex-service.md Retrieves information about chains supported by the OKX DEX. ```APIDOC ## getSupportedChains() ### Description Retrieves information about chains supported by the OKX DEX. ### Response - **Promise** - Object containing information about all supported chains ``` -------------------------------- ### OKX Balance Tool Schema and Response Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/account-tools.md Defines the input schema and return format for the okx_get_balance tool. ```javascript { ccy: { type: "string", description: "Currency" } } ``` ```javascript { content: [{ type: "text", text: JSON.stringify(result) }] } ``` -------------------------------- ### Consume Singleton Instance Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/okx-dex-service.md Requires the service module and invokes methods on the singleton instance. ```javascript const okxDexService = require('./services/okxDexService'); // Use the singleton instance directly await okxDexService.getQuote({ ... }); ``` -------------------------------- ### Use OKX API Path Constants Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/utilities.md Import and utilize the path constants within service requests. ```javascript const { OKX_API_PATHS } = require('./services/okxService'); // In a controller const result = await okxService.request( 'GET', OKX_API_PATHS.GET_BALANCE, { ccy: 'BTC' } ); ``` -------------------------------- ### Implement Error Handling for Market Tools Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/market-tools.md Wraps tool operations in try-catch blocks to log errors and throw standardized error messages. ```javascript try { const result = await marketController.method(); return result; } catch (error) { console.error('Operation error:', error); throw new Error(`Operation failed: ${error.message || 'Unknown error'}`); } ``` -------------------------------- ### Register OKX DEX Tools Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/dex-tools.md Registers all OKX DEX-related MCP tools to the server instance. ```javascript function registerOkxDexTools(server) ``` -------------------------------- ### Implement DEX Tool Execution Pattern Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/utilities.md Pattern for DEX tools using Zod validation and returning formatted MCP content. ```javascript async execute(args) { const params = this.inputSchema.parse(args); // Zod validation const result = await okxDexService.method(params); return { content: [{ type: "text", text: JSON.stringify(result) }] }; } ``` -------------------------------- ### Configure OKX Passphrase Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/configuration.md Set the OKX V5 API Passphrase for additional authentication. ```text OKX_PASSPHRASE=your-passphrase-here ``` -------------------------------- ### Configure OKX Secret Key Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/configuration.md Set the OKX V5 API Secret Key for request signing. ```text OKX_SECRET_KEY=your-secret-key-here ``` -------------------------------- ### Define createServer function signature Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/mcp-server.md The function signature for initializing the MCP server instance. ```javascript function createServer() ``` -------------------------------- ### Establish SSE Connection Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/endpoints.md Establishes an SSE connection for streaming MCP responses. Each connection generates a session ID required for subsequent message submissions. ```bash curl -X GET http://localhost:3000/sse ``` -------------------------------- ### OKX Place Order Input Schema Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/trade-tools.md Defines the required input parameters for placing an order on OKX. ```javascript { instId: { type: "string", description: "Product ID, e.g. BTC-USDT", required: true }, tdMode: { type: "string", description: "Trading mode, cash(spot), cross(cross margin), isolated(isolated margin)", required: true }, side: { type: "string", description: "Order side, buy or sell", required: true }, ordType: { type: "string", description: "Order type, market(market price), limit(limit price)", required: true }, sz: { type: "string", description: "Order size", required: true }, px: { type: "string", description: "Order price, only applicable for limit orders" } } ``` -------------------------------- ### OKX Account Info Tool Schema and Response Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/account-tools.md Defines the input schema and return format for the okx_get_account_info tool. ```javascript {} ``` ```javascript { content: [{ type: "text", text: JSON.stringify(result) }] } ``` -------------------------------- ### Define okx_get_order_history Input Schema Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/trade-tools.md Defines the expected input parameters for the order history retrieval tool. ```javascript { instType: { type: "string", description: "Product type, e.g. SPOT" }, instId: { type: "string", description: "Product ID" }, ordType: { type: "string", description: "Order type" } } ``` -------------------------------- ### okx_cross_chain_swap Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/dex-tools.md Initiates a simulation of an OKX DEX cross-chain swap. Returns transaction data, bridge fees, and route details for cross-chain operations. ```APIDOC ## okx_cross_chain_swap ### Description Initiates a cross-chain swap using OKX's cross-chain bridge and DEX. This simulation returns the transaction data required for the user to sign and execute the cross-chain operation. ### Parameters - **fromChainId** (string) - Required - Source chain ID - **toChainId** (string) - Required - Destination chain ID - **fromTokenAddress** (string) - Required - Source token contract address - **toTokenAddress** (string) - Required - Destination token contract address - **amount** (string) - Required - Amount to swap (with decimals) - **slippage** (string) - Optional - Slippage tolerance as percentage - **userWalletAddress** (string) - Required - User's wallet address ### Request Example { "name": "okx_cross_chain_swap", "arguments": { "fromChainId": "1", "toChainId": "137", "fromTokenAddress": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", "toTokenAddress": "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174", "amount": "1000000000", "slippage": "1.5", "userWalletAddress": "0x1234567890123456789012345678901234567890" } } ``` -------------------------------- ### Define OKX API path constants Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/okx-service.md A centralized mapping of OKX V5 API endpoint paths. ```javascript const OKX_API_PATHS = { // Account endpoints GET_BALANCE: '/api/v5/account/balance', GET_POSITIONS: '/api/v5/account/positions', GET_BILLS: '/api/v5/account/bills', // Market endpoints GET_TICKERS: '/api/v5/market/tickers', GET_TICKER: '/api/v5/market/ticker', GET_ORDER_BOOK: '/api/v5/market/books', GET_KLINES: '/api/v5/market/candles', // Trade endpoints PLACE_ORDER: '/api/v5/trade/order', CANCEL_ORDER: '/api/v5/trade/cancel-order', AMEND_ORDER: '/api/v5/trade/amend-order', GET_ORDER_DETAILS: '/api/v5/trade/order', GET_OPEN_ORDERS: '/api/v5/trade/orders-pending', // Funding endpoints GET_DEPOSIT_ADDRESS: '/api/v5/asset/deposit-address', GET_DEPOSIT_HISTORY: '/api/v5/asset/deposit-history', GET_WITHDRAWAL_HISTORY: '/api/v5/asset/withdrawal-history', } ``` -------------------------------- ### OPTIONS /mcp Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/endpoints.md Handles CORS preflight requests for the /mcp endpoint. ```APIDOC ## OPTIONS /mcp ### Description Returns CORS headers for browsers making cross-origin requests. ### Method OPTIONS ### Endpoint /mcp ### Response #### Success Response (200) - **Access-Control-Allow-Origin** (header) - Set to * - **Access-Control-Allow-Methods** (header) - GET, POST, OPTIONS, DELETE - **Access-Control-Allow-Headers** (header) - Content-Type, mcp-session-id ``` -------------------------------- ### Retrieve Swap Quote Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/okx-dex-service.md Fetches estimated output and route details for a token swap. ```javascript async getQuote(params) ``` -------------------------------- ### MCP Tool Return Format Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/market-tools.md Standard return format for MCP tool responses. ```javascript { content: [{ type: "text", text: JSON.stringify(result) }] } ``` -------------------------------- ### MCP Tools Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/README.md List of available MCP tools for CEX and DEX operations. ```APIDOC ## MCP Tools ### CEX Account Tools - okx_get_account_info - okx_get_positions - okx_get_balance ### CEX Trade Tools - okx_place_order - okx_cancel_order - okx_get_orders - okx_get_order_history ### CEX Market Tools - okx_get_ticker - okx_get_kline - okx_get_instruments ### CEX Funding Tools - okx_get_deposit_address - okx_get_deposit_history - okx_withdraw ### DEX Tools - okx_get_quote - okx_get_supported_chains - okx_get_token_list - okx_get_price - okx_get_kline - okx_get_balance - okx_approve_transaction - okx_swap - okx_cross_chain_swap ``` -------------------------------- ### OKX Positions Tool Schema and Response Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/account-tools.md Defines the input schema and return format for the okx_get_positions tool. ```javascript { instType: { type: "string", description: "Instrument type, options: MARGIN, SWAP, FUTURES, OPTION" }, instId: { type: "string", description: "Instrument ID" } } ``` ```javascript { content: [{ type: "text", text: JSON.stringify(result) }] } ``` -------------------------------- ### okx_get_orders Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/trade-tools.md Retrieves information for a specific order or all open orders for a product. ```APIDOC ## MCP Tool: okx_get_orders ### Description Retrieves current order information. Returns details for a specified order or all open orders for a product. ### Parameters - **instId** (string) - Required - Product ID - **ordId** (string) - Optional - Specific order ID ### Request Example { "name": "okx_get_orders", "arguments": { "instId": "BTC-USDT", "ordId": "12345678" } } ``` -------------------------------- ### Register Trade Tools Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/api-reference/trade-tools.md Registers all trade-related MCP tools to the server instance. ```javascript function registerTradeTools(server) ``` -------------------------------- ### Catch-All 404 Error Response Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/endpoints.md Returned when a request is made to an undefined path or method. ```json { "success": false, "error": { "mcp_error_code": "NOT_FOUND", "message": "The requested endpoint {METHOD} {PATH} does not exist." } } ``` -------------------------------- ### POST /mcp Source: https://github.com/buidl-land/0xauto-okx-mcp-server/blob/master/_autodocs/CONTENTS.txt The main MCP endpoint for interacting with the server's tools. ```APIDOC ## POST /mcp ### Description Main MCP endpoint used to execute tools provided by the server. ### Method POST ### Endpoint /mcp ```