merchezattor/dex-mcp-server
If you are the rightful owner of dex-mcp-server and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to henry@mcphub.com.
The DEX MCP Server is a robust and scalable Model Context Protocol server designed to provide access to Binance cryptocurrency market data through a well-architected, modular design.
DEX MCP Server
A robust and scalable Model Context Protocol (MCP) server that provides access to Binance cryptocurrency market data through a well-architected, modular design.
๐๏ธ Architecture
This server follows MCP best practices with a clean, modular architecture:
dex-mcp-server/
โโโ src/ # Main application package
โ โโโ __init__.py # Package metadata
โ โโโ config.py # Configuration management
โ โโโ exceptions.py # Custom exceptions
โ โโโ models.py # Data models and schemas
โ โโโ validators.py # Input validation utilities
โ โโโ server.py # Main server class
โ โโโ clients/ # External API clients
โ โ โโโ __init__.py
โ โ โโโ binance.py # Binance API client
โ โโโ tools/ # MCP tool implementations
โ โ โโโ __init__.py
โ โ โโโ price_tools.py # Price-related tools
โ โ โโโ market_tools.py # Market statistics tools
โ โโโ utils/ # Utility functions
โ โโโ __init__.py
โ โโโ logging.py # Logging configuration
โ โโโ lifecycle.py # Lifecycle management
โโโ main.py # Entry point
โโโ requirements.txt # Dependencies
โโโ README.md # This file
โจ Features
MCP Tools Provided
get_price(symbol="BTCUSDT")
- Get current price for a trading pairget_klines(symbol="BTCUSDT", interval="1h", limit=100)
- Get OHLCV candlestick dataaverage_price(symbol="BTCUSDT", interval="1h", limit=24)
- Calculate average price over N candlesget_24hr_stats(symbol="BTCUSDT")
- Get comprehensive 24hr ticker statistics
Architecture Benefits
- Modular Design: Clean separation of concerns following MCP best practices
- Robust Error Handling: Comprehensive error handling with custom exceptions
- Input Validation: Thorough validation of all inputs with clear error messages
- Connection Pooling: Efficient HTTP session management with connection reuse
- Retry Logic: Automatic retries with exponential backoff for failed requests
- Rate Limiting: Proper handling of API rate limits
- Logging: Structured logging with configurable levels
- Lifecycle Management: Graceful shutdown with proper resource cleanup
- Configuration: Environment-based configuration management
- Type Safety: Full type hints for better IDE support and code quality
๐ Quick Start
Installation
- Clone and setup environment:
git clone <repository-url>
cd dex-mcp-server
python -m venv .venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate
pip install -r requirements.txt
- Run the server:
python main.py
Configuration
The server can be configured via environment variables:
# API Configuration
export BINANCE_API_URL="https://api.binance.com/api/v3"
export API_TIMEOUT="10"
export MAX_RETRIES="3"
export RATE_LIMIT_DELAY="0.1"
# Connection Pool Configuration
export CONNECTION_LIMIT="100"
export CONNECTION_LIMIT_PER_HOST="30"
export DNS_CACHE_TTL="300"
# Server Configuration
export SERVER_NAME="dex-mcp-server"
export SERVER_VERSION="1.0.0"
export LOG_LEVEL="INFO"
Adding to Cursor
Add the server to Cursor via ~/.cursor/mcp.json
:
{
"mcpServers": {
"dex": {
"command": "python",
"args": ["/absolute/path/to/dex-mcp-server/main.py"]
}
}
}
๐งช Development
Project Structure Principles
This project follows established MCP server architecture patterns:
-
Configuration Management (
src/config.py
)- Centralized configuration with environment variable support
- Type-safe configuration classes
- Validation of configuration values
-
Error Handling (
src/exceptions.py
)- Custom exception hierarchy for different error types
- Rich error context for debugging
- Proper error propagation through the stack
-
Data Models (
src/models.py
)- Strongly typed data models using dataclasses
- Conversion methods for external API data
- Validation of data structure integrity
-
Input Validation (
src/validators.py
)- Comprehensive input validation functions
- Clear error messages for invalid inputs
- Security-focused validation patterns
-
External Clients (
src/clients/
)- Abstracted API clients with connection pooling
- Retry logic and error handling
- Rate limiting and timeout management
-
MCP Tools (
src/tools/
)- Organized by functional domain
- Consistent error handling and logging
- Clear documentation and type hints
-
Utilities (
src/utils/
)- Logging configuration and management
- Lifecycle management for graceful shutdown
- Reusable utility functions
Adding New Tools
To add a new MCP tool:
- Create the tool function in the appropriate module under
src/tools/
- Add validation using functions from
src/validators.py
- Handle errors using exceptions from
src/exceptions.py
- Register the tool in the appropriate registration function
- Update the main server to register your new tool category
Example:
# In src/tools/new_category.py
def register_new_tools(server: FastMCP, binance_client: BinanceClient) -> None:
@server.tool()
async def my_new_tool(param: str) -> dict:
# Validate input
param = validate_symbol(param)
# Call API
result = await binance_client.some_method(param)
# Return formatted response
return {"result": result}
# In src/server.py
from .tools import register_new_tools
def _register_tools(self) -> None:
register_price_tools(self.server, self.binance_client)
register_market_tools(self.server, self.binance_client)
register_new_tools(self.server, self.binance_client) # Add this line
Testing
The modular architecture makes testing straightforward:
# Example test structure
import pytest
from src.validators import validate_symbol
from src.exceptions import ValidationError
def test_validate_symbol():
# Test valid symbol
assert validate_symbol("BTCUSDT") == "BTCUSDT"
# Test invalid symbol
with pytest.raises(ValidationError):
validate_symbol("invalid")
๐ฆ Dependencies
- fastmcp: MCP framework for Python
- aiohttp: Async HTTP client for API requests
- uvloop: High-performance event loop (Unix only)
๐ง Environment Variables
Variable | Default | Description |
---|---|---|
BINANCE_API_URL | https://api.binance.com/api/v3 | Binance API base URL |
API_TIMEOUT | 10 | Request timeout in seconds |
MAX_RETRIES | 3 | Maximum retry attempts |
RATE_LIMIT_DELAY | 0.1 | Base delay between retries |
CONNECTION_LIMIT | 100 | Total connection pool size |
CONNECTION_LIMIT_PER_HOST | 30 | Connections per host |
DNS_CACHE_TTL | 300 | DNS cache TTL in seconds |
SERVER_NAME | dex-mcp-server | Server identification |
SERVER_VERSION | 1.0.0 | Server version |
LOG_LEVEL | INFO | Logging level |
๐ค Contributing
This architecture makes contributions easier:
- Fork the repository
- Create a feature branch
- Add your changes following the established patterns
- Add tests for new functionality
- Submit a pull request
๐ License
[Add your license information here]
๐ Acknowledgments
Built following MCP best practices and inspired by the AWS MCP Servers project architecture.