@ebowwa/prediction-markets-mcp
v0.2.2
Published
Prediction Markets MCP Server - Kalshi and Polymarket integration
Maintainers
Readme
@ebowwa/prediction-markets-mcp
Model Context Protocol (MCP) server for Kalshi and Polymarket prediction markets integration.
Overview
This MCP server provides tools for interacting with prediction markets:
- Kalshi: CFTC-regulated prediction market for event contracts
- Polymarket: Decentralized prediction market platform
Features
- Market search and discovery
- Account balance and position management
- Order creation and cancellation
- Real-time market data access
- Comprehensive error handling with custom error types
- Input validation using Zod schemas
- Retry logic with exponential backoff
- Mock mode for testing without live APIs
- Service health checks and auto-recovery
Installation
bun add @ebowwa/prediction-markets-mcpConfiguration
Set up environment variables for API credentials:
# Kalshi service URL (kalshi-ts service)
export KALSHI_SERVICE_URL="http://localhost:3000" # optional, default
# Polymarket service URL (polymarket-ts service)
export POLYMARKET_SERVICE_URL="http://localhost:3001" # optional, default
# Enable mock mode for testing without live services
export MOCK_MODE="true"
# Enable auto-start of backend services
export AUTO_START_SERVICES="true"
# Request timeout (milliseconds)
export KALSHI_TIMEOUT="30000" # optional, default 30000Usage
As MCP Server
Add to your MCP client configuration:
{
"mcpServers": {
"prediction-markets": {
"command": "bun",
"args": ["run", "/path/to/mcp/src/index.ts"],
"env": {
"KALSHI_SERVICE_URL": "http://localhost:3000",
"POLYMARKET_SERVICE_URL": "http://localhost:3001",
"MOCK_MODE": "false"
}
}
}
}Mock Mode
For testing without live API connections, enable mock mode:
export MOCK_MODE="true"
bun run devIn mock mode, all tools return sample data without requiring backend services.
Available Tools
Kalshi
kalshi_get_market- Get market details by tickerkalshi_list_markets- List markets with filterskalshi_get_market_orderbook- Get orderbook for a marketkalshi_get_market_trades- Get trade history for a marketkalshi_get_balance- Get account balancekalshi_get_positions- Get current positionskalshi_list_orders- Get order historykalshi_create_order- Create new orderkalshi_cancel_order- Cancel open orderkalshi_amend_order- Amend existing orderkalshi_list_events- List eventskalshi_get_event- Get event detailskalshi_list_series- List serieskalshi_get_series- Get series detailskalshi_get_exchange_status- Get exchange status
Polymarket
polymarket_get_market- Get market details by condition IDpolymarket_list_markets- List markets with filterspolymarket_get_event- Get event details by slugpolymarket_list_events- List eventspolymarket_get_profile- Get wallet profile datapolymarket_get_positions- Get wallet positionspolymarket_get_wallet_trades- Get wallet trade historypolymarket_search- Search markets, events, and profilespolymarket_get_orderbook- Get orderbook for a tokenpolymarket_get_trades- Get recent trades for a tokenpolymarket_get_price- Get current price for a token
Error Handling
The MCP server includes comprehensive error handling:
- NetworkError: Connection failures, timeouts
- ServiceUnavailableError: Backend service not running
- APIError: API errors with status codes (4xx, 5xx)
- ValidationError: Invalid input parameters
- AuthenticationError: API key issues
- OrderError: Order creation/modification failures
- RateLimitError: Rate limit exceeded
All errors include:
- Error code and message
- Detailed error information
- Retryable flag (for automatic retry logic)
- Formatted JSON response
Example error response:
{
"name": "ServiceUnavailableError",
"message": "Kalshi service is unavailable. Please ensure the service is running. URL: http://localhost:3000",
"code": "SERVICE_UNAVAILABLE",
"retryable": true
}Input Validation
All tool inputs are validated using Zod schemas:
- Ticker format validation (Kalshi:
SERIES-DDMONYY-T.SUB) - Ethereum address validation (Polymarket:
0x+ 40 hex chars) - Price range validation (1-99 cents for Kalshi)
- Quantity limits (1-1,000,000 contracts)
- Pagination limits (1-1,000 results per page)
Invalid inputs return helpful error messages:
Validation failed for kalshi_get_market:
- ticker: Invalid Kalshi ticker format. Expected format: SERIES-DDMONYY-T.SUBRetry Logic
Network requests automatically retry with exponential backoff:
- Max attempts: 3 (configurable)
- Initial delay: 1 second
- Backoff multiplier: 2x
- Max delay: 10 seconds
- Jitter: Random +/- 25% to avoid thundering herd
Only retryable errors trigger automatic retries:
- Network errors
- 5xx server errors
- 429 rate limit errors
Development
# Install dependencies
bun install
# Run in development
bun run dev
# Run with mock mode (no backend services needed)
MOCK_MODE=true bun run dev
# Build for distribution
bun run build
# Run tests
bun run test
# Lint code
bun run lint
# Format code
bun run formatTesting
The project includes comprehensive test coverage:
# Run all tests
bun test
# Run specific test file
bun test tests/unit/errors.test.ts
# Run with coverage
bun test --coverageTest Structure
tests/
├── unit/
│ ├── errors.test.ts # Error type tests
│ ├── validation.test.ts # Input validation tests
│ ├── retry.test.ts # Retry logic tests
│ └── mock-data.test.ts # Mock data generator testsProject Structure
mcp/
├── src/
│ ├── index.ts # MCP server entry point
│ ├── kalshi.ts # Kalshi integration
│ ├── polymarket.ts # Polymarket integration
│ ├── types.ts # Shared types
│ ├── errors.ts # Custom error types
│ ├── retry.ts # Retry logic with backoff
│ ├── validation.ts # Zod validation schemas
│ ├── mock-data.ts # Mock data for testing
│ └── service-manager.ts # Backend service orchestration
├── tests/
│ └── unit/ # Unit tests
├── package.json
├── tsconfig.json
└── README.mdMock Mode
Mock mode returns sample data for all tools without requiring backend services. Useful for:
- Development: Test MCP integration without API keys
- CI/CD: Run tests without external dependencies
- Demonstrations: Show tool functionality without live data
Enable mock mode:
export MOCK_MODE="true"Mock data includes:
- Sample Kalshi markets (weather, Fed rate, elections)
- Sample Polymarket markets (crypto, economics)
- Mock orders, positions, and balances
- Realistic orderbook and trade data
Service Architecture
The MCP server wraps backend services:
- kalshi-ts: Kalshi API integration (port 3000)
- polymarket-ts: Polymarket API integration (port 3001)
The service manager:
- Checks service health on startup
- Auto-starts services if enabled
- Handles port conflicts gracefully
- Provides service status reporting
License
MIT
