足球数据API服务器

一个通过API‑Football v3提供英超联赛数据的Model Context Protocol (MCP)服务器,支持历史数据、实时比赛事件、球队和球员信息查询,并具有智能缓存和速率限制功能。

  • by MarvDann
  • TypeScript
  • 本地部署
  • 1 星标
  • 更新于
在 GitHub 查看 MarvDann/api-football-mcp

使用说明

API-足球MCP服务器

一个通过API-Sports的API-Football v3提供英超联赛数据的模型上下文协议(MCP)服务器。该服务器采用TypeScript编写,具有严格的类型检查、强大的错误处理能力,以及为代理工作流设计的合理缓存机制。

特点/功能

  • 历史覆盖范围英超联赛历史数据(许多终点指标通常涵盖2002年至今;部分工具在数据可得的情况下支持1992年及以后的数据)
  • 实时数据实时比赛赛事、当前积分榜及赛程信息
  • 智能缓存带TTL的LRU缓存以实现最佳性能
  • 速率限制内置速率限制跟踪和指数退避机制
  • MCP集成原生模型上下文协议对大型语言模型(LLM)集成的支持
  • TypeScript严格的TypeScript配置(禁用未检查的索引访问,精确可选属性类型)

MCP 工具

工具 描述 参数
get_standings 获取英超联赛积分榜 season? (数字)
get_fixtures 获取比赛赛程 season?, teamId?, date?, from?, to?, status?, round?
get_team 获取球队信息及可选赛季阵容 teamId? 或者 name?, season?
get_player 获取玩家资料和统计数据 playerId? 或者 name?, season?
get_match_goals 获取比赛的进球事件 fixtureId (必填)
get_match_events 获取比赛的所有事件 fixtureId (必填)
get_squad 为一个赛季组建一支球队阵容 teamId (必填), season (必填)
search_teams 按名称搜索团队 query?, season?
search_players 搜索玩家 query (必填), team?, season?, page?
get_live_matches 获取当前正在进行的比赛 无
get_rate_limit 获取当前API速率限制状态 无

数据覆盖说明

  • 通过API‑Football v3获取的英格兰足球超级联赛历史数据,通常从2002赛季开始即可获取。更早的赛季(2002年之前)可能不完整或无法获取,具体取决于特定的接口端点。
  • 如果您需要特定赛季的球队,请使用 season 和,与,带有 get_team (内部使用 /players (端点)或CLI(命令行界面) --endpoint squad team=<id> season=<YYYY> 助手,它会汇总所有页面并打印出一个不包含图片URL的简洁表格。
  • 支持固定查询 round 以……的形式 "Regular Season - N" 除了……之外 season, date,和 from/to。

安装

先决条件

  • Node.js 22及以上版本
  • pnpm 包管理器
  • API‑Football API密钥来自 API‑Sports

设置

  1. 克隆仓库

    git clone https://github.com/MarvDann/api-football-mcp.git
    cd api-football-mcp
    
  2. 安装依赖项

    pnpm install
    
  3. 配置环境

    # 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. 构建项目

    pnpm run build
    

使用方法

作为MCP服务器

主要用例是作为大型语言模型(LLM)集成的机器通信协议(MCP)服务器:

# Start the MCP server
pnpm start

# Or run directly
node dist/server.js

MCP客户端配置

以下是支持MCP的流行代理的示例配置。所有示例均通过stdio启动此服务器。请将${API_FOOTBALL_KEY}替换为您的密钥或依赖您的shell环境。

  • Claude 桌面版(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 配置(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"
      }
    }
  ]
}
  • 光标(设置 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"
      }
    }
  }
}
  • 双子座(支持CLI/桌面MCP):
{
  "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(本地代理):
{
  "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"
      }
    }
  }
}

代理可用的工具包括:获取排名 (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)

服务器管理

# 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 客户端命令行界面

# 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 (table output includes venue details)
node dist/cli/api-client.js --endpoint teams search="Arsenal"

# Get detailed team info for a specific season
node dist/cli/api-client.js --endpoint team id=42 season=2024

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

# Get a club's full season squad (multi-page fetch, compact table without photo URLs)
node dist/cli/api-client.js --endpoint squad team=33 season=2025

# 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

