Ethereum MCP Server

Ethereum MCP Server

Enables AI agents to interact with Ethereum blockchain by querying ETH and ERC-20 token balances, fetching token prices from CoinGecko, and building/simulating Uniswap V3 swap transactions. Built in Rust with read-only mode by default for safety.

Category
访问服务器

README

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
  • 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

# 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:

# 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

# 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

# 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:

{
  "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)

{
  "jsonrpc": "2.0",
  "method": "tools/call",
  "params": {
    "name": "query_balance",
    "arguments": {
      "address": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
      "tokenAddress": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"
    }
  },
  "id": 1
}

Response (from server to AI client)

{
  "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:

{
  "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:

{
  "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:

{
  "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:

cargo test

Format code:

cargo fmt

Run linter:

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.

推荐服务器

Baidu Map

Baidu Map

百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。

官方
精选
JavaScript
Playwright MCP Server

Playwright MCP Server

一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。

官方
精选
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。

官方
精选
本地
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。

官方
精选
本地
TypeScript
VeyraX

VeyraX

一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。

官方
精选
本地
graphlit-mcp-server

graphlit-mcp-server

模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。

官方
精选
TypeScript
Kagi MCP Server

Kagi MCP Server

一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。

官方
精选
Python
e2b-mcp-server

e2b-mcp-server

使用 MCP 通过 e2b 运行代码。

官方
精选
Neon MCP Server

Neon MCP Server

用于与 Neon 管理 API 和数据库交互的 MCP 服务器

官方
精选
Exa MCP Server

Exa MCP Server

模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。

官方
精选