Skip to main content
Glama
mlb-api-mcp

mlb-api-mcp

by guillochon

MLB API MCP Server

CI Status License Coverage

A Model Context Protocol (MCP) server that provides comprehensive access to MLB statistics and baseball data through a FastMCP-based interface.

Overview

This MCP server acts as a bridge between AI applications and MLB data sources, enabling seamless integration of baseball statistics, game information, player data, and more into AI workflows and applications.

Related MCP server: MLB Projections MCP Server

Features

MLB Data Access

  • Current standings for all MLB teams with flexible filtering by league, season, and date

  • Game schedules and results with date range support

  • Player statistics including traditional and sabermetric stats (WAR, wOBA, wRC+)

  • Team information and rosters with various roster types

  • Live game data including boxscores, linescores, and play-by-play

  • Game highlights and scoring plays

  • Player and team search functionality

  • Draft information and award recipients

  • Game pace statistics and lineup information

MCP Tools

All MLB/statistics/game/player/team/etc. functionality is exposed as MCP tools, not as RESTful HTTP endpoints. These tools are accessible via the /mcp/ endpoint using the MCP protocol. For a list of available tools and their descriptions, visit /tools/ when the server is running.

Key MCP Tools

  • get_mlb_standings - Current MLB standings with league and season filters

  • get_mlb_schedule - Game schedules for specific dates, ranges, or teams

  • get_mlb_team_info - Detailed team information

  • get_mlb_player_info - Player biographical information

  • get_mlb_boxscore - Complete game boxscores

  • get_mlb_linescore - Inning-by-inning game scores

  • get_mlb_game_highlights - Video highlights for games

  • get_mlb_game_scoring_plays - Play-by-play data with event filtering

  • get_mlb_game_pace - Game duration and pace statistics

  • get_mlb_game_lineup - Detailed lineup information for games

  • get_multiple_mlb_player_stats - Traditional player statistics

  • get_mlb_sabermetrics - Advanced sabermetric statistics (WAR, wOBA, etc.)

  • get_mlb_roster - Team rosters with various roster types

  • get_mlb_search_players - Search players by name

  • get_mlb_search_teams - Search teams by name

  • get_mlb_players - All players for a sport/season

  • get_mlb_teams - All teams for a sport/season

  • get_mlb_draft - Draft information by year

  • get_mlb_awards - Award recipients

  • get_current_date - Current date

  • get_current_time - Current time

For the full list and detailed descriptions, see /tools/ or /docs when the server is running.

HTTP Endpoints

The following HTTP endpoints are available:

  • / - Redirects to /docs

  • /docs - Interactive API documentation and tool listing

  • /health/ - Health check endpoint

  • /mcp/info - MCP server information

  • /tools/ - List of all available MCP tools

  • /mcp/ (POST) - MCP protocol endpoint for MCP-compatible clients

Note: There are no RESTful HTTP endpoints for MLB/statistics/game/player/team/etc. All such functionality is accessed via MCP tools through the /mcp/ endpoint.

MCP Integration

  • Compatible with MCP-enabled AI applications

  • Tool-based interaction model with comprehensive endpoint descriptions

  • Automatic API documentation generation

  • Schema validation and type safety

  • Full response schema descriptions for better AI integration

Installation

Installing via Smithery

To install MLB API Server for Claude Desktop automatically via Smithery:

npx -y @smithery/cli install @guillochon/mlb-api-mcp --client claude

Option 1: Local Installation

  1. Install uv if you haven't already:

curl -LsSf https://astral.sh/uv/install.sh | sh
  1. Clone the repository:

git clone https://github.com/guillochon/mlb-api-mcp.git
cd mlb-api-mcp
  1. Create and activate a virtual environment:

uv venv
source .venv/bin/activate  # On Unix/macOS
# or
.venv\Scripts\activate  # On Windows
  1. Install dependencies:

uv pip install -e .

Option 2: Docker Installation

  1. Clone the repository:

git clone https://github.com/guillochon/mlb-api-mcp.git
cd mlb-api-mcp
  1. Build the Docker image:

docker build -t mlb-api-mcp .
  1. Run the container (default timezone is UTC, uses Python 3.12):

docker run -p 8000:8000 mlb-api-mcp

Setting the Timezone

To run the container in your local timezone, pass the TZ environment variable (e.g., for New York):

docker run -e TZ=America/New_York -p 8000:8000 mlb-api-mcp

Replace America/New_York with your desired IANA timezone name.

