extgange-betfair-mcp

aranej/extgange-betfair-mcp

3.2

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

The Betfair MCP Server is a Model Context Protocol server that allows AI assistants to interact with the Betfair Exchange platform, providing read-only access to betting markets, live odds, account information, and sporting events.

Tools
7
Resources
0
Prompts
0

Betfair MCP Server

A Model Context Protocol (MCP) server that enables AI assistants to interact with the Betfair Exchange betting platform. This server provides read-only access to betting markets, live odds, account information, and sporting events.

Features

  • Account Management: Query account balance, funds, and details
  • Event Discovery: Browse sports, competitions, and events
  • Market Intelligence: Access betting markets and live odds
  • Real-time Data: Get current prices and market information
  • Type-safe: Full type hints and Pydantic validation
  • Enterprise-ready: Production-grade error handling and logging

Production Hardening 🛡️

Automatic Rate Limiting:

  • Login operations: 90 requests/minute (safety margin under 100/min hard limit)
  • General API calls: 20 requests/second (conservative limit)
  • Per-market requests: 5 requests/second per market ID
  • Automatic cleanup: Hourly cleanup of old rate limiters to prevent memory leaks

Request Weight Validation:

  • Validates all requests against Betfair's 200-point weight limit
  • Market catalogue: Calculates weight based on projections (COMPETITION, EVENT, RUNNER_DESCRIPTION, etc.)
  • Market prices: Calculates weight for price data (EX_BEST_OFFERS, EX_TRADED, etc.)
  • Automatic validation before API calls to prevent TOO_MUCH_DATA errors

Intelligent Error Handling:

  • Classified errors: INVALID_SESSION_TOKEN, TOO_MANY_REQUESTS, TOO_MUCH_DATA, THROTTLED
  • Exponential backoff: Automatic retry with 1-10 second delays for rate limit errors
  • Session refresh: Automatic re-authentication on session expiry
  • Detailed logging: Structured error logging with context for debugging

Background Tasks:

  • Keep-alive loop: Sends keep-alive every 30 minutes to prevent session timeout
  • Rate limiter cleanup: Hourly cleanup of unused per-market rate limiters

Quick Start

Prerequisites

Installation

  1. Clone the repository:

    git clone https://github.com/aranej/extgange-betfair-mcp.git
    cd extgange-betfair-mcp
    
  2. Install dependencies using uv (recommended):

    # Install uv if not already installed
    curl -LsSf https://astral.sh/uv/install.sh | sh
    
    # Create virtual environment and install dependencies
    uv venv
    source .venv/bin/activate  # On Windows: .venv\Scripts\activate
    uv pip install -e .
    

    Or using pip:

    python -m venv .venv
    source .venv/bin/activate  # On Windows: .venv\Scripts\activate
    pip install -e .
    
  3. Configure credentials:

    cp .env.example .env
    # Edit .env and add your Betfair credentials
    

Configuration

Edit .env with your Betfair credentials:

BETFAIR_USERNAME=your_username
BETFAIR_PASSWORD=your_password
BETFAIR_APP_KEY=your_app_key

# Optional: Certificate authentication (recommended for production)
BETFAIR_CERT_FILE=/path/to/client-2048.crt
BETFAIR_KEY_FILE=/path/to/client-2048.key

# Server settings
LOG_LEVEL=INFO

Get your credentials:

Usage

Running the Server

Start the MCP server:

python -m betfair_mcp.server

Or using FastMCP CLI:

fastmcp run src/betfair_mcp/server.py

Available Tools

The server provides the following MCP tools:

Account Tools

get_account_balance

  • Get current account balance and available funds
  • Returns: available to bet, exposure, limits

get_account_details

  • Get account information and settings
  • Returns: name, currency, timezone, points balance
Event Tools

list_event_types

  • List all available sports
  • Returns: sport IDs and names (Soccer, Tennis, etc.)

list_events

  • List sporting events with filtering
  • Args: event_type_id, competition_id, text_query
  • Returns: events with IDs, names, dates

list_competitions

  • List competitions/leagues for a sport
  • Args: event_type_id
  • Returns: competition IDs and names
Market Tools

