Skip to main content
Glama

get-segment-leaderboard

Retrieve top athlete performances for a Strava segment with filtering options. Compare times, power, and heart rate data by gender, age group, weight class, club, or date range to analyze segment rankings.

Instructions

Retrieves the leaderboard for a specific Strava segment. Shows top performances with times, power, and heart rate data. Supports filtering by gender, age group, weight class, club, date range, and followed athletes.

Use this to:

  • See top performances on a segment

  • Compare your efforts against others

  • Filter by demographics or time period

  • Check if you have a chance at a top position

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
segmentIdYesThe unique identifier of the segment to fetch the leaderboard for.
genderNoFilter by gender. M for male, F for female.
age_groupNoFilter by age group.
weight_classNoFilter by weight class in kg.
followingNoIf true, filter to only athletes the authenticated user follows.
club_idNoFilter to only athletes in the specified club.
date_rangeNoFilter by date range for efforts.
per_pageNoNumber of entries per page (max 200, default 10).
pageNoPage number for pagination.

Implementation Reference

  • The execute function for the 'get-segment-leaderboard' tool, which fetches data from the Strava client and formats it for output.
    execute: async ({ segmentId, gender, age_group, weight_class, following = false, club_id, date_range, per_page = 10, page = 1 }: GetSegmentLeaderboardParams) => {
        const token = process.env.STRAVA_ACCESS_TOKEN;
    
        if (!token) {
            console.error("Missing STRAVA_ACCESS_TOKEN environment variable.");
            return {
                content: [{ type: 'text' as const, text: 'Configuration error: Missing Strava access token.' }],
                isError: true
            };
        }
    
        try {
            console.error(`Fetching leaderboard for segment ID: ${segmentId}...`);
            const leaderboard = await fetchSegmentLeaderboard(token, segmentId, {
                gender, age_group, weight_class, following, club_id, date_range, per_page, page
            });
            const formatted = formatLeaderboard(leaderboard, segmentId);
    
            console.error(`Successfully fetched leaderboard for segment ${segmentId} (${leaderboard.entry_count} entries)`);
            return { content: [{ type: 'text' as const, text: formatted }] };
        } catch (error) {
            const errorMessage = error instanceof Error ? error.message : String(error);
            console.error(`Error fetching segment leaderboard ${segmentId}: ${errorMessage}`);
    
            let userFriendlyMessage;
            if (errorMessage.startsWith("SUBSCRIPTION_REQUIRED:")) {
                userFriendlyMessage = `🔒 Accessing this segment leaderboard (ID: ${segmentId}) requires a Strava subscription. Please check your subscription status.`;
            } else if (errorMessage.includes("Record Not Found") || errorMessage.includes("404")) {
                userFriendlyMessage = `Segment with ID ${segmentId} not found.`;
            } else {
                userFriendlyMessage = `An unexpected error occurred while fetching leaderboard for segment ${segmentId}. Details: ${errorMessage}`;
            }
    
            return {
                content: [{ type: 'text' as const, text: `❌ ${userFriendlyMessage}` }],
                isError: true
            };
        }
    }
  • The Zod schema for input validation for the 'get-segment-leaderboard' tool.
    export const inputSchema = z.object({
        segmentId: z.number().int().positive().describe(
            'The unique identifier of the segment to fetch the leaderboard for.'
        ),
        gender: z.enum(['M', 'F']).optional().describe(
            'Filter by gender. M for male, F for female.'
        ),
        age_group: z.enum(['0_19', '20_24', '25_34', '35_44', '45_54', '55_64', '65_69', '70_74', '75_plus']).optional().describe(
            'Filter by age group.'
        ),
        weight_class: z.enum(['0_54', '55_64', '65_74', '75_84', '85_94', '95_plus']).optional().describe(
            'Filter by weight class in kg.'
        ),
        following: z.boolean().optional().default(false).describe(
            'If true, filter to only athletes the authenticated user follows.'
        ),
        club_id: z.number().int().optional().describe(
            'Filter to only athletes in the specified club.'
        ),
        date_range: z.enum(['this_year', 'this_month', 'this_week', 'today']).optional().describe(
            'Filter by date range for efforts.'
        ),
        per_page: z.number().int().min(1).max(200).optional().default(10).describe(
            'Number of entries per page (max 200, default 10).'
        ),
        page: z.number().int().min(1).optional().default(1).describe(
            'Page number for pagination.'
        )
    });
  • The registration and tool definition object for 'get-segment-leaderboard'.
    export const getSegmentLeaderboardTool = {
        name: 'get-segment-leaderboard',
        description:
            'Retrieves the leaderboard for a specific Strava segment. Shows top performances with times, ' +
            'power, and heart rate data. Supports filtering by gender, age group, weight class, club, ' +
            'date range, and followed athletes.\n\n' +
            'Use this to:\n' +
            '- See top performances on a segment\n' +
            '- Compare your efforts against others\n' +
            '- Filter by demographics or time period\n' +
            '- Check if you have a chance at a top position',
        inputSchema,
        execute: async ({ segmentId, gender, age_group, weight_class, following = false, club_id, date_range, per_page = 10, page = 1 }: GetSegmentLeaderboardParams) => {
            const token = process.env.STRAVA_ACCESS_TOKEN;
    
            if (!token) {
                console.error("Missing STRAVA_ACCESS_TOKEN environment variable.");
                return {
                    content: [{ type: 'text' as const, text: 'Configuration error: Missing Strava access token.' }],
                    isError: true
                };
            }
    
            try {
                console.error(`Fetching leaderboard for segment ID: ${segmentId}...`);
                const leaderboard = await fetchSegmentLeaderboard(token, segmentId, {
                    gender, age_group, weight_class, following, club_id, date_range, per_page, page
                });
                const formatted = formatLeaderboard(leaderboard, segmentId);
    
                console.error(`Successfully fetched leaderboard for segment ${segmentId} (${leaderboard.entry_count} entries)`);
                return { content: [{ type: 'text' as const, text: formatted }] };
            } catch (error) {
                const errorMessage = error instanceof Error ? error.message : String(error);
                console.error(`Error fetching segment leaderboard ${segmentId}: ${errorMessage}`);
    
                let userFriendlyMessage;
                if (errorMessage.startsWith("SUBSCRIPTION_REQUIRED:")) {
                    userFriendlyMessage = `🔒 Accessing this segment leaderboard (ID: ${segmentId}) requires a Strava subscription. Please check your subscription status.`;
                } else if (errorMessage.includes("Record Not Found") || errorMessage.includes("404")) {
                    userFriendlyMessage = `Segment with ID ${segmentId} not found.`;
                } else {
                    userFriendlyMessage = `An unexpected error occurred while fetching leaderboard for segment ${segmentId}. Details: ${errorMessage}`;
                }
    
                return {
                    content: [{ type: 'text' as const, text: `❌ ${userFriendlyMessage}` }],
                    isError: true
                };
            }
        }
    };
  • Helper function to format the leaderboard response into a human-readable table.
    export function formatLeaderboard(data: StravaLeaderboardResponse, segmentId: number): string {
        let output = `🏆 **Segment Leaderboard** (ID: ${segmentId})\n`;
        output += `   Total efforts: ${data.effort_count} | Entries shown: ${data.entries.length}\n\n`;
    
        if (data.entries.length === 0) {
            output += '   No entries found for the given filters.\n';
            return output;
        }
    
        output += '| Rank | Athlete | Time | Avg Power | Avg HR |\n';
        output += '|------|---------|------|-----------|--------|\n';
    
        for (const entry of data.entries) {
            const power = entry.average_watts ? `${Math.round(entry.average_watts)}W` : '-';
            const hr = entry.average_hr ? `${Math.round(entry.average_hr)}bpm` : '-';
            output += `| ${entry.rank} | ${entry.athlete_name} | ${formatTime(entry.elapsed_time)} | ${power} | ${hr} |\n`;
        }
    
        return output;
    }

Schema Changelog

Changes observed during successful MCP inspections.

  1. First observedv1.2.1

TDQS

A4/5.0
Behavior3/5

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

With no annotations, the description carries the transparency burden. It mentions the data returned (times/power/HR) and filters, but does not disclose pagination behavior, authentication needs, or error handling. It's adequate but not rich.

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 concise, with a short intro and a bulleted list of usage examples. No wasted sentences; each bullet adds value.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

The description covers the tool's primary function and data returned, which is helpful since there is no output schema. However, it omits details about pagination limits or auth requirements, so it's not fully complete for a tool with 9 parameters.

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 description coverage is 100%, so the schema already documents all parameters. The description summarizes filter categories but adds no new meaning beyond the schema's per-parameter descriptions.

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

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool retrieves a leaderboard for a specific Strava segment, using a specific verb and resource. It distinguishes itself from sibling tools like get-segment and list-segment-efforts by focusing on the leaderboard aspect.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The 'Use this to' bullets provide clear, actionable use cases for the tool. It doesn't explicitly mention alternatives or when not to use it, but the context is clear enough for an agent to decide.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.