get_session_results
Retrieve detailed results for any Formula One session by specifying year, event, and session type to access race data, qualifying times, or practice session outcomes.
Instructions
Get results for a specific Formula One session
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| year | Yes | Season year (e.g., 2023) | |
| event_identifier | Yes | Event name or round number (e.g., 'Monaco' or '7') | |
| session_name | Yes | Session name (e.g., 'Race', 'Qualifying', 'Sprint', 'FP1', 'FP2', 'FP3') |
Implementation Reference
- src/f1_mcp_server/f1_data.py:168-231 (handler)Core handler function that implements the 'get_session_results' tool. Validates year and session name, loads the FastF1 session (without telemetry), extracts results DataFrame, converts to JSON-serializable list of driver results, logs success/error, and returns structured response.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)}", }
- src/f1_mcp_server/server.py:320-346 (registration)Registers the 'get_session_results' tool in the MCP server's list_tools() function, providing the tool name, description, and detailed inputSchema for validation (year, event_identifier, session_name).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"], }, ),
- src/f1_mcp_server/server.py:170-200 (schema)Tool dispatch logic in the general f1_tool handler: performs additional input validation for event_identifier and session_name (including valid sessions list), sanitizes, and calls the get_session_results function.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, )
- src/f1_mcp_server/f1_data.py:66-88 (helper)Helper function used by get_session_results to validate the year parameter (1950 to current+1).def validate_year(year: Any) -> int: """ Validate that the provided year is valid for F1 data. Args: year: Year value to validate Returns: Valid year as integer Raises: ValueError: If year is invalid """ try: year_int = int(year) # F1 started in 1950 and we don't want future years far ahead current_year = datetime.now().year if year_int < 1950 or year_int > current_year + 1: raise ValueError(f"Year must be between 1950 and {current_year + 1}") return year_int except (ValueError, TypeError) as e: raise ValueError(f"Invalid year format: {year}") from e
- src/f1_mcp_server/f1_data.py:45-63 (helper)Helper utility for serializing FastF1 data (datetimes, numpy types, pandas NA) to JSON-compatible formats, used in results conversion.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)