polymarket-mcp-server

jayeshchowdary/polymarket-mcp-server

3.2

If you are the rightful owner of polymarket-mcp-server and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to henry@mcphub.com.

A comprehensive Model Context Protocol (MCP) server for professional Polymarket prediction market trading.

Tools
3
Resources
0
Prompts
0

Polymarket Trader MCP Server

A comprehensive Model Context Protocol (MCP) server for professional Polymarket prediction market trading. Provides over 55 tools for market analysis, trading execution, on-chain operations, risk management, and system diagnostics.

🚀 Features

Comprehensive Professional Trading Toolkit

  1. Market Discovery & Analysis

    • Advanced market filtering by volume, liquidity, dates, tags
    • Event management and series tracking
    • Sports metadata and tag management
    • Comprehensive search capabilities
  2. Pricing & Analytics

    • Market price and midpoint price retrieval
    • Price history and trend analysis
    • Bid-ask spread calculations
    • Potential payout calculations
  3. Trading & Order Management

    • Limit and market order placement
    • Batch order operations
    • Order status tracking and cancellation
    • Advanced order management (emergency cancellation, market-specific controls)
    • Rewards optimization and scoring
  4. User Data & Portfolio

    • Position tracking and portfolio valuation
    • Trade history and user activity
    • Closed positions analysis
    • Market trading statistics
  5. On-Chain CTF Operations

    • Condition ID calculation and position management
    • Token balance checking and fee estimation
    • Advanced CTF parameter calculations
  6. Token & Allowance Management

    • USDC balance and allowance management
    • Conditional token allowance setup
    • Proxy wallet token checking
  7. System & Analytics

    • API health monitoring and connectivity testing
    • Order book analysis and liquidity metrics
    • Market analytics and open interest tracking
    • Comprehensive system information

Complete Trading Workflows

See for 13 complete end-to-end workflows that guide you from discovery to order placement:

  1. Search and Trade - Start with search, find market, analyze, and place order
  2. Browse by Category - Filter markets by category/tag, analyze, and trade
  3. Active Markets Scanner - Find high-volume active markets for quick trade
  4. Event-Based Trading - Find event, explore markets, and place orders
  5. Price Analysis Trade - Analyze price history, check spreads, make informed trade
  6. Market Depth Analysis - Analyze order book depth and place strategic order
  7. Payout Calculation Workflow - Calculate potential returns before trading
  8. Quick Market Order - If you know the market, quick market order placement
  9. Limit Order Strategy - Place limit orders at specific prices
  10. Portfolio Management - Check positions, manage orders, adjust positions
  11. Batch Trading - Place multiple orders across different markets
  12. Risk Management - Check balances, calculate fees, set allowances, then trade
  13. Market Making - Place both buy and sell orders for liquidity provision

Each workflow includes step-by-step instructions, exact parameters to use, and which fields to extract from responses.

📋 Prerequisites

  • Python 3.10+ (required for fastmcp)
  • uv (recommended) or pip for dependency management
  • MetaMask or compatible wallet for trading
  • Polymarket account with deposited USDC

🛠️ Installation & Setup

Step 1: Clone the Repository

git clone <repository-url>
cd polymarket-trader-mcp

Step 2: Install Dependencies

# Install uv if you don't have it
curl -LsSf https://astral.sh/uv/install.sh | sh

# Install dependencies (uv automatically manages virtual environment)
uv sync

Note: uv automatically creates and manages a virtual environment for you. No need to manually create venv or activate it.

Step 3: Environment Configuration

Create a .env file in the project root:

# Account Configuration (REQUIRED)
POLYMARKET_PRIVATE_KEY=your_metamask_private_key_here
PROXY_FUNDER_ADDRESS=your_polymarket_proxy_wallet_address
ACCOUNT_TYPE=BROWSER_WALLET

# Network Configuration (Optional - has defaults)
POLYGON_RPC_URL=https://polygon-rpc.com

# API Configuration (Optional - has defaults)
GAMMA_API_URL=https://gamma-api.polymarket.com
CLOB_API_URL=https://clob.polymarket.com
DATA_API_URL=https://data-api.polymarket.com

🔑 Getting Required Credentials

