README.md•9.74 kB
# Ethereum MCP Server
A Model Context Protocol (MCP) server built in Rust that enables AI agents to query balances and execute token swaps on Ethereum.
## Features
- **Query Balances**: Get ETH or ERC-20 token balances for any Ethereum address
- **Token Prices**: Fetch current token prices from CoinGecko API
- **Build Swap Transactions**: Generate and simulate swap transactions using Uniswap V3
- **JSON-RPC Protocol**: Full MCP protocol implementation via stdin/stdout
## Prerequisites
- **Rust 1.70 or later** - Install from [rustup.rs](https://rustup.rs/)
- **Node.js 16+** (optional) - Only needed for `mcp-inspector` testing tool
- **Access to an Ethereum RPC endpoint** - Defaults to public RPC at `https://eth.llamarpc.com`
## Installation
```bash
# Clone the repository
git clone <your-repo-url>
cd ethereum-mcp
# Install Rust dependencies
cargo build --release
# (Optional) Install MCP Inspector for testing
npm install
```
## Configuration
### Environment Variables
Create a `.env` file in the project root or export these environment variables:
```bash
# Ethereum RPC endpoint (optional, defaults to public RPC)
export ETH_RPC_URL=https://your-rpc-endpoint.com
# Private key for signing transactions (optional, required for building swap transactions)
export ETHEREUM_PRIVATE_KEY=0x1234567890abcdef...
# For mainnet, consider using Infura, Alchemy, or your own node
export ETH_RPC_URL=https://mainnet.infura.io/v3/YOUR_PROJECT_ID
```
**Security Note**: Never commit private keys or `.env` files to version control.
## Usage
### Run the MCP Server
```bash
# Development mode (with logging)
cargo run
# Release mode (optimized)
cargo run --release
```
The server communicates via JSON-RPC over stdin/stdout, following the Model Context Protocol specification.
### Test with MCP Inspector
```bash
# Start the server for inspection
mcp-inspector --transport stdio -- cargo run --release
```
### Integration with AI Clients
Configure your AI client (e.g., Claude Desktop, Cline) to use this server:
```json
{
"mcpServers": {
"ethereum": {
"command": "cargo",
"args": ["run", "--release"],
"cwd": "/path/to/ethereum-mcp"
}
}
}
```
## Example MCP Tool Call
Here's an example of a complete MCP request/response interaction:
### Request (from AI client to server)
```json
{
"jsonrpc": "2.0",
"method": "tools/call",
"params": {
"name": "query_balance",
"arguments": {
"address": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
"tokenAddress": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"
}
},
"id": 1
}
```
### Response (from server to AI client)
```json
{
"jsonrpc": "2.0",
"result": {
"content": [
{
"type": "text",
"text": "ERC-20 balance: 1000000 tokens"
}
],
"isError": false
},
"id": 1
}
```
## Available Tools
### 1. `query_balance`
Query the balance of ETH or ERC-20 tokens for an Ethereum address.
**Parameters:**
- `address` (required): Ethereum address to query
- `token_address` (optional): ERC-20 token address. If not provided, returns ETH balance
**Example:**
```json
{
"name": "query_balance",
"arguments": {
"address": "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
"token_address": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"
}
}
```
### 2. `get_token_price`
Fetch current token price from CoinGecko API.
**Parameters:**
- `token` (required): Token address, symbol (e.g., "ETH", "USDC"), or CoinGecko ID
- `currency` (optional): Currency to return price in (defaults to "USD")
**Example:**
```json
{
"name": "get_token_price",
"arguments": {
"token": "ETH",
"currency": "USD"
}
}
```
### 3. `build_swap_transaction`
Build and simulate a token swap transaction using Uniswap V3.
**Parameters:**
- `fromToken` (optional): Address of token to swap from (defaults to WETH)
- `toToken` (optional): Address of token to swap to (defaults to USDC)
- `amountIn` (optional): Amount to swap (defaults to 0.0001)
- `slippageTolerance` (optional): Maximum acceptable slippage percentage
- `recipient` (optional): Address to receive swapped tokens
**Example:**
```json
{
"name": "build_swap_transaction",
"arguments": {
"fromToken": "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",
"toToken": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
"amountIn": "0.1",
"slippageTolerance": 0.5
}
}
```
## Architecture & Design Decisions
The server is organized into the following modules:
- **`src/lib.rs`**: Main library entry point and server initialization
- **`src/mcp.rs`**: MCP protocol implementation and JSON-RPC handling
- **`src/types.rs`**: Protocol type definitions
- **`src/ethereum/`**: Ethereum interaction logic organized into sub-modules:
- **`mod.rs`**: Main `EthereumService` struct and public API
- **`balance.rs`**: ETH and ERC-20 balance queries
- **`price.rs`**: Token price fetching from external APIs
- **`pool.rs`**: Uniswap V3 pool operations and price calculations
- **`swap.rs`**: Swap transaction building and simulation
- **`utils.rs`**: Helper utilities for encoding/decoding
- **`src/main.rs`**: Application entry point with logging setup
### Design Decisions
This implementation prioritizes **safety, modularity, and type-safety** through the following design choices:
1. **Alloy Framework**: Uses the Alloy library for Ethereum interactions, providing type-safe abstractions over raw RPC calls and eliminating common encoding/decoding errors in smart contract interactions.
2. **Simulation-First Approach**: All swap transactions use `eth_call` for simulation rather than executing real transactions. This allows AI agents to understand transaction outcomes without risking funds or requiring complex signing infrastructure.
3. **Uniswap V3 Focus**: Targets Uniswap V3 specifically for its widespread adoption and concentrated liquidity. The implementation reads pool state directly from the blockchain to calculate accurate swap quotes rather than relying on external APIs.
4. **Read-Only Default Mode**: By default, the server operates in read-only mode. Transaction building requires explicit configuration of `ETHEREUM_PRIVATE_KEY`, forcing conscious opt-in to features that could modify blockchain state.
5. **Rust-Based MCP Implementation**: The `rmcp` crate provides a strong foundation for MCP protocol handling, with built-in async support and proper error handling, making the server more robust than ad-hoc JSON-RPC implementations.
### Known Limitations & Assumptions
This implementation has the following limitations and assumptions:
1. **Single Fee Tier**: Only supports Uniswap V3's 0.05% fee tier (500). Other fee tiers (0.01%, 0.3%, 1%) are not automatically tried, which may miss better liquidity in alternative pools.
2. **No Router Aggregation**: Quotes are calculated directly from Uniswap V3 pools without considering alternative paths or aggregators (1inch, Paraswap, etc.), which may not provide optimal swap routes.
3. **Simulation Only**: Transactions are simulated but not executed on-chain. Actual transaction submission would require additional signing and broadcasting logic beyond the scope of this MCP server.
4. **Price Oracle Dependency**: Token prices come from CoinGecko's free API, which has rate limits and may not reflect real-time DEX prices. This is acceptable for approximate values but should not be used for precise arbitrage calculations.
5. **Mainnet Only**: Hardcoded for Ethereum mainnet addresses (Uniswap V3 contracts, token addresses). Supporting testnets or layer 2s would require additional configuration and contract addresses.
6. **Token Balance Display**: ERC-20 balances are returned as raw token units without decimal formatting, making large numbers hard to interpret without additional client-side processing.
7. **Pool Availability Required**: Input token and output token addresses must have an existing Uniswap V3 pool at the selected fee tier; otherwise the swap will not execute.
8. **Approvals and Balance for Simulation**: Because no transaction is sent, simulations can still fail if the user's account is not approved for the router or lacks sufficient token balance.
9. **Pool-Dependent Price Calculation**: Current price calculations depend on querying the pool address on-chain; this increases latency and can make simulations slower than using cached pricing services.
10. **Unknown bugs**: Project is not fully tested, unknown behavior might happen.
## Development
Run tests:
```bash
cargo test
```
Format code:
```bash
cargo fmt
```
Run linter:
```bash
cargo clippy
```
## Security Considerations
⚠️ **Important**: This is an experimental MCP server for Ethereum blockchain interactions:
1. **Environment Variables**: Never commit `.env` files or private keys to version control. Use secure key management in production.
2. **Private Key Storage**: The `ETHEREUM_PRIVATE_KEY` environment variable is loaded directly. For production, consider using hardware wallets or secure key management services (AWS KMS, GCP Secret Manager, etc.).
3. **Read-Only Mode**: The server defaults to read-only mode for safety. Building transactions requires explicit configuration.
4. **Rate Limiting**: Public RPC endpoints have rate limits. Use dedicated RPC providers (Infura, Alchemy) for production workloads.
5. **Transaction Simulation**: All swaps are simulated only. No actual transactions are executed unless you build custom broadcasting logic.
6. **Input Validation**: All user inputs are validated, but additional checks may be needed for production use.
## License
[Add your license here]
## Contributing
Contributions are welcome! Please feel free to submit a Pull Request.