api-football-mcp

MarvDann/api-football-mcp

3.3

If you are the rightful owner of api-football-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 henry@mcphub.com.

The API-Football MCP Server provides comprehensive Premier League football data from 1992 to the present, integrating with the API-Sports API-Football service.

Tools
8
Resources
0
Prompts
0

API‑Football MCP Server

A Model Context Protocol (MCP) server that provides Premier League data via API‑Sports’ API‑Football v3. Written in TypeScript with strict type checking, resilient error handling, and sensible caching for agent workflows.

Features

  • Historical Coverage: Premier League historical data (commonly 2002–present for many endpoints; some tools support 1992+ when data is available)
  • Real-time Data: Live match events, current standings, and fixture information
  • Intelligent Caching: LRU cache with TTL for optimal performance
  • Rate Limiting: Built-in rate‑limit tracking and exponential backoff
  • MCP Integration: Native Model Context Protocol support for LLM integration
  • TypeScript: Strict TypeScript (noUncheckedIndexedAccess, exactOptionalPropertyTypes)

MCP Tools

ToolDescriptionParameters
get_standingsGet Premier League standingsseason? (number)
get_fixturesGet match fixturesseason?, teamId?, date?, from?, to?, status?, round?
get_teamGet team information and optional season squadteamId? or name?, season?
get_playerGet player profile and statisticsplayerId? or name?, season?
get_match_goalsGet goal events for a matchfixtureId (required)
get_match_eventsGet all events for a matchfixtureId (required)
get_squadGet a team's squad for a seasonteamId (required), season (required)
search_teamsSearch for teams by namequery?, season?
search_playersSearch for playersquery (required), team?, season?, page?
get_live_matchesGet currently live matchesNone
get_rate_limitGet current API rate-limit statusNone

Data Coverage Notes

  • Historical coverage for the English Premier League via API‑Football v3 is commonly available from the 2002 season onwards. Earlier seasons (pre‑2002) may be incomplete or unavailable depending on the specific endpoint.
  • If you need season‑specific squads, use season with get_team (internally uses the /players endpoint) or the CLI --endpoint squad team=<id> season=<YYYY> helper.
  • Fixture queries support round in the form "Regular Season - N" in addition to season, date, and from/to.

Installation

Prerequisites

  • Node.js 22+
  • pnpm package manager
  • API‑Football API key from API‑Sports

Setup

  1. Clone the repository

    git clone https://github.com/MarvDann/api-football-mcp.git
    cd api-football-mcp
    
  2. Install dependencies

    pnpm install
    
  3. Configure environment

    # Set your API key as an environment variable
    export API_FOOTBALL_KEY=your_api_key_here
    
    # Or create a .env file
    echo "API_FOOTBALL_KEY=your_api_key_here" > .env
    
  4. Build the project

    pnpm run build
    

Usage

As MCP Server

The primary use case is as an MCP server for LLM integration:

# Start the MCP server
pnpm start

# Or run directly
node dist/server.js

MCP Client Configuration

Below are example configurations for popular MCP-capable agents. All examples launch this server over stdio. Replace ${API_FOOTBALL_KEY} with your key or rely on your shell environment.

  • Claude Desktop (claude_desktop_config.json):
{
  "mcpServers": {
    "api-football": {
      "command": "node",
      "args": ["dist/server.js"],
      "env": {
        "API_FOOTBALL_KEY": "${API_FOOTBALL_KEY}",
        "NODE_ENV": "production",
        "LOG_TO_FILE": "true",
        "LOG_DIR": "./logs",
        "LOG_ROTATE_INTERVAL": "1d"
      }
    }
  }
}
  • Claude Code (VS Code settings.json):
{
  "claudeCode.mcpServers": [
    {
      "name": "api-football",
      "command": "node",
      "args": ["dist/server.js"],
      "env": {
        "API_FOOTBALL_KEY": "${API_FOOTBALL_KEY}",
        "NODE_ENV": "production",
        "LOG_TO_FILE": "true",
        "LOG_DIR": "./logs"
      }
    }
  ]
}
  • Cursor (settings JSON):
{
  "mcpServers": {
    "api-football": {
      "command": "node",
      "args": ["dist/server.js"],
      "env": {
        "API_FOOTBALL_KEY": "${API_FOOTBALL_KEY}",
        "NODE_ENV": "production",
        "LOG_TO_FILE": "true",
        "LOG_DIR": "./logs"
      }
    }
  }
}
  • Gemini (CLI/desktop MCP support):
{
  "mcpServers": {
    "api-football": {
      "command": "node",
      "args": ["dist/server.js"],
      "env": {
        "API_FOOTBALL_KEY": "${API_FOOTBALL_KEY}",
        "NODE_ENV": "production",
        "LOG_TO_FILE": "true",
        "LOG_DIR": "./logs"
      }
    }
  }
}
  • Codex CLI (local agent):
{
  "mcpServers": {
    "api-football": {
      "command": "node",
      "args": ["dist/server.js"],
      "env": {
        "API_FOOTBALL_KEY": "${API_FOOTBALL_KEY}",
        "NODE_ENV": "production",
        "LOG_TO_FILE": "true",
        "LOG_DIR": "./logs"
      }
    }
  }
}