list_market_catalogue

  • List betting markets with filtering
  • Args: event_id, event_type_id, competition_id, market_type_codes, max_results
  • Returns: markets with runners and descriptions

get_market_prices

  • Get live odds for markets
  • Args: market_ids (list, max 250)
  • Returns: back/lay prices, matched amounts

Example Queries

Here are example natural language queries you can ask an AI assistant using this MCP server:

"What's my current Betfair account balance?"

"Show me upcoming Premier League matches"

"What are the odds for the next Manchester United game?"

"List all tennis events happening today"

"What markets are available for the Champions League final?"

Project Structure

betfair-mcp/
├── src/
│   └── betfair_mcp/
│       ├── __init__.py          # Package initialization
│       ├── server.py            # FastMCP server & tool registration
│       ├── auth.py              # Session management
│       ├── tools/               # MCP tool implementations
│       │   ├── __init__.py
│       │   ├── account.py       # Account-related tools
│       │   ├── events.py        # Event discovery tools
│       │   └── markets.py       # Market data tools
│       └── utils/               # Utility modules
│           └── __init__.py
├── pyproject.toml               # Project dependencies
├── .env.example                 # Environment template
└── README.md                    # This file

Research Documentation

This project includes comprehensive research documentation:

  • : Master navigation for all research
  • : Authentication deep dive
  • : Rate limiting strategies
  • : Real-time streaming guide
  • : SDK integration patterns
  • : MCP implementation guide
  • : User personas and scenarios
  • : Legal and ethical guidelines
  • : Production deployment guide

Development Roadmap

Current Status: Phase 1 (MVP) + Production Hardening ✅

Completed:

  • Phase 1: Core MCP server with 7 tools (account, events, markets)
  • Production Hardening: Rate limiting, weight validation, error handling

Future Phases:

  • Phase 2: Streaming API integration for real-time updates
  • Phase 3: Advanced analytics and value betting tools
  • Phase 4: Responsible gambling monitoring
  • Phase 5: Full observability (Prometheus, Grafana, Kubernetes deployment)

Compliance & Responsible Use

Important: This server is designed for read-only intelligence and does NOT support placing bets. It provides market data and account information only.

Permitted Use

  • Market research and analysis
  • Price comparison and value identification
  • Educational and research purposes
  • Integration with AI assistants for information queries

Prohibited Use

  • Automated betting or gambling
  • High-frequency trading strategies
  • Circumventing Betfair rate limits
  • Sharing account credentials

Responsible Gambling: If you or someone you know has a gambling problem, seek help:

See for full compliance guidelines.

Betfair Terms of Service

This MCP server uses the official Betfair API, which explicitly permits programmatic access:

"You may use software programs with your Betfair account provided that they interact with Betfair via the API" — Betfair Terms of Service

However, you must:

  • Use your own Betfair account
  • Comply with Betfair's API policies
  • Not exceed rate limits
  • Not engage in prohibited activities

Rate Limits

Betfair does not have general API throttling, but specific limits apply:

  • Login: 100 requests per minute (hard limit)
  • Per-market: 5 requests per second per market ID
  • Keep-alive: Recommended every 30 minutes

The server automatically handles session keep-alive. See for details.

Troubleshooting

Login Issues

Problem: LOGIN_FAILED error

Solutions:

  • Verify credentials in .env are correct
  • Check if your Betfair account is active
  • Ensure you're not exceeding 100 logins/minute
  • Try certificate authentication for production use

Certificate Authentication

Problem: Certificate files not found

Solutions:

  • Generate certificates using Betfair's guide
  • Update BETFAIR_CERT_FILE and BETFAIR_KEY_FILE paths in .env
  • Ensure certificate files have correct permissions

API Errors

Problem: THROTTLED or rate limit errors

Solutions:

  • Reduce request frequency
  • Use delayed app key (not instant key)
  • Implement exponential backoff
  • See

Contributing

Contributions are welcome! Please:

  1. Review research documentation first
  2. Follow existing code patterns
  3. Add tests for new features
  4. Update documentation

License

MIT License - see LICENSE file for details

Support

Acknowledgments

Built with:


Disclaimer: This is an independent project and is not affiliated with, endorsed by, or sponsored by Betfair. Use at your own risk.