Skip to main content
Glama
notsedano

Formula One MCP Server

by notsedano

analyze_driver_performance

Analyze a driver's performance in a specific Formula One session by providing year, event, session, and driver details to evaluate racing metrics.

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

  • Core handler function that loads F1 session data via fastf1 library, retrieves driver laps, calculates fastest lap, average lap time, and compiles detailed lap information for analysis.
    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)}
  • MCP tool registration in list_tools(), defining the tool name, description, and JSON schema for input parameters including year, event, session, and driver.
    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",
            ],
        },
    ),
  • Input schema definition for the analyze_driver_performance tool, specifying required parameters and their types/descriptions.
        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",
            ],
        },
    ),
  • Dispatch handler in the MCP server's call_tool function that invokes the analyze_driver_performance implementation after input sanitization.
    elif name == "analyze_driver_performance":
        result = analyze_driver_performance(
            sanitized_args["year"],
            str(arguments["event_identifier"]),
            str(arguments["session_name"]),
            str(arguments["driver_identifier"]),
        )
  • Tool mapping registration in the HTTP bridge for direct function invocation.
    'analyze_driver_performance': analyze_driver_performance,

Schema Changelog

Changes observed during successful MCP inspections.

  1. First observed

TDQS

C2.9/5.0
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.