Skip to main content
Glama
keithah

Tessie MCP Extension

get_weekly_mileage

Calculate total miles driven by a Tesla vehicle during a specific time period using VIN and date range inputs.

Instructions

Calculate total miles driven in a specific week or time period

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
end_dateYesEnd date of the period (ISO format)
start_dateYesStart date of the period (ISO format)
vinYesVehicle identification number (VIN)

Implementation Reference

  • src/index.ts:250-339 (registration)
    Registration of the 'get_weekly_mileage' MCP tool, including description, input schema, and complete handler implementation.
    // Register get_weekly_mileage tool
    server.tool(
      "get_weekly_mileage",
      "Calculate total miles driven in a specific week or time period",
      {
        vin: z.string().describe("Vehicle identification number (VIN)"),
        start_date: z.string().describe("Start date of the period (ISO format)"),
        end_date: z.string().describe("End date of the period (ISO format)")
      },
      async ({ vin, start_date, end_date }) => {
        try {
          const drives = await tessieClient.getDrives(vin, start_date, end_date, 500);
    
          const totalMiles = drives.reduce((sum, drive) => sum + drive.odometer_distance, 0);
    
          // Use DriveAnalyzer to predict autopilot usage for each drive
          let totalAutopilotMiles = 0;
          const dailyStats: { [key: string]: { miles: number; drives: number; autopilot_miles: number } } = {};
    
          drives.forEach(drive => {
            const date = new Date(drive.started_at * 1000).toISOString().split('T')[0];
            if (!dailyStats[date]) {
              dailyStats[date] = { miles: 0, drives: 0, autopilot_miles: 0 };
            }
    
            // Create a temporary merged drive to predict autopilot usage
            const tempMergedDrive = {
              id: `temp_${drive.id}`,
              originalDriveIds: [drive.id],
              started_at: drive.started_at,
              ended_at: drive.ended_at,
              starting_location: drive.starting_location,
              ending_location: drive.ending_location,
              starting_battery: drive.starting_battery,
              ending_battery: drive.ending_battery,
              total_distance: drive.odometer_distance,
              total_duration_minutes: (drive.ended_at - drive.started_at) / 60,
              driving_duration_minutes: (drive.ended_at - drive.started_at) / 60,
              stops: [],
              autopilot_distance: 0, // Will be predicted below
              autopilot_percentage: 0,
              energy_consumed: drive.starting_battery - drive.ending_battery,
              average_speed: drive.average_speed || 0,
              max_speed: drive.max_speed || 0
            };
    
            // Predict autopilot usage for this drive
            const predictedAutopilotMiles = driveAnalyzer.predictAutopilotUsage(tempMergedDrive);
    
            dailyStats[date].miles += drive.odometer_distance;
            dailyStats[date].drives += 1;
            dailyStats[date].autopilot_miles += predictedAutopilotMiles;
    
            totalAutopilotMiles += predictedAutopilotMiles;
          });
    
          const breakdown = Object.entries(dailyStats).map(([date, stats]) => ({
            date,
            miles: Math.round(stats.miles * 100) / 100,
            drives: stats.drives,
            autopilot_miles: Math.round(stats.autopilot_miles * 100) / 100,
            fsd_percentage: stats.miles > 0 ? Math.round((stats.autopilot_miles / stats.miles) * 10000) / 100 : 0,
          }));
    
          const result = {
            vehicle_vin: vin,
            period: { start_date, end_date },
            summary: {
              total_miles: Math.round(totalMiles * 100) / 100,
              total_drives: drives.length,
              total_autopilot_miles: Math.round(totalAutopilotMiles * 100) / 100,
              fsd_percentage: totalMiles > 0 ? Math.round((totalAutopilotMiles / totalMiles) * 10000) / 100 : 0,
            },
            daily_breakdown: breakdown.sort((a, b) => a.date.localeCompare(b.date))
          };
    
          // Wrap in MCP format
          return {
            content: [
              {
                type: "text",
                text: JSON.stringify(result, null, 2)
              }
            ]
          };
        } catch (error) {
          throw new Error(`Failed to get weekly mileage: ${error}`);
        }
      }
    );
  • The core handler function that implements the tool logic: fetches driving data from Tessie API, computes total and daily mileage, predicts autopilot usage via DriveAnalyzer helper, and formats MCP-compliant response.
    async ({ vin, start_date, end_date }) => {
      try {
        const drives = await tessieClient.getDrives(vin, start_date, end_date, 500);
    
        const totalMiles = drives.reduce((sum, drive) => sum + drive.odometer_distance, 0);
    
        // Use DriveAnalyzer to predict autopilot usage for each drive
        let totalAutopilotMiles = 0;
        const dailyStats: { [key: string]: { miles: number; drives: number; autopilot_miles: number } } = {};
    
        drives.forEach(drive => {
          const date = new Date(drive.started_at * 1000).toISOString().split('T')[0];
          if (!dailyStats[date]) {
            dailyStats[date] = { miles: 0, drives: 0, autopilot_miles: 0 };
          }
    
          // Create a temporary merged drive to predict autopilot usage
          const tempMergedDrive = {
            id: `temp_${drive.id}`,
            originalDriveIds: [drive.id],
            started_at: drive.started_at,
            ended_at: drive.ended_at,
            starting_location: drive.starting_location,
            ending_location: drive.ending_location,
            starting_battery: drive.starting_battery,
            ending_battery: drive.ending_battery,
            total_distance: drive.odometer_distance,
            total_duration_minutes: (drive.ended_at - drive.started_at) / 60,
            driving_duration_minutes: (drive.ended_at - drive.started_at) / 60,
            stops: [],
            autopilot_distance: 0, // Will be predicted below
            autopilot_percentage: 0,
            energy_consumed: drive.starting_battery - drive.ending_battery,
            average_speed: drive.average_speed || 0,
            max_speed: drive.max_speed || 0
          };
    
          // Predict autopilot usage for this drive
          const predictedAutopilotMiles = driveAnalyzer.predictAutopilotUsage(tempMergedDrive);
    
          dailyStats[date].miles += drive.odometer_distance;
          dailyStats[date].drives += 1;
          dailyStats[date].autopilot_miles += predictedAutopilotMiles;
    
          totalAutopilotMiles += predictedAutopilotMiles;
        });
    
        const breakdown = Object.entries(dailyStats).map(([date, stats]) => ({
          date,
          miles: Math.round(stats.miles * 100) / 100,
          drives: stats.drives,
          autopilot_miles: Math.round(stats.autopilot_miles * 100) / 100,
          fsd_percentage: stats.miles > 0 ? Math.round((stats.autopilot_miles / stats.miles) * 10000) / 100 : 0,
        }));
    
        const result = {
          vehicle_vin: vin,
          period: { start_date, end_date },
          summary: {
            total_miles: Math.round(totalMiles * 100) / 100,
            total_drives: drives.length,
            total_autopilot_miles: Math.round(totalAutopilotMiles * 100) / 100,
            fsd_percentage: totalMiles > 0 ? Math.round((totalAutopilotMiles / totalMiles) * 10000) / 100 : 0,
          },
          daily_breakdown: breakdown.sort((a, b) => a.date.localeCompare(b.date))
        };
    
        // Wrap in MCP format
        return {
          content: [
            {
              type: "text",
              text: JSON.stringify(result, null, 2)
            }
          ]
        };
      } catch (error) {
        throw new Error(`Failed to get weekly mileage: ${error}`);
      }
    }
  • Input schema using Zod for parameter validation: requires VIN and date range.
    {
      vin: z.string().describe("Vehicle identification number (VIN)"),
      start_date: z.string().describe("Start date of the period (ISO format)"),
      end_date: z.string().describe("End date of the period (ISO format)")
    },
  • Helper method in DriveAnalyzer class that predicts FSD/autopilot mileage for individual drives, called for each drive in the weekly aggregation to estimate daily autopilot usage.
    predictAutopilotUsage(drive: MergedDrive): number {
      if (drive.total_distance < 2) {
        // Very short drives unlikely to use autopilot
        return 0;
      }
    
      let autopilotLikelihood = 0;
    
      // Factor 1: Highway speed indicator (adjusted for real-world highway averages)
      if (drive.average_speed > 35) {
        autopilotLikelihood += 0.5; // Strong highway indicator
      } else if (drive.average_speed > 25) {
        autopilotLikelihood += 0.3; // Moderate highway/arterial indicator
      } else if (drive.average_speed > 15) {
        autopilotLikelihood += 0.1; // Light highway segments
      }
    
      // Factor 2: Distance-based likelihood (more realistic for FSD usage patterns)
      if (drive.total_distance > 15) {
        autopilotLikelihood += 0.4; // Long drives - very likely FSD
      } else if (drive.total_distance > 8) {
        autopilotLikelihood += 0.3; // Medium drives - likely FSD
      } else if (drive.total_distance > 4) {
        autopilotLikelihood += 0.2; // Short highway segments
      }
    
      // Factor 3: Max speed indicator (shows highway capability)
      if (drive.max_speed > 65) {
        autopilotLikelihood += 0.2; // Highway speeds
      } else if (drive.max_speed > 45) {
        autopilotLikelihood += 0.1; // Arterial speeds
      }
    
      // Factor 4: Speed consistency (autopilot tends to maintain steady speeds)
      const speedConsistency = this.calculateSpeedConsistency(drive);
      autopilotLikelihood += speedConsistency * 0.15;
    
      // Factor 5: Duration factor (longer drives more likely to use autopilot)
      if (drive.driving_duration_minutes > 20) {
        autopilotLikelihood += 0.15; // Extended driving
      } else if (drive.driving_duration_minutes > 10) {
        autopilotLikelihood += 0.1; // Medium duration
      }
    
      // Cap likelihood and apply more realistic highway assumptions
      autopilotLikelihood = Math.min(autopilotLikelihood, 1.0);
    
      // Boost likelihood for clear highway patterns but keep realistic
      if (drive.average_speed > 40 && drive.total_distance > 20) {
        autopilotLikelihood = Math.max(autopilotLikelihood, 0.75); // Clear highway drive
      } else if (drive.average_speed > 30 && drive.total_distance > 10) {
        autopilotLikelihood = Math.max(autopilotLikelihood, 0.65); // Likely highway drive
      }
    
      // Apply realistic deductions for non-FSD portions
      if (drive.total_distance > 5) {
        // Deduct estimated parking/city driving at start and end (~1-2 miles total)
        const parkingDeduction = Math.min(2.0 / drive.total_distance, 0.15);
        autopilotLikelihood = Math.max(0, autopilotLikelihood - parkingDeduction);
      }
    
      // Cap maximum realistic FSD usage (even perfect highway drives have some manual portions)
      autopilotLikelihood = Math.min(autopilotLikelihood, 0.92); // Max 92% FSD usage
    
      // Calculate estimated autopilot miles
      const estimatedAutopilotMiles = drive.total_distance * autopilotLikelihood;
    
      return Math.round(estimatedAutopilotMiles * 100) / 100;
    }

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/keithah/tessie-mcp'

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