The server will be available at http://localhost:8000 with:

  • MCP Server: http://localhost:8000/mcp/

  • Documentation: http://localhost:8000/docs

Docker Options

You can also run the container with additional options:

# Run in detached mode
docker run -d -p 8000:8000 --name mlb-api-server mlb-api-mcp

# Run with custom port mapping
docker run -p 3000:8000 mlb-api-mcp

# View logs
docker logs mlb-api-server

# Stop the container
docker stop mlb-api-server

# Remove the container
docker rm mlb-api-server

Usage

Starting the Server

Run the MCP server locally:

# For stdio transport (default, for MCP clients like Smithery)
uv run python main.py

# For HTTP transport (for web access)
uv run python main.py --http

The server will start with:

  • MCP Server on http://localhost:8000/mcp/

  • Interactive API documentation available at http://localhost:8000/docs

MCP Client Integration

This server can be integrated into any MCP-compatible application. The server provides tools for:

  • Retrieving team standings and schedules

  • Getting comprehensive player and team statistics

  • Accessing live game data and historical records

  • Searching for players and teams

  • Fetching sabermetric statistics like WAR

  • And much more...

API Documentation

Once the server is running, visit http://localhost:8000/docs for comprehensive API documentation including:

  • Available HTTP endpoints

  • List of all available MCP tools at /tools/

  • Tool descriptions and parameters

  • Interactive testing interface

  • Parameter descriptions and examples

Dependencies

  • mcp[cli]: MCP-compliant server framework with CLI support

  • FastAPI: Web framework for HTTP transport

  • python-mlb-statsapi: Official MLB Statistics API wrapper

  • uvicorn[standard]: ASGI server for running the app

  • websockets: WebSocket support (latest version to avoid deprecation warnings)

  • python-dotenv: Environment variable management

  • httpx: HTTP client for API requests

Development

This project uses:

  • Python 3.10+ (Docker uses Python 3.12)

  • FastMCP for the web framework

  • uv for fast Python package management

  • Hatchling for build management

  • MLB Stats API for comprehensive baseball data access

  • Ruff for linting and formatting

Setup Pre-commit Hooks

  1. Install pre-commit:

pip install pre-commit
  1. Initialize pre-commit hooks:

pre-commit install

Now, the linting checks will run automatically whenever you commit code. You can also run them manually:

pre-commit run --all-files

Contributing

Contributions are welcome! Please feel free to submit issues or pull requests.

License

This project is open source. Please check the license file for details.

Testing

This project includes comprehensive test coverage with pytest and coverage reporting.

Running Tests

# Run all tests with coverage (default)
uv run pytest

# Run tests with verbose output
uv run pytest -v

# Run specific test file
uv run pytest tests/test_mlb_api.py

# Run specific test function
uv run pytest tests/test_mlb_api.py::test_get_mlb_standings

# Run tests without coverage
uv run tests/run_coverage.py test

# Generate HTML coverage report
uv run tests/run_coverage.py html

# Clean up coverage files
uv run tests/run_coverage.py clean

Coverage

  • Current Coverage: 89.91% (exceeds 80% threshold)

  • Coverage Source: mlb_api.py and generic_api.py

  • Reports: Terminal output, HTML (htmlcov/index.html), and XML (coverage.xml)

  • CI Integration: Coverage checking runs automatically on every push/PR; results are published in the GitHub Actions job summary

Test Structure

The test suite includes:

  • Unit tests for all MCP tools (MLB API and Generic API)

  • Error handling tests for API failures

  • Edge case tests for boundary conditions

  • Mock-based tests to avoid external API calls

Live-API Scan

The mocked test suite protects this repo's own logic but does not exercise the real upstream MLB Stats API / pybaseball services, whose response shapes are outside this repo's control. To verify the tools still work against live data (e.g. after upstream field renames or contract changes), run the one-time scan:

# Invokes every registered tool against the real upstream API and prints a
# pass/fail summary plus the top-level return type of each result.
uv run python scripts/scan_live_tools.py

The scan writes a full JSON report to scripts/live_scan_report.json (gitignored). This is a manual verification pass, not part of the automated CI suite.

Adding New Tests

When adding new functionality:

  1. Add corresponding test cases to tests/test_mlb_api.py

  2. Include both success and error scenarios

  3. Use mocking to avoid external dependencies

  4. Ensure coverage remains above 80%

Example test structure:

