If you're working on on-chain AI agents or DeFAI apps, then you already know the value of an MCP (Model Context Protocol) server. In this guide, I’ll walk you through how to build a web3 MCP server using Python. This tutorial is aimed at developers comfortable with Python and blockchain integration who want a hands-on example with real code to get started quickly.
Whether you want to deploy an MCP server for Solana-based AI agents or EVM chains, understanding MCP servers can unlock new possibilities for AI-model context handling with blockchain-secured payments.
Let’s skip the fluff and get right to building a minimal but functional Python MCP server.
Before we start, here’s what you'll need:
websockets and requests libraries (we’ll show install commands)Versions of libraries used may change, so always check the official MCP docs and SDK repos for the latest:
pip install websockets requests
If you want to follow along with an example MCP wallet integration or agent payment protocol, see mcp-wallet-integration and mcp-agent-payment-protocols.
An MCP server is an off-chain middleware component that interfaces between on-chain AI agents and external AI model providers. It handles context requests, payment validation, and returns model outputs securely — typically abiding by the MCP protocol specification.
Think of it as a gateway that manages:
I’ve found that running your own server lets you customize timeout policies, fee structures, and even add analytics. Off-the-shelf solutions are great, but building yours gives you full control over security and extensibility.
For an overview of MCP basics, check what-is-mcp.
The first programming step is to scaffold a Python project. Use venv or conda to isolate dependencies. Here's how I typically set up a venv:
python3 -m venv venv
source venv/bin/activate
pip install --upgrade pip
pip install websockets requests
Create a new file mcp_server.py where all main logic will live.
MCP servers often rely on WebSocket for bidirectional communication with agents. Here’s a minimal example using websockets to start a server:
import asyncio
import websockets
import json
async def handle_agent(websocket):
async for message in websocket:
data = json.loads(message)
print(f"Received request: {data}")
# Simple echo response; here, you'd call your AI model or handlers
response = {"id": data.get("id"), "result": "Hello from MCP Server"}
await websocket.send(json.dumps(response))
async def main():
async with websockets.serve(handle_agent, "localhost", 8765):
print("MCP Server running on ws://localhost:8765")
await asyncio.Future() # run forever
if __name__ == "__main__":
asyncio.run(main())
Run this, and you have a TCP WebSocket server listening on port 8765. This obviously lacks blockchain or AI logic, but it sets the groundwork.
Your MCP server needs real-time data about agent wallets and payments. For EVM chains, Web3.py is a practical choice, while for Solana-based chains, the solana-py SDK fits well.
Example with Web3.py for EVM:
from web3 import Web3
w3 = Web3(Web3.HTTPProvider('https://mainnet.infura.io/v3/YOUR_INFURA_KEY'))
# Check connection
if not w3.isConnected():
print("Failed to connect to RPC")
exit(1)
# Example: get ETH balance
address = '0xYourAgentWalletAddress'
balance_wei = w3.eth.get_balance(address)
balance_eth = w3.fromWei(balance_wei, 'ether')
print(f"Agent wallet balance: {balance_eth} ETH")
Replace YOUR_INFURA_KEY and wallet addresses with your testnet setup. This lets the MCP server track agent wallet balances and enforce spending limits before servicing requests.
If you target Solana or others, swap in those SDK calls. See solana-mcp-server-setup for guidance.
Combine the WebSocket server with payment checks. For instance, before allowing your AI model call, verify the agent's wallet payment status.
Here's a simplified example combining Web3 call and request handling:
async def handle_agent(websocket):
async for message in websocket:
data = json.loads(message)
agent_address = data.get('agent_wallet')
# Check agent balance (EVM example only)
balance_wei = w3.eth.get_balance(agent_address)
if balance_wei < w3.toWei(0.01, 'ether'):
response = {"id": data.get("id"), "error": "Insufficient balance"}
await websocket.send(json.dumps(response))
continue
# Your AI model inference here
# Dummy response
model_output = {"text": "AI model response"}
response = {"id": data.get("id"), "result": model_output}
await websocket.send(json.dumps(response))
This is where the meat happens. You can plug in OpenAI APIs, local models, or custom inference backends.
Agent payment integration is a thorny issue. MCP servers often use x402 or ERC-4337 standards to enforce atomic fee deductions.
A practical approach I followed was to verify signed payment receipts on-chain before fulfilling requests. That means your MCP server calls the chain (via RPC) to inspect transaction validity rather than trusting off-chain tokens only.
Example pseudocode for payment verification:
# Pseudo-code; replace with actual ABI calls
payment_verified = check_payment_tx(tx_hash, expected_amount, agent_wallet)
if not payment_verified:
return error_response("Invalid or missing payment")
This step requires familiarity with smart contract ABIs (e.g., ERC-4337 wallet verification) and custom middleware for MCP payment flows. You can find more on payment protocols in mcp-agent-payment-protocols.
Once your MCP server logic is ready, you can run it locally for dev:
python mcp_server.py
For production use, consider a process supervisor (like systemd or Docker).
A typical deployment architecture looks like this:
I switched early on to containerizing the MCP server with Docker for easier scaling and updates.
This isn’t an academic paper but let me quickly flag some real-world footguns:
For a deeper dive into locking down MCP servers, see mcp-server-security-best-practices.
lsof -i :8765 on Unix.curl or web3 CLI.For rapid fixes, mcp-server-troubleshooting is your friend.
| Tool/SDK | Language | Chains | License | Maturity | Notes |
|---|---|---|---|---|---|
| Base MCP Server | Python | EVM, Solana | MIT | Alpha | Simple, minimal, extensible |
| ElizaOS | Python | EVM only | Apache 2 | Beta | With AI model integration layers |
| AgentKit | TypeScript | EVM, Solana | MIT | Early | Agent lifecycle management |
Each has trade-offs; Base MCP Server is great for custom quick starts, but lacks polished payment protocol layers. Pick based on your project scale and language preference.
Now you have a working Python example for a Web3 MCP server skeleton. This approach keeps things explicit and adaptable—key when dealing with blockchain AI infrastructure.
The next steps could be:
For more advanced setups, explore evm-mcp-server-overview or solana-mcp-claude-integration.
When I wired up the agent’s wallet checks and payment validation, I hit race conditions until I layered async locks, so keep testing under load.
If you want to give this a try right away, clone some example repos from GitHub MCP hubs and start customizing. Trust me, building your own MCP server is a solid foundation for any on-chain AI or DeFAI project.