Skip to content

About

A Model Context Protocol (MCP) server that provides comprehensive MLB statistics and data through the MLB Stats API. This server offers both a command-line interface and a web-based Streamlit chat interface for interacting with MLB data.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

MLB MCP Server

A Model Context Protocol (MCP) server that provides comprehensive MLB statistics and data through the MLB Stats API. This server offers both a command-line interface and a web-based Streamlit chat interface for interacting with MLB data.


Changelog

v3.0 — Anthropic SDK (No AWS Required)

Replaced AWS Bedrock + Strands Agent with the Anthropic SDK. Run the full UI with only an ANTHROPIC_API_KEY — no cloud account or IAM setup needed.

Changes:

  • streamlit_app.py rewritten with a proper Anthropic tool-use agentic loop
  • Removed boto3 and strands-agents dependencies
  • Added python-dotenv and anthropic to dependencies
  • New .env.example template for quick setup
  • Bumped version to 0.2.0

v2.0 — Baseball Strategy Agent

Added four strategic pitch-calling tools powered by MLB Statcast (via pybaseball) and an upgraded AI persona that reasons like a pitching coach.

New tools:

  • pitcher_arsenal — Statcast pitch mix, velocity, spin rate, whiff rate & xBA against per pitch type
  • batter_zone_profile — Hot/cold zone map and pitch-type weaknesses from Statcast data
  • pitcher_vs_batter — Career head-to-head matchup history via MLB Stats API
  • live_game_context — Real-time inning, ball-strike-out count, runners, score, and current batter/pitcher

Improvements:

  • Streamlit agent upgraded to a full pitching-coach persona with a structured strategy workflow
  • Added pybaseball dependency for Statcast data access (with disk caching for speed)
  • Fixed bug in lastest_season tool (typo in name, wrong API call, duplicate Python function name)
  • Pybaseball integration degrades gracefully — all original tools work even if pybaseball is unavailable

v1.0 — Initial Release

  • 17 MCP tools covering game data, schedules, rosters, standings, player stats, and league leaders
  • Streamlit chat UI with Strands Agent + AWS Bedrock (superseded in v3.0)

🖥️ User Interface Previews

Below are example screenshots from the MLB Agent Chat UI showing real interactions and analysis powered by the MCP server and Bedrock planner.

1️⃣ Game Schedule Query

MLB Agent - Game Schedule Query The agent identifies the upcoming World Series Game 5 between the Blue Jays and Dodgers, including venue, status, and probable pitchers.


2️⃣ Player Performance Analysis

MLB Agent - Player Performance Analysis The agent retrieves Vladimir Guerrero Jr.’s 2025 season statistics and generates a natural language analysis comparing key performance metrics.


3️⃣ World Series vs Regular Season Comparison

MLB Agent - World Series Comparison The system compares Guerrero Jr.’s World Series stats with his regular-season averages, demonstrating contextual reasoning using MLB data.


These screenshots highlight how the MLB Agent combines structured MCP tool outputs with contextual Bedrock analysis to produce in-depth baseball insights.

Features

Core MLB Data Tools

  • Game Information: Boxscores, highlights, scoring plays, pace data
  • Team Data: Rosters, standings, team leaders, schedules
  • Player Statistics: Individual player stats (hitting, pitching, fielding)
  • League Information: League leaders, standings by division
  • Live Data: Current games, next games, last games

Strategic / Pitch-Calling Tools (v2.0)

  • Live Game Context: Real-time inning, count, runners on base, score, current batter & pitcher
  • Pitcher Arsenal: Statcast pitch mix with usage %, velocity, spin rate, whiff rate, and xBA against
  • Batter Zone Profile: Hot/cold zone map and pitch-type exploitability from Statcast data
  • Head-to-Head Matchup: Career history between a specific pitcher and batter

Available MCP Tools (21 total)

General Data Tools

Tool Description
boxscore Formatted boxscore for a game
game_highlight_data Game highlight video links
game_pace_data Pace statistics for a season
scoring_play_data Scoring plays for a game
last_game / next_game Team's most recent / upcoming game
latest_season Current/latest MLB season info
league_leader_data League-wide statistical leaders
linescore Formatted and raw JSON linescore
lookup_player / lookup_team Search players and teams by name
player_stat_data Player stats (hitting, pitching, fielding; season or career)
roster Team roster with positions and jersey numbers
game_schedule Games by date range, team, or opponent
standings League/division standings with wildcard
team_leaders Team statistical leaders
date Current date/time

Strategic Tools (v2.0)

Tool Description
live_game_context Real-time game state: inning, count, runners, score, current matchup
pitcher_arsenal Statcast pitch mix, velocity, spin rate, whiff rate, xBA against per pitch type
batter_zone_profile Hot/cold zone map (1–14 grid) and pitch-type weaknesses from Statcast
pitcher_vs_batter Career head-to-head stats between a specific pitcher and batter

Credits

This project is built on top of the excellent MLB-StatsAPI Python library by Todd Roberts (@toddrob99). The MLB-StatsAPI library provides a clean, Pythonic interface to MLB's official Stats API and handles all the heavy lifting for data retrieval and formatting.