Step 1: Get Your MetaMask Private Key

  1. Open MetaMask in your browser
  2. Click the account menu (three dots) in the top right
  3. Select "Account Details"
  4. Click "Export Private Key"
  5. Enter your MetaMask password
  6. Copy the private key (starts with 0x followed by 64 characters)
  7. ⚠️ NEVER share this key with anyone!

Example:

POLYMARKET_PRIVATE_KEY=0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef

Step 2: Get Your Polymarket Proxy Wallet Address

Method A: Using the MCP Tool (Recommended)
  1. Start the MCP server (see Step 4 below)
  2. Use the check_usdc_balance tool in Inspector
  3. Copy the balance_address from the response
Method B: From Polymarket Website
  1. Go to polymarket.com
  2. Connect your MetaMask wallet
  3. Go to your account settings
  4. Look for "Proxy Wallet" or "Wallet Address"
  5. Copy the proxy wallet address
Method C: From PolygonScan
  1. Go to polygonscan.com
  2. Search for your MetaMask address
  3. Look for transactions to/from Polymarket contracts
  4. Find the proxy wallet address in transaction details

Example:

PROXY_FUNDER_ADDRESS=0x6037D3c24f8D3450a83C82E126B9D914bd835eBE

Step 3: Set Account Type

For MetaMask users:

ACCOUNT_TYPE=BROWSER_WALLET

For MagicLink users:

ACCOUNT_TYPE=EMAIL

For direct wallet users:

ACCOUNT_TYPE=EOA

🚀 Running the Server

# Start the server (uv automatically uses the managed virtual environment)
uv run python polymarket_trader_mcp.py

Note: With uv, you don't need to manually activate a virtual environment. The uv run command automatically uses the environment created by uv sync.

Expected Output

✅ Web3 and CTF contract initialized successfully.
🚀 Polymarket Trader MCP Server started
📊 Over 55 tools available
🔗 Connected to Polygon network

🔧 Configuration Details

Environment Variables Reference

VariableRequiredDefaultDescription
POLYMARKET_PRIVATE_KEY✅ Yes-Your MetaMask private key
PROXY_FUNDER_ADDRESS✅ Yes-Your Polymarket proxy wallet
ACCOUNT_TYPE✅ YesBROWSER_WALLETAccount type (BROWSER_WALLET/EMAIL/EOA)
POLYGON_RPC_URL❌ Nohttps://polygon-rpc.comPolygon RPC endpoint
GAMMA_API_URL❌ Nohttps://gamma-api.polymarket.comGamma API endpoint
CLOB_API_URL❌ Nohttps://clob.polymarket.comCLOB API endpoint
DATA_API_URL❌ Nohttps://data-api.polymarket.comData API endpoint

Account Types Explained

The MCP server supports three account types, each with different signature types per py-clob-client documentation:

  • EOA (Externally Owned Account): signature_type=0

    • Direct wallet integration (MetaMask, hardware wallets, any wallet where you control the private key)
    • No PROXY_FUNDER_ADDRESS required - funds are in the EOA address itself
    • Best for: Direct wallet control, hardware wallets, MetaMask when using direct EOA mode
  • EMAIL: signature_type=1

    • Email/Magic wallet signatures (delegated signing)
    • Requires PROXY_FUNDER_ADDRESS - this is where your funds are held
    • Best for: Email-based Polymarket accounts
  • BROWSER_WALLET: signature_type=2 (default)

    • Browser wallet with proxy contract signatures
    • Requires PROXY_FUNDER_ADDRESS - this is your Polymarket proxy wallet address
    • Best for: MetaMask users connecting through Polymarket's proxy system

Important Notes:

  • For EOA accounts, use your EOA address directly for all operations
  • For EMAIL/BROWSER_WALLET accounts, use the PROXY_FUNDER_ADDRESS for positions, balances, and trading
  • The get_trading_address() helper automatically returns the correct address based on your account type
  • Use diagnostic tools (get_current_credentials, verify_clob_client_status) to verify your configuration

📊 Tool Categories

Market Discovery

  • get_markets_advanced - Advanced market filtering
  • get_events - Event listing with filters
  • get_event_by_id - Specific event by ID
  • search_markets_events_profiles - Unified search
  • get_market_info - Comprehensive market snapshot
  • get_market_by_condition_id - Retrieve markets via condition ID (CLOB)
  • And many more discovery tools covering events, tags, sports, and series

