get_trending_videos
Find trending YouTube videos by category and region to discover popular content relevant to specific interests and locations.
Instructions
Discover trending videos in different categories and regions
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| category | No | Category ID or name (e.g., "Technology", "Education") | |
| maxResults | No | Maximum number of trending videos to return | |
| region | No | Region code for trending videos | US |
Implementation Reference
- src/tools/trending.ts:20-84 (handler)Main tool handler: TrendingVideosTool.execute() - validates input with schema, manages cache and quota, calls YouTube client, enhances and returns trending videos results.async execute(args: unknown): Promise<TrendingVideosResult> { // Validate input parameters const params = GetTrendingVideosSchema.parse(args); this.logger.info(`Getting trending videos for region: ${params.region}, category: ${params.category || 'all'}`); // Generate cache key const cacheKey = this.cache.getTrendingKey(params.region, params.category); // Check cache first const cached = await this.cache.get<TrendingVideosResult>(cacheKey); if (cached) { this.logger.info(`Returning cached trending videos for region: ${params.region}`); return cached; } // Check quota before making API call const operationCost = QuotaManager.getOperationCost('trending'); if (!this.quotaManager.canPerformOperation(operationCost)) { throw new QuotaExceededError('Insufficient quota for trending videos operation'); } // Optimize operation based on quota availability const optimizedMaxResults = this.quotaManager.optimizeOperation('trending', params.maxResults); if (optimizedMaxResults === 0) { throw new QuotaExceededError('Cannot perform trending operation due to quota constraints'); } const optimizedParams: GetTrendingVideosParams = { ...params, maxResults: optimizedMaxResults }; try { // Get trending videos from YouTube API const result = await this.youtubeClient.getTrendingVideos(optimizedParams); // Record quota usage await this.quotaManager.recordUsage(operationCost, 'trending'); // Enhance the result with additional metadata const enhancedResult = await this.enhanceTrendingData(result); // Cache the result (trending data changes frequently, so shorter TTL) await this.cache.set(cacheKey, enhancedResult, 1800); // 30 minutes TTL this.logger.info(`Retrieved ${result.videos.length} trending videos for region: ${params.region}`); return enhancedResult; } catch (error) { this.logger.error(`Failed to get trending videos for region ${params.region}:`, error); // Try to return cached data if quota exceeded if (error instanceof QuotaExceededError) { const fallbackCache = await this.getFallbackTrendingData(params.region); if (fallbackCache) { this.logger.warn('Returning fallback trending data due to quota limits'); return fallbackCache; } } throw error; } }
- src/youtube-client.ts:151-177 (helper)Core YouTube API implementation: YouTubeClient.getTrendingVideos() - calls YouTube videos.list with chart='mostPopular' to fetch trending videos.async getTrendingVideos(params: GetTrendingVideosParams): Promise<TrendingVideosResult> { try { this.checkQuota(1); // Videos.list costs 1 quota unit const response = await this.youtube.videos.list({ part: ['snippet', 'statistics', 'contentDetails'], chart: 'mostPopular', regionCode: params.region, maxResults: params.maxResults, videoCategoryId: params.category }); this.quotaUsed += 1; const videos = this.mapVideosResponse(response.data.items || []); return { videos, category: params.category, region: params.region }; } catch (error) { this.handleError(error); throw error; } }
- src/types.ts:80-84 (schema)Input schema definition: GetTrendingVideosSchema using Zod for validation of tool parameters.export const GetTrendingVideosSchema = z.object({ category: z.string().optional().describe('Category ID or name (e.g., "Technology", "Education")'), region: z.string().default('US').describe('Region code for trending videos'), maxResults: z.number().min(1).max(50).default(25).describe('Maximum number of trending videos to return'), });
- src/index.ts:296-320 (registration)Tool registration in listTools: defines name, description, and inputSchema for get_trending_videos.{ name: 'get_trending_videos', description: 'Discover trending videos in different categories and regions', inputSchema: { type: 'object', properties: { category: { type: 'string', description: 'Category ID or name (e.g., "Technology", "Education")' }, region: { type: 'string', default: 'US', description: 'Region code for trending videos' }, maxResults: { type: 'number', minimum: 1, maximum: 50, default: 25, description: 'Maximum number of trending videos to return' } } } },
- src/index.ts:567-569 (registration)Tool handler dispatch: switch case in CallToolRequestHandler that routes to trendingTool.execute()case 'get_trending_videos': result = await this.trendingTool.execute(args); break;