def test_new_function_success(mcp):
    """Test successful execution of new function"""
    new_function = get_tool(mcp, 'new_function')
    with patch('mlb_api.external_api_call', return_value={'data': 'success'}):
        result = new_function(param='value')
        assert 'data' in result

def test_new_function_error_handling(mcp):
    """Test error handling in new function"""
    new_function = get_tool(mcp, 'new_function')
    with patch('mlb_api.external_api_call', side_effect=Exception("API Error")):
        result = new_function(param='value')
        assert 'error' in result

Available Tools

24 tools
get_current_dateA

Get the current date.

Returns: str: The current date in YYYY-MM-DD format

Inputs: no named parameters. Returns: result

get_current_timeA

Get the current time.

Returns: str: The current time in HH:MM:SS format

Inputs: no named parameters. Returns: result

get_mlb_awardsC

Get award recipients for a specific award.

Args: award_id (int): Award ID.

Returns: dict: Award recipients.

Inputs: award_id (required). Returns: object

get_mlb_boxscoreB

Get boxscore for a specific game by game_id.

Args: game_id (int): The game ID. timecode (Optional[str]): Specific timecode for the boxscore snapshot. fields (Optional[str]): Comma-separated list of fields to include.

Returns: dict: Boxscore information.

Inputs: game_id (required), timecode, fields. Returns: object

get_mlb_draftC

Get draft information for a specific year.

Args: year_id (int): Draft year.

Returns: dict: Draft information.

Inputs: year_id (required). Returns: object

get_mlb_game_highlightsB

Get game highlights for a specific game by game_id.

Args: game_id (int): The game ID.

Returns: dict: Game highlights.

Inputs: game_id (required). Returns: object

get_mlb_game_lineupC

Get lineup information for a specific game by game_id.

Args: game_id (int): The game ID.

Returns: dict: Game lineup information.

Inputs: game_id (required). Returns: object

get_mlb_game_paceC

Get game pace statistics for a given season.

Args: season (int): Season year. sport_id (int): Sport ID (default: 1 for MLB).

Returns: dict: Game pace statistics.

Inputs: season (required), sport_id. Returns: object

get_mlb_game_scoring_playsB

Get plays for a specific game by game_id, with optional filtering by eventType.

Args: game_id (int): The game ID. eventType (Optional[str]): Filter plays by this event type (e.g., 'scoring_play', 'home_run'). timecode (Optional[str]): Specific timecode for the play-by-play snapshot. fields (Optional[str]): Comma-separated list of fields to include.

Returns: dict: Game plays, optionally filtered by eventType.

Inputs: game_id (required), eventType, timecode, fields. Returns: object

get_mlb_linescoreB

Get linescore for a specific game by game_id.

Args: game_id (int): The game ID.

Returns: dict: Linescore information.

Inputs: game_id (required). Returns: object

get_mlb_player_infoB

Get information about a specific player by ID.

Args: player_id (int): The player ID.

Returns: dict: Player information.

Inputs: player_id (required). Returns: object

get_mlb_playersB

Get all players for a specific sport.

Args: sport_id (int): Sport ID (default: 1 for MLB). season (Optional[int]): Filter players by a specific season (year).

Returns: dict: All players for the specified sport.

Inputs: sport_id, season. Returns: object

get_mlb_rosterB

Get team roster for a specific team (ID or name), with optional filters.

Args: team (str): Team ID or team name as a string. Can be numeric string, full name, abbreviation, or location. date (Optional[str]): Date in 'YYYY-MM-DD' format. If not provided, defaults to today. rosterType (Optional[str]): Filter by roster type (e.g., 40Man, fullSeason, etc.). season (Optional[str]): Filter by single season (year). hydrate (Optional[str]): Additional data to hydrate in the response. fields (Optional[str]): Comma-separated list of fields to include.

Returns: dict: Team roster information.

Inputs: team (required), date, rosterType, season, +2 more. Returns: object

get_mlb_sabermetricsA

Get sabermetric statistics (including WAR) for multiple players for a specific season.

Args: player_ids (str): Comma-separated list of player IDs. season (int): Season year. stat_name (Optional[str]): Specific sabermetric stat to extract (e.g., 'war', 'woba', 'wRc'). group (str): Stat group ('hitting' or 'pitching').

Returns: dict: Sabermetric statistics.

Inputs: player_ids (required), season (required), stat_name, group. Returns: object

get_mlb_scheduleA

Get MLB schedule for a specific date range, sport ID, or team (ID or name).

