Skip to main content
Glama
Machine-To-Machine

Formula One MCP Server (Python)

get_session_results

Retrieve Formula One session results by providing season year, event name or round number, and session type (Race, Qualifying, Sprint, Practice).

Instructions

Get results for a specific 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')

Implementation Reference

  • The core function that executes the tool logic for get_session_results. It validates the year and session name, uses the FastF1 API to fetch session results, loads the session (without telemetry for speed), converts results to JSON-serializable format, and returns status/data or error.
    def get_session_results(
        year: Any, event_identifier: str, session_name: str
    ) -> dict[str, Any]:
        """
        Get results for a specific 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.)
    
        Returns:
            dict: Status and session results data or error information
        """
        try:
            # Validate year
            year_int = validate_year(year)
    
            # Validate session name
            valid_sessions = [
                "Race",
                "Qualifying",
                "Sprint",
                "FP1",
                "FP2",
                "FP3",
                "SprintQualifying",
            ]
            if session_name not in valid_sessions:
                raise ValueError(
                    f"Invalid session name. Must be one of: {', '.join(valid_sessions)}"
                )
    
            logger.debug(
                f"Fetching session results for {year_int}, "
                f"event: {event_identifier}, session: {session_name}"
            )
    
            session = fastf1.get_session(year_int, event_identifier, session_name)
            # Load session without telemetry for faster results
            session.load(telemetry=False)
    
            # Get results as a DataFrame
            results = session.results
    
            # Convert results to JSON serializable format
            result_list = []
            for _, result in results.items():
                driver_result = result.to_dict()
                # Clean and convert non-serializable values
                clean_dict = {k: json_serial(v) for k, v in driver_result.items()}
                result_list.append(clean_dict)
    
            logger.info(
                f"Successfully retrieved results for {year_int}, "
                f"event: {event_identifier}, session: {session_name}"
            )
            return {"status": "success", "data": result_list}
        except Exception as e:
            logger.error(f"Error retrieving session results: {str(e)}", exc_info=True)
            return {
                "status": "error",
                "message": f"Failed to retrieve session results: {str(e)}",
            }
  • Input/output schema (inputSchema) defining the 'get_session_results' tool's parameters: year (number), event_identifier (string), and session_name (string). All three are required.
    types.Tool(
        name="get_session_results",
        description="Get results for a specific 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')"
                    ),
                },
            },
            "required": ["year", "event_identifier", "session_name"],
        },
    ),
  • The tool is registered inside the list_tools() handler which returns a list of types.Tool objects. The get_session_results entry is at lines 320-346 within that list.
    @app.list_tools()
    async def list_tools() -> list[types.Tool]:
        """
        List all available Formula One tools.
    
        Returns:
            A list of Tool objects describing available F1 data tools
        """
        return [
            types.Tool(
                name="get_event_schedule",
                description=("Get Formula One race calendar for a specific season"),
                inputSchema={
                    "type": "object",
                    "properties": {
                        "year": {
                            "type": "number",
                            "description": "Season year (e.g., 2023)",
                        },
                    },
                    "required": ["year"],
                },
            ),
            types.Tool(
                name="get_event_info",
                description=(
                    "Get detailed information about a specific Formula One Grand Prix"
                ),
                inputSchema={
                    "type": "object",
                    "properties": {
                        "year": {
                            "type": "number",
                            "description": "Season year (e.g., 2023)",
                        },
                        "identifier": {
                            "type": "string",
                            "description": (
                                "Event name or round number (e.g., 'Monaco' or '7')"
                            ),
                        },
                    },
                    "required": ["year", "identifier"],
                },
            ),
            types.Tool(
                name="get_session_results",
                description="Get results for a specific 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')"
                            ),
                        },
                    },
                    "required": ["year", "event_identifier", "session_name"],
                },
            ),
            types.Tool(
                name="get_driver_info",
                description=("Get information about a specific Formula One driver"),
                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",
                    ],
                },
            ),
            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",
                    ],
                },
            ),
            types.Tool(
                name="compare_drivers",
                description=(
                    "Compare performance between multiple Formula One drivers"
                ),
                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')"
                            ),
                        },
                        "drivers": {
                            "type": "string",
                            "description": (
                                "Comma-separated list of driver codes "
                                "(e.g., 'HAM,VER,LEC')"
                            ),
                        },
                    },
                    "required": [
                        "year",
                        "event_identifier",
                        "session_name",
                        "drivers",
                    ],
                },
            ),
            types.Tool(
                name="get_telemetry",
                description=("Get telemetry data for a specific Formula One lap"),
                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')"
                            ),
                        },
                        "lap_number": {
                            "type": "number",
                            "description": (
                                "Lap number (optional, gets fastest lap if not "
                                "provided)"
                            ),
                        },
                    },
                    "required": [
                        "year",
                        "event_identifier",
                        "session_name",
                        "driver_identifier",
                    ],
                },
            ),
            types.Tool(
                name="get_championship_standings",
                description="Get Formula One championship standings",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "year": {
                            "type": "number",
                            "description": "Season year (e.g., 2023)",
                        },
                        "round_num": {
                            "type": "number",
                            "description": (
                                "Round number (optional, gets latest "
                                "standings if not provided)"
                            ),
                        },
                    },
                    "required": ["year"],
                },
            ),
        ]
  • The server-side tool dispatch logic in the call_tool handler. It validates event_identifier and session_name arguments, checks session_name against valid values, then calls get_session_results() from f1_data.
    elif name == "get_session_results":
        # Additional validations for session-related tools
        if "event_identifier" not in arguments:
            raise ValueError("Missing required argument: event_identifier")
        if "session_name" not in arguments:
            raise ValueError("Missing required argument: session_name")
    
        event_identifier = str(arguments["event_identifier"])
        session_name = str(arguments["session_name"])
    
        # Validate session_name format
        valid_sessions = [
            "Race",
            "Qualifying",
            "Sprint",
            "FP1",
            "FP2",
            "FP3",
            "SprintQualifying",
        ]
        if session_name not in valid_sessions:
            raise ValueError(
                "Invalid session_name: must be one of "
                f"{', '.join(valid_sessions)}"
            )
    
        result = get_session_results(
            sanitized_args["year"],
            event_identifier,
            session_name,
        )
  • Helper function json_serial() used to convert non-JSON-serializable objects (timestamps, numpy types, NaNs) to JSON-compatible types within the handler.
    def json_serial(obj: Any) -> str | int | float | None:
        """
        Convert non-JSON serializable objects to strings.
    
        Args:
            obj: Object to be serialized to JSON
    
        Returns:
            JSON serializable representation of the object
        """
        if isinstance(obj, datetime | pd.Timestamp):
            return obj.isoformat()
        if isinstance(obj, np.integer):
            return int(obj)
        if isinstance(obj, np.floating):
            return float(obj)
        if pd.isna(obj) or obj is None:
            return None
        return str(obj)
Behavior2/5

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

With no annotations, the description alone must convey behavioral traits, but it only states the basic function. It does not disclose read-only nature, authentication needs, or any side effects. The agent learns nothing beyond what the name implies.

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 a single concise sentence that front-loads the purpose. However, it is slightly too brief and could benefit from a bit more context without being verbose.

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?

For a tool with three required parameters and no output schema, the description is minimally adequate but lacks details on the returned data format or any edge cases. It does not explain what 'results' entail, leaving ambiguity.

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?

Schema coverage is 100%, so the baseline is 3. The description adds no additional meaning beyond the parameter names and descriptions already in the schema. It does not provide defaults, examples, or constraints beyond what is listed.

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 action ('Get results') and the specific resource ('a specific Formula One session'). It is distinct from sibling tools like get_driver_info or get_championship_standings, which cover different aspects. However, it could be more explicit about what 'results' includes (e.g., finishing positions, times).

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 is provided on when to use this tool versus alternatives, such as analyze_driver_performance or get_event_info. There is no mention of prerequisites, limitations, or comparison with siblings.

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