jayeshchowdary/polymarket-mcp-server
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.
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
-
Market Discovery & Analysis
- Advanced market filtering by volume, liquidity, dates, tags
- Event management and series tracking
- Sports metadata and tag management
- Comprehensive search capabilities
-
Pricing & Analytics
- Market price and midpoint price retrieval
- Price history and trend analysis
- Bid-ask spread calculations
- Potential payout calculations
-
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
-
User Data & Portfolio
- Position tracking and portfolio valuation
- Trade history and user activity
- Closed positions analysis
- Market trading statistics
-
On-Chain CTF Operations
- Condition ID calculation and position management
- Token balance checking and fee estimation
- Advanced CTF parameter calculations
-
Token & Allowance Management
- USDC balance and allowance management
- Conditional token allowance setup
- Proxy wallet token checking
-
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:
- Search and Trade - Start with search, find market, analyze, and place order
- Browse by Category - Filter markets by category/tag, analyze, and trade
- Active Markets Scanner - Find high-volume active markets for quick trade
- Event-Based Trading - Find event, explore markets, and place orders
- Price Analysis Trade - Analyze price history, check spreads, make informed trade
- Market Depth Analysis - Analyze order book depth and place strategic order
- Payout Calculation Workflow - Calculate potential returns before trading
- Quick Market Order - If you know the market, quick market order placement
- Limit Order Strategy - Place limit orders at specific prices
- Portfolio Management - Check positions, manage orders, adjust positions
- Batch Trading - Place multiple orders across different markets
- Risk Management - Check balances, calculate fees, set allowances, then trade
- 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
- Open MetaMask in your browser
- Click the account menu (three dots) in the top right
- Select "Account Details"
- Click "Export Private Key"
- Enter your MetaMask password
- Copy the private key (starts with
0xfollowed by 64 characters) - ⚠️ 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)
- Start the MCP server (see Step 4 below)
- Use the
check_usdc_balancetool in Inspector - Copy the
balance_addressfrom the response
Method B: From Polymarket Website
- Go to polymarket.com
- Connect your MetaMask wallet
- Go to your account settings
- Look for "Proxy Wallet" or "Wallet Address"
- Copy the proxy wallet address
Method C: From PolygonScan
- Go to polygonscan.com
- Search for your MetaMask address
- Look for transactions to/from Polymarket contracts
- 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
| Variable | Required | Default | Description |
|---|---|---|---|
POLYMARKET_PRIVATE_KEY | ✅ Yes | - | Your MetaMask private key |
PROXY_FUNDER_ADDRESS | ✅ Yes | - | Your Polymarket proxy wallet |
ACCOUNT_TYPE | ✅ Yes | BROWSER_WALLET | Account type (BROWSER_WALLET/EMAIL/EOA) |
POLYGON_RPC_URL | ❌ No | https://polygon-rpc.com | Polygon RPC endpoint |
GAMMA_API_URL | ❌ No | https://gamma-api.polymarket.com | Gamma API endpoint |
CLOB_API_URL | ❌ No | https://clob.polymarket.com | CLOB API endpoint |
DATA_API_URL | ❌ No | https://data-api.polymarket.com | Data 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_ADDRESSrequired - 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_ADDRESSfor 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 filteringget_events- Event listing with filtersget_event_by_id- Specific event by IDsearch_markets_events_profiles- Unified searchget_market_info- Comprehensive market snapshotget_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 ordersplace_market_order- Place market orders (FOK/FAK)place_batch_orders- Batch order placementget_open_orders- Get active orderscancel_order- Cancel specific ordercancel_all_orders- Emergency order cancellation- And other order management utilities
User Data & Portfolio
get_user_positions- Current positionsget_trades- Trade historyget_user_activity- User activity feedget_user_portfolio_value- Portfolio valuationget_closed_positions- Closed positionsget_user_markets_traded- Markets traded countget_top_holders- Market top holders
On-Chain CTF Operations
get_condition_id- Calculate condition IDget_position_ids- Calculate position IDscheck_ctf_balance- Check token balancescalculate_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 allowanceset_conditional_token_allowance- Set token allowancecheck_proxy_wallet_tokens- Proxy wallet tokenscheck_conditional_token_allowance- Check conditional token balance/allowance using py-clob-clientcheck_balance_allowance_clob- Check balance/allowance for COLLATERAL or CONDITIONAL using py-clob-clientupdate_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 statusget_current_credentials- Show active credential configuration (account_type, signature_type, addresses)verify_clob_client_status- Detailed CLOB client health check and connection testget_tool_credential_mapping- Show which credentials each tool category requires
Pricing & Analytics
get_market_price- Get current market price for a tokenget_midpoint_price- Get midpoint price (average of bid/ask)get_price_history- Get historical price dataget_bid_ask_spreads- Get bid-ask spreads for multiple tokenscalculate_potential_payout- Calculate potential payout before trading
System & Analytics
get_order_book- Order book dataget_open_interest- Market open interestget_event_live_volume- Event volume trackingcalculate_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:
-
Check MCP Connection
check_mcp_connection()- Verifies server is running
- Shows which clients are initialized
- Checks Web3 connection status
-
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
-
Verify CLOB Client Status
verify_clob_client_status()- Tests CLOB client connection
- Verifies API credentials are set
- Shows client address and health status
-
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 usesclob_client.get_balance_allowance()if available, falls back to Web3check_balance_allowance_clob()- Direct access to py-clob-client methods for both COLLATERAL and CONDITIONAL tokensupdate_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
.envfile - 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_balancetool to get your proxy address - Ensure you're using the correct proxy wallet address
- Verify your MetaMask is connected to Polymarket
Getting Help
- Check the logs for specific error messages
- Verify your environment variables are set correctly
- Test with the
health_checktool to verify API connectivity
📚 API Documentation
Polymarket APIs
This server integrates with:
-
Gamma Markets API: Market data, events, metadata
-
CLOB API: Order book, pricing, trades, order management
- Documentation: https://docs.polymarket.com/developers/CLOB/introduction
-
Data API: User positions, trades, activity
- Documentation: https://docs.polymarket.com/developers/data-api/overview
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
- Define the tool function in
polymarket_trader_mcp.py - Add
@mcp.tool()decorator with description - Implement async API calls using helper functions
- Add error handling and validation
- Update the metadata file
Adding New Workflows
- Create workflow function in
workflows.py - Combine multiple existing tools
- Add business logic for decision making
- 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:
- Follow existing code style
- Add tests for new features
- Update documentation
- Submit pull requests
📞 Support
For issues, questions, or contributions:
- Open an issue on GitHub
- Check Polymarket documentation: https://docs.polymarket.com
- Review FastMCP documentation: https://github.com/jlowin/fastmcp
- MCP Protocol Specification: https://modelcontextprotocol.io
⚖️ 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