npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@ebowwa/prediction-markets-mcp

v0.2.2

Published

Prediction Markets MCP Server - Kalshi and Polymarket integration

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-mcp

Configuration

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 30000

Usage

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 dev

In mock mode, all tools return sample data without requiring backend services.

Available Tools

Kalshi

  • kalshi_get_market - Get market details by ticker
  • kalshi_list_markets - List markets with filters
  • kalshi_get_market_orderbook - Get orderbook for a market
  • kalshi_get_market_trades - Get trade history for a market
  • kalshi_get_balance - Get account balance
  • kalshi_get_positions - Get current positions
  • kalshi_list_orders - Get order history
  • kalshi_create_order - Create new order
  • kalshi_cancel_order - Cancel open order
  • kalshi_amend_order - Amend existing order
  • kalshi_list_events - List events
  • kalshi_get_event - Get event details
  • kalshi_list_series - List series
  • kalshi_get_series - Get series details
  • kalshi_get_exchange_status - Get exchange status

Polymarket

  • polymarket_get_market - Get market details by condition ID
  • polymarket_list_markets - List markets with filters
  • polymarket_get_event - Get event details by slug
  • polymarket_list_events - List events
  • polymarket_get_profile - Get wallet profile data
  • polymarket_get_positions - Get wallet positions
  • polymarket_get_wallet_trades - Get wallet trade history
  • polymarket_search - Search markets, events, and profiles
  • polymarket_get_orderbook - Get orderbook for a token
  • polymarket_get_trades - Get recent trades for a token
  • polymarket_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.SUB

Retry 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 format

Testing

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 --coverage

Test 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 tests

Project 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.md

Mock 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

References