Args: sport_id (int): Sport ID (default: 1 for MLB). start_date (str): Start date in 'YYYY-MM-DD' format. Required. end_date (str): End date in 'YYYY-MM-DD' format. Required. team (Optional[str]): Team ID or team name as a string. Can be numeric string, full name, abbreviation, or location. If not provided, defaults to all teams.

Returns: dict: Schedule data for the specified parameters.

Inputs: start_date (required), end_date (required), sport_id, team. Returns: object

get_mlb_search_playersB

Search for players by name.

Args: fullname (str): Player name to search for. sport_id (int): Sport ID (default: 1 for MLB). search_key (str): Search key (default: "fullname").

Returns: dict: Player search results.

Inputs: fullname (required), sport_id, search_key. Returns: object

get_mlb_search_teamsB

Search for teams by name or ID.

Args: team_name (str): Team name or ID to search for. search_key (str): Search key ("name", "id", or "all").

Returns: dict: Team search results.

Inputs: team_name (required), search_key. Returns: object

get_mlb_standingsA

Get current MLB standings for a given season (year).

Args: season (Optional[int]): The year for which to retrieve standings. Defaults to current year. standingsTypes (Optional[str]): The type of standings to retrieve (e.g., 'regularSeason', 'wildCard', etc.). date (Optional[str]): Date in 'YYYY-MM-DD' format. hydrate (Optional[str]): Additional data to hydrate in the response. fields (Optional[str]): Comma-separated list of fields to include in the response. league (str): Filter by league. Accepts 'AL', 'NL', or 'both' (default: 'both').

Returns: dict: Standings for the specified league(s) and season.

Inputs: season, standingsTypes, date, hydrate, +2 more. Returns: object

get_mlb_team_infoC

Get information about a specific team by ID or name.

Args: team (str): Team ID or team name as a string. Can be numeric string, full name, abbreviation, or location. season (Optional[int]): Season year. sport_id (Optional[int]): Sport ID. hydrate (Optional[str]): Additional data to hydrate. fields (Optional[str]): Comma-separated list of fields to include.

Returns: dict: Team information.

Inputs: team (required), season, sport_id, hydrate, +1 more. Returns: object

get_mlb_teamsA

Get all teams for a specific sport.

Args: sport_id (int): Sport ID (default: 1 for MLB). season (Optional[int]): Filter teams by a specific season (year).

Returns: dict: All teams for the specified sport.

Inputs: sport_id, season. Returns: object

get_multiple_mlb_player_statsC

Get player stats by comma separated player_ids, group, type, season, and optional eventType.

Args: player_ids (str): Comma-separated list of player IDs. group (Optional[str]): Stat group (e.g., hitting, pitching). type (Optional[str]): Stat type (e.g., season, career). season (Optional[int]): Season year. eventType (Optional[str]): Event type filter.

Returns: dict: Player statistics.

Inputs: player_ids (required), group, type, season, +1 more. Returns: object

get_statcast_batterA

Retrieve MLB Statcast data for a single batter over a date range.

Parameters

player_id : int MLBAM ID of the batter. start_date : str The start date in 'YYYY-MM-DD' format. Required. end_date : str The end date in 'YYYY-MM-DD' format. Required.

Returns

dict Dictionary with Statcast data for the batter. If the result is too large, returns an error message.

Notes

Data is sourced from MLB Statcast via pybaseball. See the official documentation for more details: https://github.com/jldbc/pybaseball/tree/master/docs

Inputs: player_id (required), start_date (required), end_date (required). Returns: object

get_statcast_pitcherA

Retrieve MLB Statcast data for a single pitcher over a date range.

Parameters

player_id : int MLBAM ID of the pitcher. start_date : str The start date in 'YYYY-MM-DD' format. Required. end_date : str The end date in 'YYYY-MM-DD' format. Required.

Returns

dict Dictionary with Statcast data for the pitcher. If the result is too large, returns an error message.

Notes

Data is sourced from MLB Statcast via pybaseball. See the official documentation for more details: https://github.com/jldbc/pybaseball/tree/master/docs

Inputs: player_id (required), start_date (required), end_date (required). Returns: object

get_statcast_teamA

Retrieve MLB Statcast data for all players on a team over a date range.

Parameters

