关于 Polygon MCP Server
Polygon MCP Server 通过钱包、合约、跨链桥、DeFi 和交易模拟工具连接 AI 系统与 Polygon 区块链。开发者可通过标准化 MCP 接口调用这些操作;README 指出,当前模拟实现可能导致跨链桥操作无法正常工作。
主要功能
- 01钱包余额查询与代币转账
- 02合约模板与部署
- 03Ethereum 与 Polygon 跨链操作
- 04QuickSwap、Uniswap V3 和 Polymarket 工具
- 05交易模拟与 Gas 估算
- 06Mainnet 和 Amoy 网络切换
适用场景
- 01查询钱包余额并转移代币
- 02使用支持的模板部署合约
- 03获取兑换报价或使用 DeFi 工具
- 04模拟交易并估算 Gas
MCP 相关
该 MCP 服务注册区块链操作工具,接收客户端请求、验证参数,并返回 Polygon 操作结果。README 提醒,跨链操作当前使用模拟版 MaticPOSClient,可能无法正常运行。
配置
本地服务的配置在各客户端中通用,复制后粘贴到客户端的 MCP 配置文件即可。
我们还没有获取到这个服务的安装包或远程地址,请按项目 README 中的说明安装。
工具
本地服务需要在你的电脑上运行后才能读取工具,维护者暂未提供工具列表。
详细介绍
Polygon MCP 服务
一个与 Polygon 区块链网络无缝集成的模型上下文协议(MCP)服务。此服务使 AI 助手能够通过标准化接口与 Polygon 交互,并提供钱包操作、智能合约部署、L2 桥接、DeFi 交互和交易模拟等全面工具。
目录
简介
Polygon 是 Ethereum 的 Layer 2 扩容解决方案,在保持 Ethereum 安全性的同时提供更快、更便宜的交易。此 MCP 服务允许 AI 助手与 Polygon 网络交互,通过简单、标准化的接口执行各种区块链操作。
该服务充当 AI 系统与 Polygon 区块链之间的桥梁,负责处理区块链交互的复杂性,并为常见操作提供简洁、易用的 API。
┌─────────────┐ ┌───────────────┐ ┌─────────────────┐
│ │ │ │ │ │
│ AI System ├─────┤ Polygon MCP ├─────┤ Polygon Chain │
│ │ │ Server │ │ │
└─────────────┘ └───────────────┘ └─────────────────┘
快速开始
前提条件
- Node.js(v18 或更高版本)
- npm 或 yarn
- Polygon 钱包私钥(用于签署交易)
- Polygon 主网和 Amoy 测试网的 RPC 端点
安装
- 克隆代码仓库或下载源代码
- 安装依赖项:
cd polygonmcp
npm install
- 创建
.env文件,并添加以下变量:
# Network RPC endpoints
POLYGON_MAINNET_RPC=https://polygon-rpc.com
POLYGON_AMOY_RPC=https://rpc-amoy.polygon.technology
ETHEREUM_RPC_URL=https://eth-sepolia.g.alchemy.com/v2/YOUR_ALCHEMY_KEY # Sepolia for Amoy's L1
# API Keys
POLYGONSCAN_API_KEY=YOUR_EXPLORER_API_KEY # Use OKLink API key for Amoy
# Wallet (IMPORTANT: Use secure key management in production)
PRIVATE_KEY=your_private_key_here
DEFAULT_NETWORK=amoy # Use 'amoy' for testnet
# DeFi Configuration (Optional)
DEFAULT_SLIPPAGE=0.5
DEFAULT_DEADLINE_MINUTES=20
运行服务
启动服务:
npm start
开发时启用自动重启:
npm run dev
入门步骤
-
查看钱包余额:
import { PolygonMCPServer } from './polygon-mcp.js'; const server = new PolygonMCPServer(); async function checkBalance() { // Wallet is connected automatically on server start if PRIVATE_KEY is in .env // await server.connectWallet(process.env.PRIVATE_KEY); const balances = await server.listBalances(); console.log('Wallet balances:', balances); } checkBalance().catch(console.error); -
获取测试网 POL(仅限 Amoy 测试网):
async function getTestPol() { // Wallet is connected automatically on server start if PRIVATE_KEY is in .env // await server.connectWallet(process.env.PRIVATE_KEY); const result = await server.getTestnetPol(); console.log('Faucet result:', result); } -
模拟交易:
// Wallet is connected automatically on server start if PRIVATE_KEY is in .env async function simulateTransaction() { const result = await server.simulateTransaction({ to: '0x1234...', // Recipient address value: '0.01', // Amount in MATIC (or native token) }); console.log('Simulation result:', result); }
功能
钱包操作
| 工具 | 描述 | 示例 |
|---|---|---|
get-address | 获取当前钱包地址 | const address = await server.getAddress() |
get-testnet-pol | 从水龙头请求测试网 POL(仅限 Amoy 测试网) | await server.getTestnetPol() |
list-balances | 列出已连接钱包的代币余额 | const balances = await server.listBalances() |
transfer-funds | 向其他地址转入 POL 或 ERC20 代币 | await server.transferFunds('0x1234...', '0.1', 'MATIC') |
钱包管理器提供:
- 增强的钱包连接验证
- 支持多个网络
- 提供详细错误消息的改进型错误处理
- 安全的私钥管理
智能合约操作
| 工具 | 描述 | 示例 |
|---|---|---|
deploy-contract | 在 Polygon 上部署智能合约 | await server.deployContract(name, code, args) |
verify-contract | 在 Polygonscan 上验证已部署的合约 | await server.verifyContract(address, name, code, args) |
list-contract-templates | 列出可用的合约模板 | const templates = await server.listContractTemplates() |
支持的合约类型:
- ERC20 代币
- ERC721 NFT 集合
- ERC1155 多代币
- 质押合约
- 多签钱包
L2 桥接操作
| 工具 | 描述 | 示例 |
|---|---|---|
deposit-eth | 将 ETH 从 Ethereum 存入 Polygon | await server.mcpServer.callTool('deposit-eth', { amount: '0.1' }) |
withdraw-eth | 将 ETH/POL 从 Polygon 提取到 Ethereum | await server.mcpServer.callTool('withdraw-eth', { amount: '0.1' }) |
deposit-token | 将 ERC20 从 Ethereum 存入 Polygon | await server.mcpServer.callTool('deposit-token', { token: 'USDC', amount: '100' }) |
withdraw-token | 将 ERC20 从 Polygon 提取到 Ethereum | await server.mcpServer.callTool('withdraw-token', { token: 'USDC', amount: '100' }) |
check-bridge-status | 检查桥接交易状态(尚未实现为工具) | N/A |
功能:
- 通过
PolygonBridge类支持 ETH 和 ERC20 代币桥接。 - 在
bridge-operations.js中封装MaticPOSClient的使用。 - 增强桥接操作的错误处理。
- 支持检查点(
MaticPOSClient的固有功能)。
**注意:**由于 ESM 兼容性问题,当前实现使用的是 MaticPOSClient 的模拟版本。在创建合适的 ESM 兼容实现之前,桥接操作可能无法正常运行。
DeFi 交互
QuickSwap DEX
| 工具 | 描述 | 示例 |
|---|---|---|
swap-tokens | 使用 QuickSwap 兑换代币 | await server.swapTokens('MATIC', 'USDC', '10') |
get-swap-quote | 获取代币兑换的价格报价 | const quote = await server.getSwapQuote('MATIC', 'USDC', '10') |
add-liquidity | 向 QuickSwap 池添加流动性 | await server.addLiquidity('MATIC', 'USDC', '10', '20') |
Uniswap V3
| 工具 | 描述 | 示例 |
|---|---|---|
uniswapV3SwapSingle | 执行单跳兑换 | await server.uniswapV3SwapSingle(tokenIn, tokenOut, amount, fee) |
uniswapV3SwapMulti | 执行多跳兑换 | await server.uniswapV3SwapMulti(path, amounts) |
getUniswapV3QuoteSingle | 获取单跳兑换的报价 | const quote = await server.getUniswapV3QuoteSingle(tokenIn, tokenOut, amount, fee) |
getUniswapV3QuoteMulti | 获取多跳兑换的报价 | const quote = await server.getUniswapV3QuoteMulti(path, amount) |
Polymarket 预测市场
| 工具 | 描述 | 示例 |
|---|---|---|
getPolymarketInfo | 获取市场信息 | const info = await server.getPolymarketInfo(marketId) |
placePolymarketBet | 通过购买仓位代币下注 | await server.placePolymarketBet(marketId, outcome, amount) |
getPolymarketPositions | 获取用户在某个市场的仓位 | const positions = await server.getPolymarketPositions(marketId) |
交易模拟
| 工具 | 描述 | 示例 |
|---|---|---|
simulate-transaction | 模拟交易以预览其效果 | const result = await server.simulateTransaction(txParams) |
estimate-gas | 估算交易的 Gas | const gas = await server.estimateGas(txParams) |
功能:
- 支持 EIP-1559 的 Gas 估算
- 代币转账检测与分析
- 合约交互模拟
- 增强 BigInt 处理
- 改进错误上下文
网络工具
| 工具 | 描述 | 示例 |
|---|---|---|
get-gas-price | 获取 Polygon 当前 Gas 价格 | const price = await server.getGasPrice() |
switch-network | 在 Polygon 主网和 Amoy 测试网之间切换 | await server.switchNetwork('mainnet') |
架构
Polygon MCP 服务采用模块化架构构建,将不同职责分离,以提升可维护性:
flowchart TD
MCPServer["Polygon MCP Server (polygon-mcp.js)"]
subgraph Modules
BridgeOps["Bridge Operations (bridge-operations.js)"]
ContractOps["Contract Templates (contract-templates.js)"]
DeFiOps["DeFi Interactions (defi-interactions.js)"]
SimOps["Transaction Simulator (transaction-simulation.js)"]
end
subgraph Common ["Common Utilities (common/)"]
WalletManager["Wallet Manager (Singleton)"]
ConfigManager["Configuration Manager"]
Utils["Utility Functions (utils.js)"]
Constants["Constants"]
Logger["Logger (logger.js)"]
Errors["Error Handling (errors.js)"]
Validation["Validation (validation.js)"]
end
MCPServer -- instantiates/uses --> Modules
MCPServer -- uses --> Common
Modules -- use --> Common
核心组件
- Polygon MCP 服务(
polygon-mcp.js):主入口,负责处理 MCP 通信、实例化模块、注册工具并分发调用。 - 通用工具(
common/):- 钱包管理器:用于集中管理钱包状态和访问的单例。
- 配置管理器:用于集中加载配置(
getConfig)的单例。 - 工具函数:共享辅助函数,例如
resolveTokenAddress。 - 常量:共享 ABI、地址。
- 日志记录器、错误处理、验证:支持组件。
- 功能模块:
- 桥接操作(
bridge-operations.js):封装MaticPOSClient和桥接逻辑。 - 合约模板(
contract-templates.js):处理合约编译和基于模板的部署。 - DeFi 交互(
defi-interactions.js):与 DEX(QuickSwap、Uniswap)和 Polymarket 交互。 - 交易模拟器(
transaction-simulation.js):使用eth_call模拟交易。
- 桥接操作(
数据流
- 客户端请求由 MCP 服务接收
- 验证请求并检查参数
- 由相应模块处理请求
- 通过 ethers.js 执行区块链交互
- 格式化结果并返回给客户端
API 参考
钱包操作(通过 MCP 工具)
get-address
获取已连接钱包的地址。
返回: JSON 字符串 { "address": "0x..." }
list-balances
列出已连接钱包(或指定地址)的原生代币和已知代币余额。
参数(可选):
address(string):要查询的地址(默认为已连接的钱包)
返回: JSON 字符串 { "address": "...", "nativeBalance": "...", "tokens": { "USDC": "...", ... } }
transfer-funds
向其他地址转移原生代币(POL)或 ERC20 代币。
参数:
to(string):接收方地址amount(string):转账金额token(string,可选):代币符号或地址(转移原生 POL 时省略)
返回: JSON 字符串 { "success": true, "txHash": "0x...", ... }
合约操作(通过 MCP 工具)
list-contract-templates
列出可用的合约模板。
返回: JSON 字符串 [{ "id": "erc20", "name": "...", ... }, ...]
deploy-contract
根据模板部署合约。
参数:
templateId(string):模板 ID(例如,'erc20'、'nft')params(object):模板特定的参数(例如,{ "name": "MyToken", ... })constructorArgs(Array,可选):合约构造函数的参数
返回: JSON 字符串 { "address": "0x...", "transactionHash": "0x...", ... }
verify-contract(目前未作为 MCP 工具公开)
在 Polygonscan 上验证合约。
参数:
address(string):合约地址name(string):合约名称code(string):合约源代码constructorArgs(Array):构造函数参数
返回: 对象 - 验证结果(如果已实现为工具)
桥接操作(通过 MCP 工具)
deposit-eth
将 ETH 从 Ethereum 存入 Polygon。
参数:
amount(string):要存入的 ETH 数量
返回: JSON 字符串 { "txHash": "0x...", "status": "pending" }
withdraw-eth
将原生代币(POL)从 Polygon 提现至 Ethereum。注意:Polygon 已在主网和测试网上将 MATIC 更名为 POL。
参数:
amount(string):要提现的原生代币(POL)数量
返回: JSON 字符串 { "txHash": "0x...", "status": "pending" }
deposit-token
将 ERC20 代币从 Ethereum 存入 Polygon。
参数:
token(string):代币符号或地址amount(string):要存入的数量
返回: JSON 字符串 { "txHash": "0x...", "status": "pending" }
withdraw-token
将 ERC20 代币从 Polygon 提现到 Ethereum。
参数:
token(字符串):代币符号或地址amount(字符串):提现金额
返回值: JSON 字符串 { "txHash": "0x...", "status": "pending" }
(注意:check-bridge-status 已在 PolygonBridge 中实现,但尚未作为 MCP 工具公开)
高级用法
组合多项操作
// Example: Swap tokens and then bridge to Ethereum (Conceptual using MCP tools)
async function swapAndBridge() {
// Assume server is running and wallet connected via env/config
// Swap MATIC to USDC (using a hypothetical swap tool - needs implementation)
// const swapResult = await server.mcpServer.callTool('swap-tokens', { fromToken: 'MATIC', toToken: 'USDC', amount: '10' });
// console.log('Swap result:', swapResult);
// await server.provider.waitForTransaction(swapResult.content[0].text.txHash); // Wait for swap tx
// Bridge USDC to Ethereum
const bridgeResult = await server.mcpServer.callTool('withdraw-token', { token: 'USDC', amount: '10' });
console.log('Bridge result:', bridgeResult);
}
自定义合约部署
// Deploy a custom ERC20 token using templates (Conceptual using MCP tools)
async function deployCustomToken() {
// Assume server is running and wallet connected via env/config
// Get the ERC20 template info (optional step)
// const templates = await server.mcpServer.callTool('list-contract-templates', {});
// console.log(templates);
// Define parameters
const templateId = 'erc20';
const params = { name: 'MyCustomToken' }; // Name is used in template processing
const constructorArgs = ['MyCustomToken', 'MCT', '1000000000000000000000000']; // Name, Symbol, InitialSupply (in wei)
// Deploy the contract
const deployResult = await server.mcpServer.callTool('deploy-contract', {
templateId,
params,
constructorArgs
});
const deployData = JSON.parse(deployResult.content[0].text);
console.log('Contract deployed at:', deployData.address);
// Verification would need the source code, which isn't directly returned by deploy-contract
// Verification might need a separate tool or manual process.
}
const customizedCode = erc20Template.code
.replace('{{name}}', 'MyCustomToken')
.replace('initialSupply * 10 ** decimals()', '1000000 * 10 ** 18');
// Deploy the contract
const result = await server.deployContract(
'MyCustomToken',
customizedCode,
['MyCustomToken', 'MCT', 1000000]
);
用于安全性的交易模拟
// Simulate a transaction before executing it (Conceptual using MCP tools)
async function safeTransfer() {
// Assume server is running and wallet connected via env/config
const txParams = {
to: '0x1234...',
value: '1000000000000000000', // 1 POL in wei
// data: '0x' // Optional data
};
// Simulate first
const simResult = await server.mcpServer.callTool('simulate-transaction', { transaction: txParams });
const simulation = JSON.parse(simResult.content[0].text);
// Check for issues
if (!simulation.success) {
console.error('Transaction would fail:', simulation.errorMessage);
return;
}
// Check gas costs
console.log('Estimated gas cost:', simulation.gasCost.ether, 'MATIC');
// Execute if simulation was successful (using transfer-funds tool)
const transferResult = await server.mcpServer.callTool('transfer-funds', {
to: txParams.to,
amount: '1.0' // Amount in POL for the tool
});
console.log('Transaction sent:', transferResult);
}
故障排查
当前状态与已知问题
重要提示: 由于 ESM 兼容性问题,当前实现使用的是 MaticPOSClient 的模拟版本。在创建出兼容 ESM 的正式实现之前,桥接操作(存款/提现)可能无法正常运行。
常见问题
“钱包未连接”错误
请确保已在 .env 文件或 MCP 服务配置中正确设置 PRIVATE_KEY。如果提供了密钥,钱包会在服务启动时自动连接。手动调用 connectWallet 已不再是主要方式。
RPC 连接问题
如果遇到 RPC 连接问题,请尝试:
- 检查互联网连接
- 验证
.env文件中的 RPC 端点 URL - 使用其他 RPC 提供商
资金不足
对于需要支付 Gas 费的操作,请确保钱包中有足够的原生代币(POL):
const balances = await server.listBalances();
// Check native token balance (POL)
const nativeToken = 'POL';
console.log(`${nativeToken} balance:`, balances.nativeBalance);
交易失败
发送交易前,使用交易模拟器诊断问题:
const simulation = await server.simulateTransaction(tx);
if (!simulation.success) {
console.error('Transaction would fail:', simulation.errorMessage);
}
调试
通过设置环境变量启用调试日志:
DEBUG=polygon-mcp:*
贡献
欢迎贡献!以下是参与贡献的方式:
- Fork 此仓库
- 创建功能分支:
git checkout -b feature/my-feature - 提交更改:
git commit -am 'Add my feature' - 推送到分支:
git push origin feature/my-feature - 提交拉取请求
开发环境设置
- 克隆仓库
- 安装依赖:
npm install - 创建包含测试凭据的
.env.test文件 - 运行测试:
npm test - 运行代码检查:
npm run lint
安全注意事项
此服务会处理私钥和敏感的区块链操作。用于生产环境时:
- 切勿将私钥存储在代码或环境变量中
- 使用安全的密钥管理系统或硬件钱包集成
- 实施适当的身份验证和授权
- 添加速率限制以防止滥用
- 添加全面的日志记录和监控
- 验证所有输入参数
- 实施适当的错误处理
- 使用安全的配置管理
MCP 集成
添加到 MCP 设置
要在 Claude 或其他兼容 MCP 的系统中使用此服务,请将其添加到 MCP 设置配置文件中:
对于 Cursor/Claude Dev:
{
"mcpServers": {
"polygon": {
"command": "node",
"args": ["path/to/polygon-mcp.js"],
"env": {
"POLYGON_MAINNET_RPC": "https://polygon-rpc.com",
"POLYGON_AMOY_RPC": "https://rpc-amoy.polygon.technology",
"ETHEREUM_RPC_URL": "https://eth-sepolia.g.alchemy.com/v2/YOUR_ALCHEMY_KEY",
"POLYGONSCAN_API_KEY": "YOUR_EXPLORER_API_KEY",
"PRIVATE_KEY": "your_private_key_here",
"DEFAULT_NETWORK": "amoy",
"DEFAULT_SLIPPAGE": "0.5",
"DEFAULT_DEADLINE_MINUTES": "20"
},
"disabled": false,
"autoApprove": []
}
}
}
项目结构
polygon-mcp.js- 主服务实现bridge-operations.js- L2 桥接操作contract-templates.js- 合约部署模板defi-interactions.js- DeFi 协议交互transaction-simulation.js- 交易模拟逻辑。logger.js- 结构化日志工具。errors.js- 自定义错误类和辅助函数。validation.js- 输入验证辅助函数(可能未得到充分使用)。common/- 共享工具和常量:config-manager.js- 集中式配置加载(getConfig)。constants.js- 共享 ABI、地址。wallet-manager.js- 单例钱包管理器。utils.js- 集中式实用函数(例如,resolveTokenAddress)。
许可证
此项目采用 MIT 许可证授权,详情请参阅 LICENSE 文件。
评论
一个开放协议,规定了 AI 应用如何以统一方式连接外部工具与数据源。客户端负责与模型对话,MCP 服务负责提供工具、资源和提示模板,两者通过标准消息通信,同一个服务可以被不同客户端复用。