Skip to main content
Glama
guillochon

mlb-api-mcp

get_mlb_sabermetrics

Retrieve sabermetric statistics like WAR, wOBA, and wRC+ for MLB players by season to analyze advanced baseball performance metrics for hitting or pitching groups.

Instructions

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.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
player_idsYes
seasonYes
stat_nameNo
groupNohitting

Implementation Reference

  • The main handler function for the 'get_mlb_sabermetrics' tool, decorated with @mcp.tool(). It parses the comma-separated player_ids, calls the helper function get_sabermetrics_for_players, and handles errors.
    @mcp.tool()
    def get_mlb_sabermetrics(
        player_ids: str, season: int, stat_name: Optional[str] = None, group: str = "hitting"
    ) -> dict:
        """
        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.
        """
        try:
            player_ids_list = [pid.strip() for pid in player_ids.split(",")]
            result = get_sabermetrics_for_players(mlb, player_ids_list, season, stat_name, group)
            return result
        except Exception as e:
            return {"error": str(e)}
  • Supporting helper function that performs the actual API call to fetch sabermetrics data from MLB stats API, filters for the specified players, extracts relevant stats including WAR, wOBA, etc., and formats the output.
    def get_sabermetrics_for_players(
        mlb, player_ids: list, season: int, stat_name: Optional[str] = None, group: str = "hitting"
    ) -> dict:
        """
        Get sabermetric statistics (like WAR) for multiple players for a specific season.
    
        Parameters
        ----------
        mlb : mlbstatsapi.Mlb
            The MLB stats API instance
        player_ids : list
            List of player IDs to get sabermetrics for
        season : int
            The season year to get stats for
        stat_name : str, optional
            Specific sabermetric stat to extract (e.g., 'war', 'woba', 'wRc'). If None, returns all sabermetrics.
        group : str, optional
            The stat group ('hitting' or 'pitching'). Default is 'hitting'.
    
        Returns
        -------
        dict
            Dictionary containing player sabermetrics data
        """
    
        # Build the API endpoint URL
        endpoint = f"stats?stats=sabermetrics&group={group}&sportId=1&season={season}"
    
        # Make the API call directly
        response = mlb._mlb_adapter_v1.get(endpoint=endpoint)
    
        if 400 <= response.status_code <= 499:
            return {"error": f"API error: {response.status_code}"}
    
        if not response.data or "stats" not in response.data:
            return {"error": "No stats data found"}
    
        # Extract the relevant data
        result = {"season": season, "group": group, "players": []}
    
        # Filter for our specific players
        player_ids_int = [int(pid) for pid in player_ids]
    
        for stat_group in response.data["stats"]:
            if "splits" in stat_group:
                for split in stat_group["splits"]:
                    if "player" in split and split["player"]["id"] in player_ids_int:
                        player_data = {
                            "player_id": split["player"]["id"],
                            "player_name": split["player"].get("fullName", "Unknown"),
                            "position": split.get("position", {}).get("abbreviation", "N/A"),
                            "team": split.get("team", {}).get("name", "N/A"),
                            "team_id": split.get("team", {}).get("id", None),
                        }
    
                        # Extract the sabermetric stats
                        if "stat" in split:
                            if stat_name:
                                # Return only the specific stat requested
                                if stat_name.lower() in split["stat"]:
                                    player_data[stat_name] = split["stat"][stat_name.lower()]
                                else:
                                    player_data[stat_name] = None
                                    player_data["available_stats"] = list(split["stat"].keys())
                            else:
                                # Return all sabermetric stats
                                player_data["sabermetrics"] = split["stat"]
    
                        result["players"].append(player_data)
    
        return result
  • main.py:19-23 (registration)
    In the main server file, after creating the FastMCP instance, setup_mlb_tools(mcp) is called, which defines and registers the get_mlb_sabermetrics tool (along with others) using @mcp.tool() decorators.
    mcp = FastMCP("MLB API MCP Server")
    
    # Setup all MLB and generic tools
    setup_mlb_tools(mcp)
    setup_generic_tools(mcp)

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/guillochon/mlb-api-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server