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.
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.pyrewritten with a proper Anthropic tool-use agentic loop- Removed
boto3andstrands-agentsdependencies - Added
python-dotenvandanthropicto dependencies - New
.env.exampletemplate for quick setup - Bumped version to
0.2.0
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 typebatter_zone_profile— Hot/cold zone map and pitch-type weaknesses from Statcast datapitcher_vs_batter— Career head-to-head matchup history via MLB Stats APIlive_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
pybaseballdependency for Statcast data access (with disk caching for speed) - Fixed bug in
lastest_seasontool (typo in name, wrong API call, duplicate Python function name) - Pybaseball integration degrades gracefully — all original tools work even if pybaseball is unavailable
- 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)
Below are example screenshots from the MLB Agent Chat UI showing real interactions and analysis powered by the MCP server and Bedrock planner.
The agent identifies the upcoming World Series Game 5 between the Blue Jays and Dodgers, including venue, status, and probable pitchers.
The agent retrieves Vladimir Guerrero Jr.’s 2025 season statistics and generates a natural language analysis comparing key performance metrics.
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.
- 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
- 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
| 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 |
| 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 |
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.
- Python 3.11 or higher
- An Anthropic API key (free tier available)
-
Clone the repository
git clone <repository-url> cd mlb_mcp_server-main
-
Install dependencies
pip install anthropic mcp[cli] mlb-statsapi pybaseball streamlit python-dotenv httpx
Or with uv:
uv sync
-
Run the MCP server (standalone, for testing)
python -m mcp run mlb_mcp_server.py
For a user-friendly chat interface:
-
Set up environment variables — copy
.env.exampleto.envand fill in your key:ANTHROPIC_API_KEY=sk-ant-... ANTHROPIC_MODEL=claude-sonnet-4-6 SERVER_CMD=python mlb_mcp_server.py
-
Run the Streamlit app:
streamlit run streamlit_app.py
Or with uv:
uv run streamlit run streamlit_app.py
-
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.
# 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- "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"
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:
- Call
pitcher_arsenal→ see Cole's pitch mix and whiff rates per pitch - Call
batter_zone_profile→ find Judge's weakest zones and pitch types - Call
pitcher_vs_batter→ check career history in this exact matchup - 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)
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)
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
# Install and run locally
uv sync
uv run streamlit run streamlit_app.pyCreate 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- Use the Docker approach above
- Configure AWS credentials for Bedrock access
- Deploy to ECS or run on EC2 instance
- Add
Procfile:web: uv run streamlit run streamlit_app.py --server.port=$PORT --server.address=0.0.0.0 - Deploy via Git or Heroku CLI
- Connect your GitHub repository
- Set environment variables in platform dashboard
- Use automatic deployment from main branch
- FastMCP-based server providing MLB data tools
- Connects to MLB Stats API via
mlb-statsapipackage - Supports both formatted text and raw JSON responses
- 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
anthropic- Anthropic Python SDK (powers the Streamlit UI)mcp[cli]- Model Context Protocol frameworkmlb-statsapi- MLB Stats API clientpybaseball- Statcast & advanced analytics data (Baseball Savant, FanGraphs, Baseball Reference)streamlit- Web interface frameworkpython-dotenv- Environment variable loadinghttpx- HTTP client for API requests
{
"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
}{
"personID": 545361, # Player ID
"group": "hitting", # hitting/pitching/fielding
"type": "season", # season/career
"season": "2024" # Season year
}{
"leagueID": "103,104", # AL=103, NL=104
"division": "all", # Division filter
"season": "2024", # Season year
"date": "MM/DD/YYYY" # Historical date
}{
"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_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_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.
{
"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).
-
MCP Server Won't Start
- Ensure Python 3.11+ is installed
- Run
uv syncto install dependencies - Check that
mlb_mcp_server.pyis executable
-
Streamlit Connection Errors
- Verify MCP server command in environment variables
- Check AWS credentials for Bedrock access
- Ensure all dependencies are installed
-
Tool Call Failures
- Validate required parameters (team IDs, dates)
- Check MLB Stats API availability
- Review error logs for specific issues
-
pitcher_arsenal/batter_zone_profileReturn 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_playerfirst to confirm the correct ID. - Try a smaller
days_backvalue (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.
-
pitcher_vs_batterReturns 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.
-
live_game_contextReturns "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_idto narrow to a specific team's game.
Enable debug logging by setting:
logging.basicConfig(level=logging.DEBUG)- Fork the repository
- Create a feature branch
- Make your changes
- Add tests if applicable
- Submit a pull request
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.
For issues and questions:
- Check the troubleshooting section above
- Review the MLB-StatsAPI documentation
- Review the MLB Stats API documentation
- Open an issue in the repository
- MLB-StatsAPI - The core Python library for MLB Stats API
- pybaseball - Statcast, Baseball Reference, and FanGraphs data for Python
- Model Context Protocol - MCP Python SDK
- FastMCP - Simplified MCP server framework
- Baseball Savant - Official MLB Statcast data source
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.