Trading Operations

  • place_limit_order - Place limit orders
  • place_market_order - Place market orders (FOK/FAK)
  • place_batch_orders - Batch order placement
  • get_open_orders - Get active orders
  • cancel_order - Cancel specific order
  • cancel_all_orders - Emergency order cancellation
  • And other order management utilities

User Data & Portfolio

  • get_user_positions - Current positions
  • get_trades - Trade history
  • get_user_activity - User activity feed
  • get_user_portfolio_value - Portfolio valuation
  • get_closed_positions - Closed positions
  • get_user_markets_traded - Markets traded count
  • get_top_holders - Market top holders

On-Chain CTF Operations

  • get_condition_id - Calculate condition ID
  • get_position_ids - Calculate position IDs
  • check_ctf_balance - Check token balances
  • calculate_ctf_fees - Estimate gas costs

Token Management

  • check_usdc_balance - USDC balance and allowances (uses py-clob-client when available, falls back to Web3)
  • set_usdc_allowance - Set USDC allowance
  • set_conditional_token_allowance - Set token allowance
  • check_proxy_wallet_tokens - Proxy wallet tokens
  • check_conditional_token_allowance - Check conditional token balance/allowance using py-clob-client
  • check_balance_allowance_clob - Check balance/allowance for COLLATERAL or CONDITIONAL using py-clob-client
  • update_balance_allowance_cache - Refresh cached balance/allowance data using py-clob-client

Diagnostic & Verification Tools

  • check_mcp_connection - Verify MCP server is running and check client initialization status
  • get_current_credentials - Show active credential configuration (account_type, signature_type, addresses)
  • verify_clob_client_status - Detailed CLOB client health check and connection test
  • get_tool_credential_mapping - Show which credentials each tool category requires

Pricing & Analytics

  • get_market_price - Get current market price for a token
  • get_midpoint_price - Get midpoint price (average of bid/ask)
  • get_price_history - Get historical price data
  • get_bid_ask_spreads - Get bid-ask spreads for multiple tokens
  • calculate_potential_payout - Calculate potential payout before trading

System & Analytics

  • get_order_book - Order book data
  • get_open_interest - Market open interest
  • get_event_live_volume - Event volume tracking
  • calculate_clob_fees - Calculate trading fees

💡 Usage Examples

Basic Market Analysis

# Get trending markets
get_markets_advanced(limit=10, active=True, liquidity_num_min=1000)

# Get market information
get_market_info(market_id="12345")

# Check order book
get_order_book(token_id="your_token_id")

Trading Operations

# Place a limit order
place_limit_order(
    token_id="your_token_id",
    side="BUY",
    size=100,
    price=0.6
)

# Place a market order
place_market_order(
    token_id="your_token_id",
    side="SELL",
    size=50,
    order_type="FOK"
)

Portfolio Management

# Check your positions
get_user_positions(user="your_proxy_wallet_address")

# Check USDC balance
check_usdc_balance()

# Get trade history
get_trades(user="your_proxy_wallet_address", limit=20)

On-Chain Operations

# Check CTF token balances
check_ctf_balance(
    condition_id="0x123abc...",
    user_address="your_proxy_wallet_address"
)

# Calculate position IDs
get_position_ids(condition_id="0x123abc...")

# Estimate gas fees
calculate_ctf_fees(operation="split", amount=1.0)

🔍 Diagnostic Tools Usage

Verifying Your Setup

Before trading, use the diagnostic tools to verify your configuration:

  1. Check MCP Connection

    check_mcp_connection()
    
    • Verifies server is running
    • Shows which clients are initialized
    • Checks Web3 connection status
  2. Get Current Credentials

    get_current_credentials()
    
    • Shows your account_type and signature_type
    • Displays EOA address and proxy_funder_address (if set)
    • Shows which address is used for trading
    • Validates credential configuration
  3. Verify CLOB Client Status

    verify_clob_client_status()
    
    • Tests CLOB client connection
    • Verifies API credentials are set
    • Shows client address and health status
  4. Check Tool Requirements

    get_tool_credential_mapping()
    
    • Shows which credentials each tool category needs
    • Helps understand which tools will work with your current setup

