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

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

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