getChannelTopVideos
Retrieve the most viewed videos from any YouTube channel to analyze popular content and identify successful video strategies.
Instructions
Retrieves the top videos from a specific channel. Returns a list of the most viewed or popular videos from the channel, based on view count. Use this when you want to identify the most successful content from a channel.
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| channelId | Yes | YouTube channel ID to get top videos from | |
| descriptionDetail | No | Controls video description detail to manage token cost. Options: 'NONE' (default, no text), 'SNIPPET' (a brief preview for broad scans), 'LONG' (a 500-char text for deep analysis of specific targets). | NONE |
| includeTags | No | Specify 'true' to include the video's 'tags' array in the response, which is useful for extracting niche keywords. The 'tags' are omitted by default to conserve tokens. | |
| maxResults | No | Maximum number of top videos to return (1-500, default: 10) |
Implementation Reference
- The primary handler function for the 'getChannelTopVideos' tool. Validates input parameters using Zod schema and delegates the core logic to the YouTubeService.getChannelTopVideos method, handling success and error formatting.export const getChannelTopVideosHandler = async ( params: ChannelParams, youtubeService: YoutubeService ): Promise<CallToolResult> => { try { const validatedParams = getChannelTopVideosSchema.parse(params); const topVideos = await youtubeService.getChannelTopVideos(validatedParams); return formatSuccess(topVideos); } catch (error: unknown) { return formatError(error); } };
- Zod schema defining the input parameters for the 'getChannelTopVideos' tool, including channelId, maxResults, includeTags, and descriptionDetail.export const getChannelTopVideosSchema = z.object({ channelId: channelIdSchema.describe( "YouTube channel ID to get top videos from" ), maxResults: maxResultsSchema .optional() .default(10) .describe("Maximum number of top videos to return (1-500, default: 10)"), includeTags: z .boolean() .optional() .default(false) .describe( "Specify 'true' to include the video's 'tags' array in the response, which is useful for extracting niche keywords. The 'tags' are omitted by default to conserve tokens." ), descriptionDetail: z .enum(["NONE", "SNIPPET", "LONG"]) .optional() .default("NONE") .describe( "Controls video description detail to manage token cost. Options: 'NONE' (default, no text), 'SNIPPET' (a brief preview for broad scans), 'LONG' (a 500-char text for deep analysis of specific targets)." ), });
- Core helper function in YouTubeService that implements the logic to fetch top videos from a channel by performing paginated search.list calls ordered by viewCount, batch fetching video details, processing statistics, and optionally including tags and formatted descriptions. Handles caching.async getChannelTopVideos( options: ChannelOptions ): Promise<LeanChannelTopVideo[]> { const cacheKey = this.cacheService.createOperationKey( "getChannelTopVideos", options ); const operation = async (): Promise<LeanChannelTopVideo[]> => { try { const { channelId, maxResults = 10, includeTags = false, descriptionDetail = "NONE", } = options; const searchResults: youtube_v3.Schema$SearchResult[] = []; let nextPageToken: string | undefined = undefined; const targetResults = Math.min(maxResults, this.ABSOLUTE_MAX_RESULTS); while (searchResults.length < targetResults) { const response = await this.trackCost( () => this.youtube.search.list({ part: ["id"], channelId: channelId, maxResults: Math.min( this.MAX_RESULTS_PER_PAGE, targetResults - searchResults.length ), order: "viewCount", type: ["video"], pageToken: nextPageToken, }), API_COSTS["search.list"] ); const searchResponse: youtube_v3.Schema$SearchListResponse = response.data; if (!searchResponse.items?.length) { break; } searchResults.push(...searchResponse.items); nextPageToken = searchResponse.nextPageToken || undefined; if (!nextPageToken) { break; } } if (!searchResults.length) { throw new Error("No videos found."); } const videoIds = searchResults .map((item) => item.id?.videoId) .filter((id): id is string => id !== undefined); const videoDetails: youtube_v3.Schema$Video[] = []; for (let i = 0; i < videoIds.length; i += this.MAX_RESULTS_PER_PAGE) { const batch = videoIds.slice(i, i + this.MAX_RESULTS_PER_PAGE); const response = await this.trackCost( () => this.youtube.videos.list({ part: ["snippet", "statistics", "contentDetails"], id: batch, }), API_COSTS["videos.list"] ); if (response.data.items) { videoDetails.push(...response.data.items); } } return videoDetails.slice(0, targetResults).map((video) => { const viewCount = parseYouTubeNumber(video.statistics?.viewCount); const likeCount = parseYouTubeNumber(video.statistics?.likeCount); const commentCount = parseYouTubeNumber( video.statistics?.commentCount ); const formattedDescription = formatDescription( video.snippet?.description, descriptionDetail ); const baseVideo = { id: video.id, title: video.snippet?.title, publishedAt: video.snippet?.publishedAt, duration: video.contentDetails?.duration, viewCount: viewCount, likeCount: likeCount, commentCount: commentCount, likeToViewRatio: calculateLikeToViewRatio(viewCount, likeCount), commentToViewRatio: calculateCommentToViewRatio( viewCount, commentCount ), categoryId: video.snippet?.categoryId ?? null, defaultLanguage: video.snippet?.defaultLanguage ?? null, }; const videoWithDescription = formattedDescription !== undefined ? { ...baseVideo, description: formattedDescription } : baseVideo; return includeTags ? { ...videoWithDescription, tags: video.snippet?.tags ?? [] } : videoWithDescription; }); } catch (error) { throw new YouTubeApiError( `YouTube API call for getChannelTopVideos failed for channelId: ${options.channelId}`, error ); } }; return this.cacheService.getOrSet( cacheKey, operation, CACHE_TTLS.SEMI_STATIC, CACHE_COLLECTIONS.CHANNEL_TOP_VIDEOS, options ); }
- src/tools/index.ts:114-121 (registration)Registration of the 'getChannelTopVideos' tool in the allTools function, including the config and wrapped handler with service injection.{ config: getChannelTopVideosConfig, handler: (params) => getChannelTopVideosHandler( params as unknown as ChannelParams, youtubeService ), },
- Tool configuration object including name, description, and reference to the input schema.export const getChannelTopVideosConfig = { name: "getChannelTopVideos", description: "Retrieves the top videos from a specific channel. Returns a list of the most viewed or popular videos from the channel, based on view count. Use this when you want to identify the most successful content from a channel.", inputSchema: getChannelTopVideosSchema, };