Polygon Blockchain MCP server

Integrates with the Polygon blockchain network to enable wallet operations, smart contract deployments, L2 bridging, DeFi interactions, and transaction simulations using ethers.js v6 across both Mainnet and Mumbai Testnet environments.
Back to servers
Setup instructions
Provider
Dbillionaer
Release date
Mar 13, 2025
Language
TypeScript
Stats
4 stars

The Polygon MCP Server provides a standardized interface for AI assistants to interact with the Polygon blockchain network, enabling various operations like wallet management, smart contract deployment, L2 bridging, DeFi interactions, and transaction simulations.

Installation

Prerequisites

  • Node.js (v18 or higher)
  • npm or yarn
  • A Polygon wallet private key (for signing transactions)
  • RPC endpoints for Polygon Mainnet and Amoy Testnet

Setup Instructions

  1. Clone the repository or download the source code
  2. Install dependencies:
cd polygonmcp
npm install
  1. Create a .env file with the following variables:
# 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  

# 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

Running the Server

Start the server:

npm start

For development with auto-restart:

npm run dev

Basic Usage

Check Your Wallet Balance

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
  const balances = await server.listBalances();
  console.log('Wallet balances:', balances);
}

checkBalance().catch(console.error);

Get Testnet POL (Amoy Testnet Only)

async function getTestPol() {
  // Wallet is connected automatically when PRIVATE_KEY is in .env
  const result = await server.getTestnetPol();
  console.log('Faucet result:', result);
}

Simulate a Transaction

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);
}

Supported Features

Wallet Operations

Tool Description Example
get-address Retrieve the current wallet address const address = await server.getAddress()
get-testnet-pol Request testnet POL from a faucet (Amoy testnet only) await server.getTestnetPol()
list-balances List token balances for the connected wallet const balances = await server.listBalances()
transfer-funds Transfer POL or ERC20 tokens to another address await server.transferFunds('0x1234...', '0.1', 'MATIC')

Smart Contract Operations

Tool Description Example
deploy-contract Deploy a smart contract to Polygon await server.deployContract(name, code, args)
verify-contract Verify a deployed contract on Polygonscan await server.verifyContract(address, name, code, args)
list-contract-templates List available contract templates const templates = await server.listContractTemplates()

L2 Bridge Operations

Tool Description Example
deposit-eth Deposit ETH from Ethereum to Polygon await server.mcpServer.callTool('deposit-eth', { amount: '0.1' })
withdraw-eth Withdraw ETH/POL from Polygon to Ethereum await server.mcpServer.callTool('withdraw-eth', { amount: '0.1' })
deposit-token Deposit ERC20 from Ethereum to Polygon await server.mcpServer.callTool('deposit-token', { token: 'USDC', amount: '100' })
withdraw-token Withdraw ERC20 from Polygon to Ethereum await server.mcpServer.callTool('withdraw-token', { token: 'USDC', amount: '100' })

DeFi Interactions

QuickSwap DEX

// Swap MATIC for USDC
const result = await server.swapTokens('MATIC', 'USDC', '10');

// Get a price quote for a token swap
const quote = await server.getSwapQuote('MATIC', 'USDC', '10');

// Add liquidity to a QuickSwap pool
await server.addLiquidity('MATIC', 'USDC', '10', '20');

Uniswap V3

// Execute single-hop swap
await server.uniswapV3SwapSingle(tokenIn, tokenOut, amount, fee);

// Get quote for single-hop swap
const quote = await server.getUniswapV3QuoteSingle(tokenIn, tokenOut, amount, fee);

Transaction Simulation

// Simulate a transaction
const result = await server.simulateTransaction({
  to: '0x1234...',
  value: '0.01', 
  data: '0x...' // Optional contract interaction data
});

// Estimate gas
const gas = await server.estimateGas({
  to: '0x1234...',
  value: '0.01'
});

Advanced Usage

Custom Contract Deployment

// Deploy a custom ERC20 token
async function deployCustomToken() {
  // Define parameters
  const templateId = 'erc20';
  const params = { name: 'MyCustomToken' }; 
  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);
}

Transaction Simulation for Security

// Simulate a transaction before executing it
async function safeTransfer() {
  const txParams = {
    to: '0x1234...',
    value: '1000000000000000000', // 1 POL in wei
  };

  // 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
  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);
}

Troubleshooting

Common Issues

  • Wallet not connected error: Ensure the PRIVATE_KEY is correctly set in the .env file as the wallet connects automatically on server start.

  • RPC connection issues: Verify your internet connection and RPC endpoint URLs in the .env file.

  • Insufficient funds: Ensure your wallet has enough of the native token (POL) for gas fees:

    const balances = await server.listBalances();
    console.log(`POL balance:`, balances.nativeBalance);
    
  • Transaction failures: Use the transaction simulator to diagnose issues before sending:

    const simulation = await server.simulateTransaction(tx);
    if (!simulation.success) {
      console.error('Transaction would fail:', simulation.errorMessage);
    }
    

Debugging

Enable debug logging by setting the environment variable:

DEBUG=polygon-mcp:*

MCP Integration

To use this server with Claude or other MCP-compatible systems, add it to your MCP settings configuration file:

For 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": []
    }
  }
}

How to install this MCP server

For Claude Code

To add this MCP server to Claude Code, run this command in your terminal:

claude mcp add-json "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":[]}'

See the official Claude Code MCP documentation for more details.

For Cursor

There are two ways to add an MCP server to Cursor. The most common way is to add the server globally in the ~/.cursor/mcp.json file so that it is available in all of your projects.

If you only need the server in a single project, you can add it to the project instead by creating or adding it to the .cursor/mcp.json file.

Adding an MCP server to Cursor globally

To add a global MCP server go to Cursor Settings > Tools & Integrations and click "New MCP Server".

When you click that button the ~/.cursor/mcp.json file will be opened and you can add your server like this:

{
    "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": []
        }
    }
}

Adding an MCP server to a project

To add an MCP server to a project you can create a new .cursor/mcp.json file or add it to the existing one. This will look exactly the same as the global MCP server example above.

How to use the MCP server

Once the server is installed, you might need to head back to Settings > MCP and click the refresh button.

The Cursor agent will then be able to see the available tools the added MCP server has available and will call them when it needs to.

You can also explicitly ask the agent to use the tool by mentioning the tool name and describing what the function does.

For Claude Desktop

To add this MCP server to Claude Desktop:

1. Find your configuration file:

  • macOS: ~/Library/Application Support/Claude/claude_desktop_config.json
  • Windows: %APPDATA%\Claude\claude_desktop_config.json
  • Linux: ~/.config/Claude/claude_desktop_config.json

2. Add this to your configuration file:

{
    "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": []
        }
    }
}

3. Restart Claude Desktop for the changes to take effect

Want to 10x your AI skills?

Get a free account and learn to code + market your apps using AI (with or without vibes!).

Nah, maybe later