Skip to main content
Glama
jikime

YouTube Toolbox

get_trending_videos

Retrieve trending YouTube videos by region to discover popular content and analyze current viewing trends.

Instructions

Get trending videos on YouTube by region

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
region_codeNo
max_resultsNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • MCP tool handler for get_trending_videos. This is the entry point decorated with @mcp.tool(). It receives parameters, calls the underlying YouTubeService.get_trending_videos helper, formats the response by extracting relevant fields from the API response, and returns structured data including video details, stats, and URLs.
    @mcp.tool(
        name="get_trending_videos",
        description="Get trending videos on YouTube by region",
    )
    async def get_trending_videos(region_code: str = None, max_results: int = 5) -> Dict[str, Any]:
        """
        Get trending videos on YouTube by region
        
        Args:
            region_code (str): ISO country code (default: 'US')
            max_results (int): Maximum number of videos to return (default: 10)
        
        Returns:
            Dict[str, Any]: Trending videos data
        """
        try:
            # 이제 region_code 처리는 YouTubeService 클래스 내부에서 처리합니다
            trending_data = youtube_service.get_trending_videos(region_code, max_results)
            
            # Format the response
            formatted_videos = []
            for video in trending_data.get('items', []):
                formatted_videos.append({
                    'id': video.get('id'),
                    'title': video.get('snippet', {}).get('title'),
                    'description': video.get('snippet', {}).get('description'),
                    'publishedAt': video.get('snippet', {}).get('publishedAt'),
                    'channelId': video.get('snippet', {}).get('channelId'),
                    'channelTitle': video.get('snippet', {}).get('channelTitle'),
                    'viewCount': video.get('statistics', {}).get('viewCount'),
                    'likeCount': video.get('statistics', {}).get('likeCount'),
                    'commentCount': video.get('statistics', {}).get('commentCount'),
                    'thumbnails': video.get('snippet', {}).get('thumbnails'),
                    'url': f"https://www.youtube.com/watch?v={video.get('id')}"
                })
                
            return {
                'videos': formatted_videos,
                'region': region_code,
                'totalResults': len(formatted_videos)
            }
        except Exception as e:
            logger.exception(f"Error in get_trending_videos: {e}")
            return {'error': str(e)}
  • Core helper method in YouTubeService class that performs the actual YouTube Data API v3 call to fetch trending videos using videos.list with chart='mostPopular'. Handles region_code normalization and returns raw API response.
    def get_trending_videos(self, region_code: Optional[str] = 'ko', max_results: Optional[int] = 5) -> Dict[str, Any]:
        """
        Get trending videos for a specific region
        """
        try:
            params = {
                'part': 'snippet,contentDetails,statistics',
                'chart': 'mostPopular',
                'maxResults': max_results
            }
            
            if region_code:
                # Normalize region code to ensure valid ISO country code format
                normalized_code = self.normalize_region_code(region_code)
                params['regionCode'] = normalized_code
                
            response = self.youtube.videos().list(**params).execute()
            return response
        except HttpError as e:
            logger.error(f"Error getting trending videos: {e}")
            raise e
  • Helper utility method used by get_trending_videos to normalize region codes (e.g., 'KO' to 'KR') before passing to YouTube API.
    def normalize_region_code(self, region_code: str) -> str:
        """
        Convert region codes to valid ISO 3166-1 alpha-2 country codes
        """
        if not region_code:
            return None
            
        # Common mappings for non-standard codes to standard ISO codes
        region_mapping = {
            'KO': 'KR',  # Korea
            'EN': 'US',  # English -> US as fallback
            'JP': 'JP',  # Japan
            'CN': 'CN',  # China
        }
        
        # Convert to uppercase
        region_code = region_code.upper()
        
        # Return mapped code or original if no mapping exists
        return region_mapping.get(region_code, region_code)
  • server.py:672-691 (registration)
    Resource that lists all available tools, including 'get_trending_videos', providing its name and description.
    @mcp.resource(
        uri='youtube://available-youtube-tools', 
        name="available-youtube-tools", 
        description="Returns a list of YouTube tools available on this MCP server."
    )
    async def get_available_youtube_tools() -> List[Dict[str, str]]:
        """Returns a list of YouTube tools available on this MCP server."""
        available_tools = [
            {"name": "search_videos", "description": "Search for YouTube videos with advanced filtering options"},
            {"name": "get_video_details", "description": "Get detailed information about a YouTube video"},
            {"name": "get_channel_details", "description": "Get detailed information about a YouTube channel"},
            {"name": "get_video_comments", "description": "Get comments for a YouTube video"},
            {"name": "get_video_transcript", "description": "Get transcript/captions for a YouTube video"},
            {"name": "get_related_videos", "description": "Get videos related to a specific YouTube video"},
            {"name": "get_trending_videos", "description": "Get trending videos on YouTube by region"},
            {"name": "get_video_enhanced_transcript", "description": "Advanced transcript extraction tool with filtering, search, and multi-video capabilities. Provides rich transcript data for detailed analysis and processing. Features: 1) Extract transcripts from multiple videos; 2) Filter by time ranges; 3) Search within transcripts; 4) Segment transcripts; 5) Format output in different ways; 6) Include video metadata."}
        ]
        
        logger.info(f"Resource 'get_available_youtube_tools' called. Returning {len(available_tools)} tools.")
        return available_tools
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 tool retrieves trending videos by region but lacks details on permissions, rate limits, data freshness, or response format. This is a significant gap for a tool that likely involves external API calls.

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 with zero waste. It's appropriately sized and front-loaded, clearly stating the tool's purpose without unnecessary elaboration.

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

Completeness3/5

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

Given the tool's moderate complexity (2 parameters, no annotations, but with an output schema), the description is minimally adequate. The output schema likely covers return values, reducing the burden, but the lack of behavioral details and incomplete parameter semantics leaves room for improvement.

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 description mentions 'by region,' which aligns with the 'region_code' parameter, adding some context beyond the schema. However, with 0% schema description coverage and 2 parameters, it doesn't fully explain 'max_results' or provide format details for 'region_code,' leaving gaps in parameter understanding.

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 action ('Get trending videos') and resource ('on YouTube by region'), providing a specific purpose. However, it doesn't differentiate this tool from sibling tools like 'search_videos' or 'get_related_videos', which could also retrieve videos in some context.

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 when-not scenarios, prerequisites, or compare it to siblings like 'search_videos' for general queries or 'get_ideo_details' for specific videos, leaving usage ambiguous.

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/jikime/py-mcp-youtube-toolbox'

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