Independent review. This site is not the official website and is not affiliated with, endorsed by, or operated by the wallet vendor reviewed here. Never enter your seed phrase or private keys on any third-party site.

How to Build a Web3 MCP Server Using Python

Get Free Crypto Wallets Network

How to Build a Web3 MCP Server Using Python


Introduction

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.

Prerequisites: Setup and Versions

Before we start, here’s what you'll need:

  • Python 3.10+ (I developed on 3.11, but 3.10 works fine)
  • An accessible blockchain node RPC endpoint (e.g., Alchemy, Infura for EVMs, or a Solana RPC)
  • Basic familiarity with async Python programming
  • 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.

What Is an MCP Server?

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:

  • Agent authentication
  • Session and spending limits
  • Model input/output handling
  • Agent payment processing

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.

Step 1: Initialize Your Python Environment

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.

Step 2: Setting Up Basic MCP Server Logic

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.

Step 3: Connecting to a Blockchain Node (RPC)

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.

Step 4: Handling On-Chain AI Agent Requests

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.

Step 5: Implementing Agent Payment Protocols

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.

Step 6: Running and Deploying Your MCP Server

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:

  • MCP server behind a reverse proxy (NGINX) for TLS termination
  • Access to a managed blockchain RPC node with fallback options
  • Configured environment for secrets (e.g., API keys, private keys)

I switched early on to containerizing the MCP server with Docker for easier scaling and updates.

Security Considerations for MCP Servers

This isn’t an academic paper but let me quickly flag some real-world footguns:

  • Never hardcode private keys. Use environment variables or secure vaults.
  • Be cautious with uncontrolled agent requests—sanitize inputs rigorously.
  • Validate payments on-chain to avoid spoofing.
  • Implement spending limits via session keys or middleware checks.
  • Use TLS and authenticated WebSocket connections.

For a deeper dive into locking down MCP servers, see mcp-server-security-best-practices.

Common Pitfalls and Troubleshooting

  • WebSocket connection refused: Check ports and firewall. Use lsof -i :8765 on Unix.
  • RPC connection issues: Confirm endpoint validity, test with curl or web3 CLI.
  • Asyncio blocking: Don’t run long blocking tasks inside async callbacks; offload to executors.
  • Payment verification failures: Ensure your ABI matches deployed contract versions and your node sync status is current.

For rapid fixes, mcp-server-troubleshooting is your friend.

Comparison Table: Python MCP Server Framework Options

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.

Conclusion and Next Steps

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:

  • Integrate real AI model APIs (like GPT via OpenAI SDK)
  • Enhance payment verification with ERC-4337 wallets
  • Add logging and monitoring
  • Build a frontend dashboard for agent management

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.


Back to MCP Hub Home

Get Free Crypto Wallets Network