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;
    }
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It states the calculation action but doesn't reveal whether this is a read-only operation, requires authentication, has rate limits, or what the output format might be. For a tool with three required parameters and no annotation coverage, this is a significant gap in transparency.

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 function without any wasted words. It's appropriately sized and front-loaded, making it easy for an agent to parse quickly.

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 a calculation tool with three required parameters, no annotations, and no output schema, the description is incomplete. It doesn't explain what the calculation returns (e.g., numeric value, structured data), error conditions, or behavioral traits, leaving significant gaps for the agent to navigate.

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 schema description coverage is 100%, with clear documentation for all three parameters (vin, start_date, end_date). The description adds minimal value beyond the schema, as it only implies date-range filtering without providing additional syntax or format details. This meets the baseline for high schema coverage.

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 with a specific verb ('calculate') and resource ('total miles driven'), and specifies the scope ('in a specific week or time period'). However, it doesn't explicitly differentiate from sibling tools like 'get_driving_history' or 'get_mileage_at_location', which might also involve mileage calculations.

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. It doesn't mention sibling tools like 'get_driving_history' or 'get_vehicles', nor does it specify prerequisites or exclusions, leaving the agent to infer usage context from the tool name 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/keithah/tessie-mcp'

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