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

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

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)
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries full burden for behavioral disclosure. It states what the tool does but lacks critical behavioral details: whether it's read-only or mutative, rate limits, authentication needs, error handling, or what happens with invalid inputs. The description doesn't contradict annotations (none exist), but provides minimal behavioral context.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is appropriately sized and front-loaded with the core purpose in the first sentence. The Args and Returns sections are structured clearly. While efficient, the 'Returns' section could be slightly more informative given the output schema exists.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's moderate complexity (4 parameters, no annotations, but has output schema), the description is partially complete. It covers parameters well but lacks behavioral context and usage differentiation from siblings. The output schema reduces need to explain return values, but more guidance on when to use this specific tool would improve completeness.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

With 0% schema description coverage, the description compensates well by explaining all 4 parameters in the Args section. It clarifies that player_ids is 'comma-separated,' season is a 'year,' stat_name is 'optional' with examples, and group has two possible values. This adds significant meaning beyond the bare schema types.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose: 'Get sabermetric statistics (including WAR) for multiple players for a specific season.' It specifies the verb ('Get'), resource ('sabermetric statistics'), scope ('multiple players', 'specific season'), and distinguishes from siblings by focusing on sabermetrics rather than awards, boxscores, or other MLB data.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage context by mentioning 'multiple players' and 'specific season,' but doesn't explicitly state when to use this tool versus alternatives like 'get_multiple_mlb_player_stats' or 'get_statcast_batter.' No exclusions or prerequisites are provided, leaving usage guidance incomplete.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

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