Tools available to agents include: get_standings, get_fixtures, get_team, get_player, get_squad, get_match_goals, get_match_events, get_live_matches, search_teams, search_players, get_rate_limit.

CLI Tools

Server Management
# Start server with custom settings
node dist/cli/server.js start --log-level debug --verbose

# Check server health
node dist/cli/server.js health

# Validate configuration
node dist/cli/server.js validate --dry-run

# List available MCP tools
node dist/cli/server.js tools

# Show cache statistics
node dist/cli/server.js cache --verbose
API Client CLI
# Get current season standings
node dist/cli/api-client.js --endpoint standings

# Get fixtures for a specific date range
node dist/cli/api-client.js --endpoint fixtures season=2023 from=2023-01-01 to=2023-01-31

# Search for a team
node dist/cli/api-client.js --endpoint teams search="Arsenal"

# Get player information
node dist/cli/api-client.js --endpoint player id=276 --format table

# Get goal events for a fixture
node dist/cli/api-client.js --endpoint goals fixture=123456 --format table

# Check rate limit status
node dist/cli/api-client.js --endpoint rate-limit --format table
Cache Management CLI
# View cache statistics
node dist/cli/cache.js stats --format table

# List cached keys
node dist/cli/cache.js keys

# Find keys by pattern
node dist/cli/cache.js find "standings:*"

# Clear cache
node dist/cli/cache.js clear

# Get specific cached value
node dist/cli/cache.js get "standings:2023"

Configuration

Environment Variables

VariableDescriptionDefault
API_FOOTBALL_KEYRequired. Your API-Football API key-
NODE_ENVEnvironment modedevelopment
LOG_LEVELLogging level (debug, info, warn, error)info
LOG_FORMATLog format (json, text)json
LOG_TO_FILEEnable file logging (pino)false
LOG_DIRDirectory for logs when LOG_TO_FILE=true./logs
LOG_ROTATE_INTERVALRotation interval (when rotating transport available)1d
LOG_ROTATE_SIZERotation size threshold (when available)10M
CACHE_MAX_SIZEMaximum cache entries1000
CACHE_TTLCache TTL in milliseconds300000 (5 minutes)
API_TIMEOUTAPI request timeout in milliseconds15000 (15 seconds)
API_BASE_URLAPI-Football base URLhttps://v3.football.api-sports.io

Cache Policies

The server uses different cache TTL values based on data type:

  • Historical data (past seasons): 24 hours
  • Current season data: 5 minutes
  • Live match data: 30 seconds
  • Static data (teams, players): 1 hour

Development

Scripts

# Development
pnpm run dev          # Watch mode with hot reload
pnpm run build        # Build TypeScript
pnpm run lint:check   # Run ESLint (no fix)
pnpm run lint         # Run ESLint with --fix
pnpm run test         # Run all tests

# Offline test suite (no real API calls)
pnpm run test:offline   # unit + contract + performance (mocked)

# Online tests (may hit API-Football; respect rate limits)
pnpm run test:online

# Run specific categories
pnpm run test:unit
pnpm run test:contract
pnpm run test:performance
pnpm run test:integration

# Type checking
pnpm run check-types  # Type check without emitting

Project Structure

src/
ā”œā”€ā”€ models/           # TypeScript interfaces
│   ā”œā”€ā”€ league.ts     # League data models
│   ā”œā”€ā”€ team.ts       # Team and venue models
│   ā”œā”€ā”€ player.ts     # Player and statistics models
│   ā”œā”€ā”€ fixture.ts    # Match and fixture models
│   ā”œā”€ā”€ standing.ts   # League standings models
│   └── ...
ā”œā”€ā”€ lib/
│   ā”œā”€ā”€ api-client/   # API-Football HTTP client
│   ā”œā”€ā”€ cache/        # LRU cache with TTL
│   ā”œā”€ā”€ tools/        # MCP tool implementations
│   └── server/       # Structured logger + helpers
ā”œā”€ā”€ services/         # Business logic layer
ā”œā”€ā”€ cli/              # Command-line interfaces
ā”œā”€ā”€ config.ts         # Configuration management
└── server.ts         # MCP server entry (built to dist/server.js)