MLB-StatsAPI Features Used:

  • Game data retrieval (boxscores, highlights, schedules)
  • Player and team statistics
  • League standings and leader boards
  • Real-time game information
  • Historical data access

We extend our gratitude to Todd Roberts and all contributors to the MLB-StatsAPI project for making MLB data easily accessible to Python developers.

Quick Start

Prerequisites

Installation

  1. Clone the repository

    git clone <repository-url>
    cd mlb_mcp_server-main
  2. Install dependencies

    pip install anthropic mcp[cli] mlb-statsapi pybaseball streamlit python-dotenv httpx

    Or with uv:

    uv sync
  3. Run the MCP server (standalone, for testing)

    python -m mcp run mlb_mcp_server.py

Web Interface (Streamlit)

For a user-friendly chat interface:

  1. Set up environment variables — copy .env.example to .env and fill in your key:

    ANTHROPIC_API_KEY=sk-ant-...
    ANTHROPIC_MODEL=claude-sonnet-4-6
    SERVER_CMD=python mlb_mcp_server.py
  2. Run the Streamlit app:

    streamlit run streamlit_app.py

    Or with uv:

    uv run streamlit run streamlit_app.py
  3. Access the interface at http://localhost:8501

No AWS account needed. The UI uses the Anthropic SDK directly. You only need an ANTHROPIC_API_KEY.

Usage Examples

Command Line (via MCP)

# Get today's MLB standings
echo '{"method": "call_tool", "params": {"name": "standings"}}' | uv run mcp run mlb_mcp_server.py

# Get team roster
echo '{"method": "call_tool", "params": {"name": "roster", "arguments": {"team_id": 119}}}' | uv run mcp run mlb_mcp_server.py

Web Interface — General Questions

  • "Show me today's standings"
  • "Get the roster for the Dodgers"
  • "Who are the home run leaders this season?"
  • "Show me the boxscore for game 716663"

Web Interface — Baseball Strategy Agent (v2.0)

The agent now reasons like a pitching coach + catcher. It chains multiple tool calls to deliver grounded, situational advice:

Pitch-calling (catcher perspective):

"I'm catching for Gerrit Cole and we're facing Aaron Judge. Runner on second, 1-2 count in the 7th. What do I call?"

The agent will:

  1. Call pitcher_arsenal → see Cole's pitch mix and whiff rates per pitch
  2. Call batter_zone_profile → find Judge's weakest zones and pitch types
  3. Call pitcher_vs_batter → check career history in this exact matchup
  4. Deliver a structured answer: primary pitch recommendation, setup sequence, what to avoid, and situational adjustments

Batter scouting:

"What are the weaknesses of Freddie Freeman vs. right-handed pitching this season?"

Live in-game lookup:

"What's the current count and who's pitching in the Yankees game right now?"

Pitcher arsenal scouting:

"Show me Spencer Strider's pitch arsenal and which pitch has the best whiff rate"

How to get player IDs (needed for strategic tools):

First look up the player: "Look up player Gerrit Cole"
→ Returns personId: 543037
Then use that ID: pitcher_arsenal(pitcher_id=543037)

Configuration

Environment Variables

  • ANTHROPIC_API_KEY - Your Anthropic API key (required for Streamlit UI)
  • ANTHROPIC_MODEL - Claude model ID (default: claude-sonnet-4-6)
  • SERVER_CMD - Command to start MCP server (default: python mlb_mcp_server.py)

Team IDs Reference

Common MLB team IDs (see current_mlb_teams.json for complete list):

  • Los Angeles Dodgers: 119
  • New York Yankees: 147
  • Philadelphia Phillies: 143
  • Atlanta Braves: 144
  • Boston Red Sox: 111

Deployment Options

1. Local Development

# Install and run locally
uv sync
uv run streamlit run streamlit_app.py

2. Docker Deployment

Create a Dockerfile:

FROM python:3.11-slim

WORKDIR /app
COPY . .

RUN pip install uv
RUN uv sync

EXPOSE 8501

CMD ["uv", "run", "streamlit", "run", "streamlit_app.py", "--server.address", "0.0.0.0"]

Build and run:

docker build -t mlb-mcp-server .
docker run -p 8501:8501 mlb-mcp-server

3. Cloud Deployment

AWS EC2/ECS

  1. Use the Docker approach above
  2. Configure AWS credentials for Bedrock access
  3. Deploy to ECS or run on EC2 instance

Heroku

  1. Add Procfile:
    web: uv run streamlit run streamlit_app.py --server.port=$PORT --server.address=0.0.0.0
    
  2. Deploy via Git or Heroku CLI

Railway/Render

  1. Connect your GitHub repository
  2. Set environment variables in platform dashboard
  3. Use automatic deployment from main branch

Architecture

MCP Server (mlb_mcp_server.py)

  • FastMCP-based server providing MLB data tools
  • Connects to MLB Stats API via mlb-statsapi package
  • Supports both formatted text and raw JSON responses

