Skip to main content
Glama
efikuta

YouTube Knowledge MCP

by efikuta

get_trending_videos

Find trending YouTube videos by category and region to identify popular content and emerging topics.

Instructions

Discover trending videos in different categories and regions

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
categoryNoCategory ID or name (e.g., "Technology", "Education")
regionNoRegion code for trending videosUS
maxResultsNoMaximum number of trending videos to return

Implementation Reference

  • Main handler implementation in TrendingVideosTool.execute() - validates params, handles caching, quota management, calls YouTube API via client, enhances results.
    export class TrendingVideosTool {
      constructor(
        private youtubeClient: YouTubeClient,
        private cache: CacheManager,
        private quotaManager: QuotaManager,
        private logger: Logger
      ) {}
    
      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;
        }
      }
  • Zod schema definition for get_trending_videos input 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:297-319 (registration)
    Tool registration in listToolsRequestHandler - defines name, description, and inputSchema.
    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 dispatch in CallToolRequestHandler switch statement - calls TrendingVideosTool.execute().
    case 'get_trending_videos':
      result = await this.trendingTool.execute(args);
      break;
  • YouTubeClient.getTrendingVideos() - core API call to fetch trending videos using YouTube Data API v3.
    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;
      }
    }
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 what the tool does but doesn't mention critical aspects like whether this is a read-only operation, rate limits, authentication needs, or what the return format looks like. For a tool with no annotations, 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 purpose with zero 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 lack of annotations and output schema, the description is incomplete. It doesn't explain what the tool returns (e.g., video list format, metadata), behavioral traits, or usage context relative to siblings. For a tool with no structured output information, the description should provide more completeness.

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 input schema has 100% description coverage, providing clear documentation for all three parameters. The description adds no additional parameter semantics beyond what's in the schema, so it meets the baseline of 3 without compensating or enhancing the schema's information.

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 the verb 'discover' and resource 'trending videos', and specifies scope with 'different categories and regions'. However, it doesn't explicitly distinguish this from sibling tools like 'youtube_search' or 'get_video_details', which prevents a score of 5.

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 like 'youtube_search' or 'get_video_details'. It mentions categories and regions but doesn't specify use cases, prerequisites, or exclusions, leaving the agent with minimal context for tool selection.

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/efikuta/youtube-knowledge-mcp'

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