缓存管理命令行界面(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"

配置

环境变量

变量 描述 默认值
API_FOOTBALL_KEY 必需的您的API-Football API密钥 -
NODE_ENV 环境模式 development
LOG_LEVEL 日志级别(调试、信息、警告、错误) info
LOG_FORMAT 日志格式(json,text) json
LOG_TO_FILE 启用文件日志记录(pino) false
LOG_DIR 日志目录(当...时) LOG_TO_FILE=true ./logs
LOG_ROTATE_INTERVAL 旋转间隔(当可用旋转运输时) 1d
LOG_ROTATE_SIZE 旋转尺寸阈值(如有) 10M
CACHE_MAX_SIZE 最大缓存条目数 1000
CACHE_TTL 缓存TTL(生存时间)以毫秒为单位 300000 (5分钟)
API_TIMEOUT API请求超时时间(毫秒) 15000 (15秒)
API_BASE_URL API-足球基础URL https://v3.football.api-sports.io

缓存策略

服务器根据数据类型使用不同的缓存TTL(生存时间)值:

  • 历史数据 (过往季节):24小时
  • 当前赛季数据5分钟
  • 实时比赛数据30秒
  • 静态数据 (队伍,球员):1小时

发展

脚本

# 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

项目结构

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

测试

该项目遵循测试驱动开发(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

代码质量

  • **ESLint(埃斯利恩特,一种JavaScript代码静态分析工具)**标准风格(不使用分号,两个空格)。在测试中,对未使用的变量和非空断言的要求较为宽松。在源代码中,对以(此处原文未完整,假设后续为某前缀或关键字)开头的未使用参数的要求较为宽松 _ 被允许。
  • TypeScript严格模式已启用
  • Vitest带有覆盖率的测试框架
  • 自动格式化在VS Code中保存时自动修复ESLint

API 参考文档

数据模型

团队

interface Team {
  id: number
  name: string
  code: string
  country: string
  founded: number
  national: boolean
  logo: string
}

玩家

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

速率限制

API-Football服务有速率限制。服务器会自动处理:

  • 读取速率限制头部信息 来自API响应
  • 实现指数退避算法 当达到限制时
  • 请求队列 遵守速率限制
  • 缓存响应 为了最小化API调用

速率限制状态可以通过以下方式监控:

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

错误处理

服务器提供了全面的错误处理功能:

  • MCP 错误代码标准的MCP错误响应
  • API故障优雅地处理API错误
  • 缓存回退机制当API不可用时,提供缓存数据
  • 请求验证API调用前的参数验证
  • 结构化日志记录详细的错误日志记录,用于调试

演出

基准(或标准)

  • 缓存命中< 10毫秒响应时间
  • API调用时发生缓存未命中平均<200毫秒
  • 并发请求支持100+并发请求
  • 内存使用情况100MB以内,典型使用量

优化特性

  • LRU 缓存自动驱逐最近最少使用的条目
  • 连接池重用HTTP连接
  • 压缩API响应的Gzip压缩
  • 批处理操作带有并发控制的多个请求

故障排除

常见问题

  1. API密钥无效

    Error: API key is required
    

    解决方案:设置 API_FOOTBALL_KEY 环境变量

  2. 速率限制已超出

    Warn: Rate limit hit, waiting 30000ms
    

    解决方案:服务器会自动处理此问题,请等待重置

  3. 缓存性能

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

调试模式

启用调试日志记录:

export LOG_LEVEL=debug
pnpm start

贡献;助力

  1. **遵循测试驱动开发(TDD)**在实现之前编写测试
  2. 代码风格使用 ESLint 标准配置
  3. 类型安全保持严格的TypeScript合规性
  4. 文档更新README文件以包含新功能
  5. 测试在提交前确保所有测试均通过

拉取请求流程

  1. 从(某个分支)创建特性分支 main
  2. 为新功能编写测试
  3. 使用TypeScript实现功能
  4. 运行完整测试套件: pnpm test
  5. 检查代码规范(或代码风格检查): pnpm run lint
  6. 提交带有描述的拉取请求

宪法与治理

此项目遵循MCP服务器的内部开发规范(.specify/memory/constitution.md):

  • 协议:通过 @modelcontextprotocol/sdk 在标准输入输出(stdio)上使用 JSON-RPC 2.0
  • 以TypeScript为先,确保工具间及客户端集成的严格类型安全性
  • 清除错误格式,使用指数退避重试,并具备速率限制意识
  • 记录工具、验证输入、净化输出以及缓存策略

请确保所做的更改符合这些原则。

许可证

MIT 许可证 - 详见 许可证 详情请参阅文件。

支持


使用TypeScript、Node.js和模型上下文协议,满怀爱意地构建而成。

  • 代理速率限制
    • 使用 get_rate_limit 用于检查当前限制、剩余时间和建议等待时间的工具。
    • 服务器在遇到429状态码时采用指数退避策略,并跟踪供应商头部信息。测试显示,空间调用大约需要3.5秒。
    • 代理的最佳实践:
      • 尽可能批量处理相关查询并使用缓存
      • 在探索过程中进行的Pace呼叫(间隔>=3.5秒)
      • 处理429错误,并在建议的延迟后重试
      • 建议使用季节性过滤器以减少有效载荷大小