Streamlit Interface (streamlit_app.py)

  • Web-based chat interface powered by the Anthropic SDK
  • Full agentic tool-use loop: Claude calls MCP tools and reasons over results
  • Real-time tool call display with expandable details

Dependencies

  • anthropic - Anthropic Python SDK (powers the Streamlit UI)
  • mcp[cli] - Model Context Protocol framework
  • mlb-statsapi - MLB Stats API client
  • pybaseball - Statcast & advanced analytics data (Baseball Savant, FanGraphs, Baseball Reference)
  • streamlit - Web interface framework
  • python-dotenv - Environment variable loading
  • httpx - HTTP client for API requests

API Reference

Key Tool Parameters

game_schedule

{
    "date": "MM/DD/YYYY",           # Specific date
    "start_date": "MM/DD/YYYY",     # Date range start
    "end_date": "MM/DD/YYYY",       # Date range end
    "team_id": 119,                 # Team ID
    "season": "2024"                # Season year
}

player_stat_data

{
    "personID": 545361,             # Player ID
    "group": "hitting",             # hitting/pitching/fielding
    "type": "season",               # season/career
    "season": "2024"                # Season year
}

standings

{
    "leagueID": "103,104",          # AL=103, NL=104
    "division": "all",              # Division filter
    "season": "2024",               # Season year
    "date": "MM/DD/YYYY"            # Historical date
}

pitcher_arsenal (v2.0)

{
    "pitcher_id": 543037,           # MLB player ID (MLBAM) — use lookup_player first
    "season": 2025,                 # Season year (default: current year)
    "days_back": 30                 # Optional: only last N days (faster; shows current form)
}

Returns per-pitch-type breakdown: usage_pct, avg_velocity_mph, avg_spin_rate_rpm, whiff_rate_pct, called_strike_rate_pct, xba_against.

batter_zone_profile (v2.0)

{
    "batter_id": 665742,            # MLB player ID — use lookup_player first
    "season": 2025,                 # Season year (default: current year)
    "days_back": 30,                # Optional: only last N days
    "pitcher_throws": "R"           # Optional: "L" or "R" to split by pitcher handedness
}

Returns zone_profile (14-zone hot/cold grid with whiff rates), pitch_type_splits (exploitable vs. dangerous pitches), and batter_tendencies (K%, BB%, hard-hit%).

pitcher_vs_batter (v2.0)

{
    "pitcher_id": 543037,           # MLB player ID of the pitcher
    "batter_id": 592450             # MLB player ID of the batter
}

Returns career head-to-head hitting and pitching stats from the MLB Stats API.

live_game_context (v2.0)

{
    "game_pk": 716663,              # Optional: specific game ID
    "team_id": 147                  # Optional: find live game for this team
}

Returns inning, inning_half, count (balls/strikes/outs), score, current_matchup (batter + pitcher with handedness and pitch count), and runners (which bases are occupied).

Troubleshooting

Common Issues

  1. MCP Server Won't Start

    • Ensure Python 3.11+ is installed
    • Run uv sync to install dependencies
    • Check that mlb_mcp_server.py is executable
  2. Streamlit Connection Errors

    • Verify MCP server command in environment variables
    • Check AWS credentials for Bedrock access
    • Ensure all dependencies are installed
  3. Tool Call Failures

    • Validate required parameters (team IDs, dates)
    • Check MLB Stats API availability
    • Review error logs for specific issues
  4. pitcher_arsenal / batter_zone_profile Return No Data

    • These tools pull from Baseball Savant (Statcast). Data is only available during and after the regular season.
    • If the player ID is wrong, no data is returned — use lookup_player first to confirm the correct ID.
    • Try a smaller days_back value (e.g., days_back=30) for recent-form queries; full-season pulls are larger.
    • First-run queries are slow (fetching from Baseball Savant); subsequent calls for the same player/date range are instant thanks to disk caching.
  5. pitcher_vs_batter Returns Empty Stats

    • The MLB Stats API only records head-to-head history when both players have appeared in the same game. New players or rare matchups may return empty.
  6. live_game_context Returns "No games in progress"

    • Check that a game is actually live. The tool returns today's full schedule so you can see upcoming games.
    • Supply a team_id to narrow to a specific team's game.

Debug Mode

Enable debug logging by setting:

logging.basicConfig(level=logging.DEBUG)

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests if applicable
  5. Submit a pull request

License

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

The underlying MLB-StatsAPI library is also open source - see their repository for license information.

Support

For issues and questions:

  1. Check the troubleshooting section above
  2. Review the MLB-StatsAPI documentation
  3. Review the MLB Stats API documentation
  4. Open an issue in the repository

Related Projects


Note: This server requires internet access to connect to the MLB Stats API. Some features may be limited during MLB off-season or maintenance periods.

About

A Model Context Protocol (MCP) server that provides comprehensive MLB statistics and data through the MLB Stats API. This server offers both a command-line interface and a web-based Streamlit chat interface for interacting with MLB data.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages