Skip to main content
Glama
Machine-To-Machine

Formula One MCP Server (Python)

analyze_driver_performance

Analyze a Formula One driver's performance in a specific session by providing season year, event, session name, and driver identifier.

Instructions

Analyze a driver's performance in a Formula One session

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
yearYesSeason year (e.g., 2023)
event_identifierYesEvent name or round number (e.g., 'Monaco' or '7')
session_nameYesSession name (e.g., 'Race', 'Qualifying', 'Sprint', 'FP1', 'FP2', 'FP3')
driver_identifierYesDriver identifier (number, code, or name; e.g., '44', 'HAM', 'Hamilton')

Implementation Reference

  • The core implementation of analyze_driver_performance. It loads session data, retrieves laps for a specific driver, calculates statistics (fastest lap, average lap time), and returns formatted lap-by-lap data including compound, tyre life, stint info.
    def analyze_driver_performance(
        year: Any, event_identifier: str, session_name: str, driver_identifier: str
    ) -> dict[str, Any]:
        """
        Analyze a driver's performance in a Formula One session.
    
        Args:
            year (int or str): The year of the F1 season
            event_identifier (str): Event name or round number
            session_name (str): Session type (Race, Qualifying, Sprint, etc.)
            driver_identifier (str): Driver number, code, or name
    
        Returns:
            dict: Status and performance analysis or error information
        """
        try:
            # Validate year
            year_int = validate_year(year)
    
            logger.debug(
                f"Analyzing driver performance for {year_int}, "
                f"event: {event_identifier}, session: {session_name}, "
                f"driver: {driver_identifier}"
            )
            session = fastf1.get_session(year_int, event_identifier, session_name)
            session.load()
    
            # Get laps for the specified driver
            driver_laps = session.laps.pick_driver(driver_identifier)
    
            if len(driver_laps) == 0:
                return {
                    "status": "error",
                    "message": f"No laps found for driver {driver_identifier}",
                }
    
            # Basic statistics
            fastest_lap = driver_laps.pick_fastest()
    
            # Calculate average lap time (excluding outliers)
            valid_lap_times = []
            for _, lap in driver_laps.iterrows():
                if lap["LapTime"] is not None and not pd.isna(lap["LapTime"]):
                    valid_lap_times.append(lap["LapTime"].total_seconds())
    
            avg_lap_time = (
                sum(valid_lap_times) / len(valid_lap_times) if valid_lap_times else None
            )
    
            # Format lap time as minutes:seconds.milliseconds
            formatted_fastest = (
                str(fastest_lap["LapTime"])
                if fastest_lap is not None and not pd.isna(fastest_lap["LapTime"])
                else None
            )
    
            # Get all lap times - limit to avoid excessive data
            max_laps = min(len(driver_laps), 100)  # Safety limit
            lap_times = []
    
            for _, lap in driver_laps.iloc[:max_laps].iterrows():
                lap_dict = {
                    "LapNumber": int(lap["LapNumber"])
                    if not pd.isna(lap["LapNumber"])
                    else None,
                    "LapTime": str(lap["LapTime"]) if not pd.isna(lap["LapTime"]) else None,
                    "Compound": lap["Compound"] if not pd.isna(lap["Compound"]) else None,
                    "TyreLife": int(lap["TyreLife"])
                    if not pd.isna(lap["TyreLife"])
                    else None,
                    "Stint": int(lap["Stint"]) if not pd.isna(lap["Stint"]) else None,
                    "FreshTyre": bool(lap["FreshTyre"])
                    if not pd.isna(lap["FreshTyre"])
                    else None,
                    "LapStartTime": json_serial(lap["LapStartTime"])
                    if not pd.isna(lap["LapStartTime"])
                    else None,
                }
                lap_times.append(lap_dict)
    
            # Format results
            result = {
                "DriverCode": fastest_lap["Driver"]
                if fastest_lap is not None and not pd.isna(fastest_lap["Driver"])
                else None,
                "TotalLaps": len(driver_laps),
                "FastestLap": formatted_fastest,
                "AverageLapTime": avg_lap_time,
                "LapTimes": lap_times,
            }
    
            logger.info(f"Successfully analyzed performance for driver {driver_identifier}")
            return {"status": "success", "data": result}
        except Exception as e:
            return {"status": "error", "message": str(e)}
  • The tool registration schema for analyze_driver_performance. Defines the tool name, description, and input schema (year, event_identifier, session_name, driver_identifier) as an MCP Tool object.
    types.Tool(
        name="analyze_driver_performance",
        description=("Analyze a driver's performance in a Formula One session"),
        inputSchema={
            "type": "object",
            "properties": {
                "year": {
                    "type": "number",
                    "description": "Season year (e.g., 2023)",
                },
                "event_identifier": {
                    "type": "string",
                    "description": (
                        "Event name or round number (e.g., 'Monaco' or '7')"
                    ),
                },
                "session_name": {
                    "type": "string",
                    "description": (
                        "Session name (e.g., 'Race', 'Qualifying', "
                        "'Sprint', 'FP1', 'FP2', 'FP3')"
                    ),
                },
                "driver_identifier": {
                    "type": "string",
                    "description": (
                        "Driver identifier (number, code, or name; "
                        "e.g., '44', 'HAM', 'Hamilton')"
                    ),
                },
            },
            "required": [
                "year",
                "event_identifier",
                "session_name",
                "driver_identifier",
            ],
        },
  • The call_tool handler that routes the name 'analyze_driver_performance' to the imported function from f1_data.py, passing validated arguments.
    elif name == "analyze_driver_performance":
        result = analyze_driver_performance(
            sanitized_args["year"],
            str(arguments["event_identifier"]),
            str(arguments["session_name"]),
            str(arguments["driver_identifier"]),
        )
  • Import statement bringing analyze_driver_performance from f1_data module into server.py.
    from .f1_data import (
        analyze_driver_performance,
        compare_drivers,
        get_championship_standings,
        get_driver_info,
        get_event_info,
        get_event_schedule,
        get_session_results,
        get_telemetry,
    )
Behavior1/5

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

No annotations exist, and the description fails to disclose behavioral traits such as whether the tool is read-only, requires authentication, or has side effects. It is extremely vague.

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?

Single sentence, no waste. However, it sacrifices necessary detail for brevity, scoring slightly above average.

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

Completeness2/5

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

No output schema, no annotations, and no explanation of what the analysis produces. The description is incomplete for a 4-parameter tool.

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

Parameters3/5

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

Input schema has 100% description coverage, so the baseline is 3. The description does not add additional meaning beyond the schema.

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 verb 'analyze', the resource 'driver's performance', and the context 'Formula One session'. It effectively distinguishes from sibling tools like compare_drivers and get_driver_info.

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

Usage Guidelines2/5

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

No guidance on when to use this tool versus alternatives. It lacks explicit context cues or when-not-to-use advice.

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/Machine-To-Machine/f1-mcp-server'

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