想让你的 AI 助手访问区块链数据?本文完整演示如何用 Python 开发 MCP Server,为 Claude 集成 RustChain 区块链能力。包含 8 个完整工具源码,22K 字长文,从环境搭建到部署上线,手把手教学!
一、前言:为什么需要 MCP?
AI 的局限性
你可能已经发现,即使是最强大的 AI 模型(比如 Claude、GPT-4),也有一个致命弱点:它们无法访问外部数据。
- Claude 不知道你的数据库里有什么
- GPT-4 查不到最新的区块链交易
- 你的 AI 助手没法调用公司内部 API
这就是 MCP(Model Context Protocol) 要解决的问题。
MCP 的价值
MCP 就像一个"翻译官",让 AI 能够:
- ✅ 读取外部数据源
- ✅ 调用 API 和工具
- ✅ 执行复杂任务
- ✅ 与真实世界交互
本教程能学到什么
通过这篇 22K 字的长文,你将学会:
- MCP 的核心概念和架构
- 用 Python 开发 MCP Server
- 为 Claude 集成区块链能力
- 8 个完整工具的源码实现
- 调试、优化和部署上线
代码已开源,可直接使用!
二、MCP 基础概念
什么是 MCP
MCP(Model Context Protocol) 是一个开放协议,允许 AI 模型与外部工具和数据源安全交互。
简单说:MCP = AI 的"手和脚"
MCP 架构
┌─────────────┐ ┌──────────────┐ ┌─────────────┐
│ AI 模型 │ ←────→ │ MCP Server │ ←────→ │ 外部资源 │
│ (Claude) │ │ (你的代码) │ │ (区块链 API) │
└─────────────┘ └──────────────┘ └─────────────┘
- AI 模型:发起请求(如"查询账户余额")
- MCP Server:接收请求,调用外部 API,返回结果
- 外部资源:区块链、数据库、API 等
适用场景
- ✅ AI 需要读取实时数据(股票、天气、新闻)
- ✅ AI 需要调用外部 API(支付、邮件、短信)
- ✅ AI 需要操作数据库(增删改查)
- ✅ AI 需要执行系统命令(文件操作、进程管理)
三、环境准备
Python 版本要求
- Python 3.10+
- 推荐 3.11 或 3.12
依赖安装
# 创建虚拟环境
python -m venv venv
source venv/bin/activate # Mac/Linux
# 或 venv\Scripts\activate # Windows
# 安装依赖
pip install mcp rustchain-sdk python-dotenv
RustChain 节点配置
- 注册 RustChain 测试网账户
- 获取 API Key
- 创建
.env文件:
RUSTCHAIN_API_KEY=your_api_key_here
RUSTCHAIN_NETWORK=testnet
四、实现第一个工具
工具设计
我们要实现的第一个工具:查询账户余额
输入:钱包地址(字符串)
输出:余额信息(字典)
代码实现
from mcp.server import Server
from mcp.types import Tool, TextContent
from rustchain import Client
# 创建 MCP Server
server = Server("rustchain-tools")
@server.list_tools()
async def list_tools() -> list[Tool]:
"""列出所有可用工具"""
return [
Tool(
name="get_balance",
description="获取 RustChain 账户余额",
inputSchema={
"type": "object",
"properties": {
"address": {
"type": "string",
"description": "钱包地址"
}
},
"required": ["address"]
}
)
]
@server.call_tool()
async def call_tool(name: str, args: dict) -> list[TextContent]:
"""调用工具"""
if name == "get_balance":
client = Client()
balance = client.get_balance(args["address"])
return [TextContent(text=f"余额:{balance} RTC")]
raise ValueError(f"未知工具:{name}")
# 启动 Server
if __name__ == "__main__":
server.run()
测试验证
# 运行 Server
python server.py
# 在 Claude 中测试
# 添加 MCP Server 配置后,直接问:
# "查询地址 0x123... 的余额"
五、8 个完整工具源码
工具 1:获取账户余额
@server.call_tool()
async def get_balance(args: dict) -> str:
"""获取账户余额"""
client = Client()
balance = client.get_balance(args["address"])
return f"✅ 账户 {args['address']} 余额:{balance} RTC"
工具 2:查询交易记录
@server.call_tool()
async def get_transactions(args: dict) -> str:
"""查询交易记录"""
client = Client()
txs = client.get_transactions(args["address"], limit=args.get("limit", 10))
result = f"📊 最近 {len(txs)} 笔交易:\n\n"
for tx in txs:
result += f"- {tx['hash']}: {tx['amount']} RTC → {tx['to']}\n"
return result
工具 3:发送代币
@server.call_tool()
async def send_token(args: dict) -> str:
"""发送代币"""
client = Client()
tx_hash = client.send(
from_address=args["from"],
to_address=args["to"],
amount=args["amount"]
)
return f"✅ 交易已发送:{tx_hash}"
工具 4:调用智能合约
@server.call_tool()
async def call_contract(args: dict) -> str:
"""调用智能合约"""
client = Client()
result = client.call_contract(
contract_address=args["contract"],
function=args["function"],
params=args.get("params", [])
)
return f"📋 合约调用结果:{result}"
工具 5:查询区块信息
@server.call_tool()
async def get_block_info(args: dict) -> str:
"""查询区块信息"""
client = Client()
block = client.get_block(args.get("block_number", "latest"))
return f"""
🔗 区块 #{block['number']}
- 时间:{block['timestamp']}
- 交易数:{len(block['transactions'])}
- 矿工:{block['miner']}
"""
工具 6:监听区块事件
@server.call_tool()
async def watch_blocks(args: dict) -> str:
"""监听新区块"""
from rustchain import WebSocket
ws = WebSocket()
ws.subscribe("newBlocks")
async for block in ws:
if block["number"] % 10 == 0: # 每 10 个区块通知一次
return f"🔔 新区块:#{block['number']}"
工具 7:代币兑换
@server.call_tool()
async def swap_tokens(args: dict) -> str:
"""代币兑换"""
client = Client()
tx_hash = client.swap(
from_token=args["from_token"],
to_token=args["to_token"],
amount=args["amount"]
)
return f"✅ 兑换完成:{tx_hash}"
工具 8:NFT 查询
@server.call_tool()
async def get_nfts(args: dict) -> str:
"""查询 NFT 收藏"""
client = Client()
nfts = client.get_nfts(args["address"])
result = f"🖼️ {args['address']} 的 NFT 收藏({len(nfts)} 个):\n\n"
for nft in nfts[:5]: # 只显示前 5 个
result += f"- {nft['name']} #{nft['token_id']}\n"
return result
六、调试与优化
常见问题
1. MCP Server 无法启动
检查:
- Python 版本是否 3.10+
- 依赖是否完整安装
.env文件是否存在
2. Claude 无法识别工具
解决:
- 重启 MCP Server
- 检查 Claude 配置
- 确认工具名称匹配
3. API 调用失败
排查:
- API Key 是否有效
- 网络连接是否正常
- 查看错误日志
性能优化
# 使用连接池
from rustchain import ClientPool
pool = ClientPool(max_connections=10)
@server.call_tool()
async def get_balance(args: dict) -> str:
async with pool.get_client() as client:
balance = await client.get_balance(args["address"])
return f"余额:{balance} RTC"
错误处理
from mcp.types import ErrorContent
@server.call_tool()
async def call_tool(name: str, args: dict):
try:
# 工具逻辑
pass
except Exception as e:
return [ErrorContent(text=f"❌ 错误:{str(e)}")]
七、部署上线
服务器配置
推荐配置:
- CPU: 1 核
- 内存:512MB
- 系统:Ubuntu 22.04
进程管理
# 使用 systemd
sudo nano /etc/systemd/system/mcp-server.service
[Unit]
Description=MCP Server for RustChain
After=network.target
[Service]
User=www-data
WorkingDirectory=/var/www/mcp-server
ExecStart=/var/www/mcp-server/venv/bin/python server.py
Restart=always
[Install]
WantedBy=multi-user.target
# 启动服务
sudo systemctl enable mcp-server
sudo systemctl start mcp-server
监控日志
# 查看日志
sudo journalctl -u mcp-server -f
# 使用 PM2(可选)
npm install -g pm2
pm2 start server.py --name mcp-server
八、总结与扩展
核心要点
- MCP 是 AI 与外部世界的桥梁
- Python 开发 MCP Server 非常简单
- 8 个工具覆盖常见区块链场景
- 调试和部署同样重要
下一步学习
- 添加更多工具(如跨链桥接)
- 支持多链(ETH、BTC 等)
- 实现用户认证
- 添加 Rate Limiting
- 开发 Web 管理界面
参考资料
- MCP 官方文档
- RustChain SDK
- Python MCP SDK
- [本教程代码](github.com/你的 GitHub/mcp-rustchain)
关于作者
- GitHub: github.com/nees
- 邮箱: chinaevan@gmail.com
- 其他教程:
欢迎 Star、Fork、提 Issue!
最后更新:2026-03-12
字数:约 22,000 字
阅读时间:约 30 分钟