team : str Team ID or team name (see MLB team list for valid values). start_date : str The start date in 'YYYY-MM-DD' format. Required. end_date : str The end date in 'YYYY-MM-DD' format. Required. fields: List[str] The field to return. If not provided, defaults to all fields. Available fields: pitch_type, game_date, release_speed, release_pos_x, release_pos_z, player_name, batter, pitcher, events, description, spin_dir, spin_rate_deprecated, break_angle_deprecated, break_length_deprecated, zone, des, game_type, stand, p_throws, home_team, away_team, type, hit_location, bb_type, balls, strikes, game_year, pfx_x, pfx_z, plate_x, plate_z, on_3b, on_2b, on_1b, outs_when_up, inning, inning_topbot, hc_x, hc_y, tfs_deprecated, tfs_zulu_deprecated, umpire, sv_id, vx0, vy0, vz0, ax, ay, az, sz_top, sz_bot, hit_distance_sc, launch_speed, launch_angle, effective_speed, release_spin_rate, release_extension, game_pk, fielder_2, fielder_3, fielder_4, fielder_5, fielder_6, fielder_7, fielder_8, fielder_9, release_pos_y, estimated_ba_using_speedangle, estimated_woba_using_speedangle, woba_value, woba_denom, babip_value, iso_value, launch_speed_angle, at_bat_number, pitch_number, pitch_name, home_score, away_score, bat_score, fld_score, post_away_score, post_home_score, post_bat_score, post_fld_score, if_fielding_alignment, of_fielding_alignment, spin_axis, delta_home_win_exp, delta_run_exp, bat_speed, swing_length, estimated_slg_using_speedangle, delta_pitcher_run_exp, hyper_speed, home_score_diff, bat_score_diff, home_win_exp, bat_win_exp, age_pit_legacy, age_bat_legacy, age_pit, age_bat, n_thruorder_pitcher, n_priorpa_thisgame_player_at_bat, pitcher_days_since_prev_game, batter_days_since_prev_game, pitcher_days_until_next_game, batter_days_until_next_game, api_break_z_with_gravity, api_break_x_arm, api_break_x_batter_in, arm_angle, attack_angle, attack_direction, swing_path_tilt, intercept_ball_minus_batter_pos_x_inches, intercept_ball_minus_batter_pos_y_inches Returns

dict Dictionary with Statcast data for all players on the team. If the result is too large, returns an error message. Notes

This uses the pybaseball statcast function, which returns all Statcast events for the specified team and date range. See the official documentation for more details: https://github.com/jldbc/pybaseball/tree/master/docs

Inputs: team (required), start_date (required), end_date (required), fields (required). Returns: object

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    B3.4/5.0

    Scored across 24 tools

    Disambiguation4/5

    Most tools have distinct purposes targeting specific MLB resources like games, players, teams, and statistics. However, some overlap exists between get_mlb_player_info and get_mlb_players, and between get_mlb_team_info and get_mlb_teams, which could cause minor confusion. The Statcast tools are clearly differentiated by batter/pitcher/team focus.

    Naming Consistency5/5

    All tools follow a consistent get_* prefix pattern with snake_case naming. The naming convention is uniform throughout, with clear verb_noun structure (e.g., get_mlb_boxscore, get_mlb_schedule, get_statcast_batter). No mixing of naming styles or inconsistent patterns.

    Tool Count3/5

    24 tools is borderline heavy for an MLB API server. While MLB has many data dimensions, this feels like it could be consolidated (e.g., multiple player/team retrieval tools). The count suggests potential redundancy rather than comprehensive coverage of distinct operations.

    Completeness4/5

    The toolset provides extensive read-only coverage of MLB data including games, players, teams, statistics, and advanced metrics. Minor gaps exist in write operations (no create/update/delete tools) and some specialized queries, but for a data retrieval API this is reasonably complete for agent workflows.

    Maintenance

    ActivityInactive
    ResponsivenessLimited data

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      A
      quality
      D
      maintenance
      An MCP Server implementation that integrates the Balldontlie API, to provide information about players, teams and games for the NBA, NFL and MLB.
      4
      86 npm
      26
      MIT
    • F
      license
      Not graded
      quality
      D
      maintenance
      An MCP server that enables interaction with MLB (Major League Baseball) v3 projections through the SportsData.io API, allowing access to baseball statistics and projections through natural language.
      -
    • F
      license
      Not graded
      quality
      D
      maintenance
      An MCP Server that enables interaction with MLB scores and statistics via the SportsData.io MLB V3 Scores API, allowing users to access baseball data through natural language queries.
      -
    • F
      license
      Not graded
      quality
      D
      maintenance
      An MCP server for accessing college basketball statistics through the SportsData.io CBB v3 Stats API, enabling AI agents to retrieve and analyze college basketball data through natural language interactions.
      -