Skip to main content
Glama
notsedano

Formula One MCP Server

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

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. It states the action ('analyze') but doesn't explain what 'analyze' entails—whether it returns statistics, insights, or raw data; if it's read-only or has side effects; or any performance or permission considerations. This is a significant gap for a tool with no annotation coverage.

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

Conciseness5/5

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

The description is a single, efficient sentence that directly states the tool's purpose without unnecessary words. It's front-loaded with the core action and context, making it easy to parse quickly, and every part of the sentence contributes essential information.

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?

Given the complexity of analyzing performance in a dynamic sport like Formula One, no annotations, and no output schema, the description is incomplete. It doesn't clarify what 'analyze' returns (e.g., metrics, comparisons, or raw data), leaving the agent uncertain about the tool's behavior and output, which is inadequate for effective use.

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?

The input schema has 100% description coverage, clearly documenting all 4 required parameters (year, event_identifier, session_name, driver_identifier). The description doesn't add any parameter-specific details beyond what the schema provides, such as formatting examples or constraints, so it meets the baseline for high schema coverage without extra value.

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

Purpose4/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 as analyzing a driver's performance in a Formula One session, specifying the resource (driver) and context (session). However, it doesn't differentiate from sibling tools like 'get_session_results' or 'compare_drivers' that might also involve performance analysis, making it clear but not fully distinctive.

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?

The description provides no guidance on when to use this tool versus alternatives. With siblings like 'get_session_results' and 'compare_drivers' that might overlap in analyzing performance, there's no indication of specific use cases, prerequisites, or exclusions, leaving the agent to guess based on tool names alone.

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

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