Using py-clob-client Native Methods

The server now uses py-clob-client's native balance/allowance methods when available:

  • check_usdc_balance() - Automatically uses clob_client.get_balance_allowance() if available, falls back to Web3
  • check_balance_allowance_clob() - Direct access to py-clob-client methods for both COLLATERAL and CONDITIONAL tokens
  • update_balance_allowance_cache() - Refresh cached balance/allowance data

Benefits:

  • More reliable balance/allowance queries
  • Better integration with Polymarket's systems
  • Automatic fallback to Web3 if clob_client is unavailable

🔒 Security Best Practices

Private Key Security

  • Never commit your private key to version control
  • Use environment variables for all sensitive data
  • Keep your private key secure - anyone with it can access your wallet
  • Consider using a hardware wallet for large amounts

Environment Security

  • Never share your .env file
  • Use different keys for testing and production
  • Regularly rotate your private keys
  • Monitor your wallet for unauthorized transactions

🐛 Troubleshooting

Common Issues

"Web3 not initialized" Error
# Check your environment variables
echo $POLYMARKET_PRIVATE_KEY
echo $PROXY_FUNDER_ADDRESS

# Verify your .env file exists and is properly formatted
cat .env
"Failed to fetch CTF contract ABI" Warning
  • This is a non-critical warning
  • The tools will still work for basic operations
  • Caused by Polygonscan API rate limits
"No module named 'py_builder_signing_sdk'" Error
# Reinstall dependencies
uv sync
"Invalid private key" Error
  • Ensure your private key starts with 0x
  • Check that it's exactly 66 characters long
  • Verify you copied it correctly from MetaMask
"Proxy wallet not found" Error
  • Use the check_usdc_balance tool to get your proxy address
  • Ensure you're using the correct proxy wallet address
  • Verify your MetaMask is connected to Polymarket

Getting Help

  1. Check the logs for specific error messages
  2. Verify your environment variables are set correctly
  3. Test with the health_check tool to verify API connectivity

📚 API Documentation

Polymarket APIs

This server integrates with:

Web3 Integration

  • Polygon Network: Fast, low-cost transactions
  • USDC (ERC-20): Collateral token for trading
  • ERC-1155: Outcome tokens (YES/NO shares)
  • CTF Framework: Conditional Token Framework for share management

🏗️ Architecture

polymarket_trader_mcp.py    # Main server (55+ tools)
workflows.py                # High-level trading workflows
pyproject.toml              # UV dependency management
uv.lock                     # Locked dependency versions
README.md                   # This documentation
PROJECT_RUNDOWN.md         # Detailed project overview
polymarket_mcp_metadata.json # Tool metadata

🚀 Performance Features

  • Async HTTP client (httpx) for concurrent requests
  • Connection pooling for efficient API usage
  • Rate limiting awareness to respect API limits
  • Error recovery mechanisms for robust operation
  • Web3 integration for on-chain operations

🔄 Development

Adding New Tools

  1. Define the tool function in polymarket_trader_mcp.py
  2. Add @mcp.tool() decorator with description
  3. Implement async API calls using helper functions
  4. Add error handling and validation
  5. Update the metadata file

Adding New Workflows

  1. Create workflow function in workflows.py
  2. Combine multiple existing tools
  3. Add business logic for decision making
  4. Return actionable insights

📈 Roadmap

  • WebSocket integration for real-time updates
  • Enhanced CTF tools for advanced share management
  • Machine learning price prediction
  • Advanced portfolio analytics with correlation matrices
  • Automated strategy execution with backtesting
  • Multi-wallet support for portfolio diversification

🤝 Contributing

Contributions welcome! Please:

  1. Follow existing code style
  2. Add tests for new features
  3. Update documentation
  4. Submit pull requests

📞 Support

For issues, questions, or contributions:

⚖️ License

MIT License - See LICENSE file for details

⚠️ Disclaimer

This software is for educational and research purposes. Trading prediction markets involves risk. Always do your own research and never risk more than you can afford to lose. The authors are not responsible for any financial losses incurred while using this software.


Built with ❤️ for the Polymarket trading community

55+ tools • 13 workflows • Professional-grade trading infrastructure