Alok-cgp/crypto-mcp-server
If you are the rightful owner of crypto-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 dayong@mcphub.com.
A robust Python-based Model Context Protocol (MCP) server for retrieving real-time and historical cryptocurrency market data from major exchanges using CCXT.
Crypto MCP Server
A robust Python-based Model Context Protocol (MCP) server for retrieving real-time and historical cryptocurrency market data from major exchanges using CCXT.
🚀 Features
Core Functionality
- Real-time Data: Live ticker prices, order books, and recent trades
- Historical Data: OHLCV candlestick data with customizable timeframes
- Multi-Exchange Support: Binance, Coinbase, Kraken, Bitfinex, and more
- Smart Caching: Disk-based caching with configurable TTL for optimal performance
- Comprehensive Error Handling: Graceful degradation and detailed error logging
- Type Safety: Full type hints and Pydantic models for configuration
MCP Server Tools (13 Total)
- get_ticker - Current price and 24h statistics
- get_orderbook - Order book depth (bids/asks)
- get_ohlcv - Candlestick data for technical analysis
- get_trades - Recent trade history
- get_markets - List of available trading pairs
- search_symbols - Find symbols by query
- get_24h_stats - 24-hour trading statistics
- get_historical_data - Multi-day historical OHLCV
- get_market_info - Detailed market information
- get_exchange_status - Exchange connectivity status
- get_cache_stats - Cache performance metrics
- clear_cache - Cache management
- get_supported_exchanges - List supported exchanges
📋 Prerequisites
- Python 3.8 or higher
- pip (Python package manager)
- Virtual environment (recommended)
🔧 Installation
1. Clone the Repository
git clone https://github.com/yourusername/crypto-mcp-server.git
cd crypto-mcp-server
2. Create Virtual Environment
# Windows
python -m venv venv
.\venv\Scripts\activate
# Linux/Mac
python3 -m venv venv
source venv/bin/activate
3. Install Dependencies
pip install --upgrade pip
pip install -r requirements.txt
4. Configure Environment
# Copy environment template
cp .env.example .env
# Edit .env with your preferred settings
# (Optional: Add API keys for private endpoints)
🎯 Quick Start
Running the Server
# Start the MCP server
python -m src.server
# Or use the entry point (after installation)
crypto-mcp-server
Basic Usage Example
from src.crypto_client import CryptoClient
# Create client
client = CryptoClient('binance')
# Get current BTC price
ticker = client.get_ticker('BTC/USDT')
print(f"BTC Price: ${ticker['last']}")
# Get historical data
df = client.get_ohlcv('BTC/USDT', timeframe='1d', limit=30)
print(df.head())
# Search for symbols
symbols = client.search_symbols('BTC')
print(f"Found {len(symbols)} BTC pairs")
📁 Project Structure
crypto-mcp-server/
├── src/
│ ├── __init__.py
│ ├── server.py # Main MCP server
│ ├── crypto_client.py # CCXT integration
│ ├── cache_manager.py # Caching layer
│ └── config.py # Configuration management
├── tests/
│ ├── __init__.py
│ ├── test_server.py # Server tests
│ ├── test_crypto_client.py # Client tests
│ ├── test_cache_manager.py # Cache tests
│ └── test_integration.py # Integration tests
├── requirements.txt
├── setup.py
├── .env.example
├── .gitignore
└── README.md
🧪 Testing
Run All Tests
pytest
Run Specific Test File
pytest tests/test_crypto_client.py -v
Run with Coverage
pytest --cov=src --cov-report=html
Test Coverage Summary
- 60+ comprehensive tests
- Cache Manager: 18 tests
- Crypto Client: 20 tests
- MCP Server: 25+ tests
- Integration: 20+ tests
Key Test Areas
✅ Unit tests for all components
✅ Integration tests for end-to-end workflows
✅ Error handling and recovery
✅ Caching behavior and expiration
✅ Data consistency validation
✅ Performance characteristics
✅ Configuration impact
⚙️ Configuration
Environment Variables (.env)
# Cache Configuration
CACHE_ENABLED=true
CACHE_TTL=300 # 5 minutes
CACHE_MAX_SIZE=1000
CACHE_DIR=.cache
# Exchange Configuration
DEFAULT_EXCHANGE=binance
RATE_LIMIT=true
REQUEST_TIMEOUT=30000 # 30 seconds
# Server Configuration
SERVER_HOST=localhost
SERVER_PORT=8000
DEBUG=false
LOG_LEVEL=INFO
# API Keys (Optional)
COINMARKETCAP_API_KEY=your_key_here
Programmatic Configuration
from src.config import config
# Access configuration
print(config.cache.ttl)
print(config.exchange.default_exchange)
# Validate configuration
config.validate_config()
🔌 API Reference
CryptoClient Methods
get_ticker(symbol, use_cache=True)
Get current ticker data for a symbol.
ticker = client.get_ticker('BTC/USDT')
# Returns: {last, bid, ask, high, low, volume, change, ...}
get_orderbook(symbol, limit=20, use_cache=True)
Get order book depth.
orderbook = client.get_orderbook('BTC/USDT', limit=50)
# Returns: {bids: [[price, amount], ...], asks: [[price, amount], ...]}
get_ohlcv(symbol, timeframe='1d', limit=100, use_cache=True)
Get OHLCV candlestick data.
df = client.get_ohlcv('BTC/USDT', timeframe='1h', limit=24)
# Returns: DataFrame with [timestamp, open, high, low, close, volume]
get_historical_data(symbol, timeframe='1d', days=30)
Get multi-day historical data.
df = client.get_historical_data('BTC/USDT', timeframe='1d', days=90)
# Returns: DataFrame with up to 90 days of data
CacheManager Methods
get(key)
Retrieve value from cache.
value = cache_manager.get('my_key')
set(key, value, ttl=None)
Store value in cache.
cache_manager.set('my_key', data, ttl=300)
get_cached_or_fetch(key, fetch_func, *args, **kwargs)
Smart caching pattern.
data = cache_manager.get_cached_or_fetch(
'ticker:BTC',
fetch_function,
'BTC/USDT'
)
🏗️ Architecture
Design Principles
- Separation of Concerns: Each module has a single responsibility
- Dependency Injection: Easy testing with mock objects
- Error Resilience: Comprehensive error handling at all levels
- Performance: Multi-level caching with intelligent TTL
- Extensibility: Easy to add new exchanges or data sources
Component Diagram
┌─────────────────┐
│ MCP Server │ ← Handles tool calls
└────────┬────────┘
│
┌────▼─────┐
│ Client │ ← CCXT integration
└────┬─────┘
│
┌────▼─────┐
│ Cache │ ← Performance layer
└──────────┘
Caching Strategy
- Ticker: 60 seconds TTL (real-time data)
- Orderbook: 30 seconds TTL (high-frequency data)
- OHLCV: 5 minutes TTL (historical data)
- Markets: 1 hour TTL (rarely changes)
- Market Info: 1 hour TTL (static data)
🔍 Troubleshooting
Common Issues
Issue: ModuleNotFoundError: No module named 'mcp'
Solution: Ensure virtual environment is activated and dependencies installed
pip install -r requirements.txt
Issue: ccxt.ExchangeError: Exchange not found
Solution: Check exchange name is correct and supported
from src.config import config
print(config.exchange.supported_exchanges)
Issue: Cache not working
Solution: Check cache directory permissions and CACHE_ENABLED setting
# Check .env file
CACHE_ENABLED=true
Issue: Rate limit errors
Solution: Enable rate limiting in configuration
RATE_LIMIT=true
📊 Performance Benchmarks
Typical response times (with warm cache):
- Ticker: < 10ms
- Orderbook: < 15ms
- OHLCV: < 20ms
- Historical (30 days): < 50ms
Without cache (API calls):
- Ticker: 100-500ms
- Orderbook: 150-600ms
- OHLCV: 200-800ms
🤝 Contributing
Contributions are welcome! Please follow these guidelines:
- Fork the repository
- Create a feature branch (
git checkout -b feature/AmazingFeature) - Write tests for new functionality
- Ensure all tests pass (
pytest) - Commit your changes (
git commit -m 'Add AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
📝 Development Setup
# Install development dependencies
pip install -r requirements.txt
# Run tests with coverage
pytest --cov=src --cov-report=html
# Format code
black src/ tests/
# Lint code
flake8 src/ tests/
# Type checking
mypy src/
🛠️ Technology Stack
- MCP Framework: Model Context Protocol server implementation
- CCXT: Unified cryptocurrency exchange API
- Pandas: Data manipulation and analysis
- Pydantic: Data validation and settings management
- Loguru: Advanced logging
- DiskCache: Persistent caching
- Pytest: Testing framework
📈 Future Enhancements
- WebSocket support for real-time streaming
- More exchange integrations
- Advanced technical indicators
- Portfolio tracking features
- Alerting system
- REST API endpoint wrapper
- Docker containerization
- Kubernetes deployment configs
🔐 Security Considerations
- Never commit API keys to version control
- Use
.envfor sensitive configuration - Enable rate limiting to prevent API abuse
- Validate all user inputs
- Keep dependencies updated
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
👨💻 Author
Your Name
Email: your.email@example.com
GitHub: @yourusername
🙏 Acknowledgments
- CCXT library for unified exchange API
- Anthropic for MCP framework
- Python community for excellent libraries
📞 Support
For issues and questions:
- Open an issue on GitHub
- Email: your.email@example.com
- Documentation: [Link to docs]
📚 Additional Resources
Note: This is an educational project. Always do your own research before making trading decisions. Cryptocurrency trading involves substantial risk.