tests/
ā”œā”€ā”€ unit/             # Unit tests
ā”œā”€ā”€ integration/      # Integration tests
ā”œā”€ā”€ contract/         # API contract tests
└── performance/      # Performance tests

Testing

The project follows Test-Driven Development (TDD):

# Run all tests
pnpm test

# Run specific test categories
pnpm run test:unit
pnpm run test:integration
pnpm run test:contract
pnpm run test:performance

# Run tests in watch mode
# Offline suite (does not require API key)
pnpm run test:offline

# Online tests (require API key, respect vendor rate limits)
pnpm run test:online

Code Quality

  • ESLint: Standard style (no semicolons, 2 spaces). In tests, unused vars and non‑null assertions are relaxed. In src, unused args prefixed with _ are allowed.
  • TypeScript: Strict mode enabled
  • Vitest: Testing framework with coverage
  • Automatic formatting: ESLint autofix on save in VS Code

API Reference

Data Models

Team
interface Team {
  id: number
  name: string
  code: string
  country: string
  founded: number
  national: boolean
  logo: string
}
Player
interface Player {
  id: number
  name: string
  firstname: string
  lastname: string
  age: number
  birth: {
    date: string
    place: string
    country: string
  }
  nationality: string
  height: string
  weight: string
  injured: boolean
  photo: string
}
Fixture
interface Fixture {
  id: number
  referee: string
  timezone: string
  date: string
  timestamp: number
  periods: {
    first: number
    second: number
  }
  venue: {
    id: number
    name: string
    city: string
  }
  status: {
    long: string
    short: string
    elapsed: number
  }
}

Rate Limiting

The API-Football service has rate limits. The server handles this automatically:

  • Reads rate limit headers from API responses
  • Implements exponential backoff when limits are hit
  • Queues requests to respect rate limits
  • Caches responses to minimize API calls

Rate limit status can be monitored via:

node dist/cli/api-client.js --endpoint rate-limit --format table

Error Handling

The server provides comprehensive error handling:

  • MCP Error Codes: Standard MCP error responses
  • API Failures: Graceful handling of API errors
  • Cache Fallbacks: Serve cached data when API is unavailable
  • Request Validation: Parameter validation before API calls
  • Structured Logging: Detailed error logging for debugging

Performance

Benchmarks

  • Cache hits: < 10ms response time
  • Cache miss with API call: < 200ms average
  • Concurrent requests: Supports 100+ concurrent requests
  • Memory usage: < 100MB typical usage

Optimization Features

  • LRU Cache: Automatic eviction of least-recently-used entries
  • Connection pooling: Reuse HTTP connections
  • Compression: Gzip compression for API responses
  • Batch operations: Multiple requests with concurrency control

Troubleshooting

Common Issues

  1. API Key Invalid

    Error: API key is required
    

    Solution: Set API_FOOTBALL_KEY environment variable

  2. Rate Limit Exceeded

    Warn: Rate limit hit, waiting 30000ms
    

    Solution: Server automatically handles this, wait for reset

  3. Cache Performance

    # Check cache statistics
    node dist/cli/cache.js stats --format table
    
    # Clear cache if needed
    node dist/cli/cache.js clear
    

Debug Mode

Enable debug logging:

export LOG_LEVEL=debug
pnpm start

Contributing

  1. Follow TDD: Write tests before implementation
  2. Code Style: Use ESLint standard configuration
  3. Type Safety: Maintain strict TypeScript compliance
  4. Documentation: Update README for new features
  5. Testing: Ensure all tests pass before submitting

Pull Request Process

  1. Create feature branch from main
  2. Write tests for new functionality
  3. Implement features with TypeScript
  4. Run full test suite: pnpm test
  5. Check linting: pnpm run lint
  6. Submit pull request with description

Constitution & Governance

This project follows an internal development constitution for MCP servers (.specify/memory/constitution.md):

  • Protocol: JSON‑RPC 2.0 over stdio via @modelcontextprotocol/sdk
  • TypeScript‑first, strict type safety across tools and client integration
  • Clear error formatting, retry with exponential backoff, and rate‑limit awareness
  • Documented tools, validated inputs, sanitized outputs, and caching strategy

Please keep changes aligned with these principles.

License

MIT License - see the file for details.

Support


Built with ā¤ļø using TypeScript, Node.js, and the Model Context Protocol.

  • Rate Limiting for Agents
    • Use the get_rate_limit tool to inspect the current limit, remaining, and recommended wait time.
    • The server applies exponential backoff on 429 and tracks vendor headers. Tests space calls by ~3.5s.
    • Best practices for agents:
      • Batch related queries and cache where possible
      • Pace calls (>= 3.5s apart) during exploration
      • Handle 429 and retry after the suggested delay
      • Prefer season filters to reduce payload sizes