Skip to main content
Glama
jikime

YouTube Toolbox

get_related_videos

Find related YouTube videos by entering a video ID to discover similar content and expand your viewing options.

Instructions

Get videos related to a specific YouTube video

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
video_idYes
max_resultsNo

Implementation Reference

  • The MCP tool handler and registration for 'get_related_videos'. This function receives the tool call, invokes the YouTubeService helper method, formats the response, and returns the list of related videos.
    @mcp.tool(
        name="get_related_videos",
        description="Get videos related to a specific YouTube video",
    )
    async def get_related_videos(video_id: str, max_results: Optional[int] = 10) -> Dict[str, Any]:
        """
        Get videos related to a specific YouTube video
        
        Args:
            video_id (str): YouTube video ID
            max_results (int): Maximum number of related videos to return (default: 10)
        
        Returns:
            Dict[str, Any]: Related videos data
        """
        try:
            related_data = youtube_service.get_related_videos(video_id, max_results)
            
            # Format the response
            formatted_videos = []
            for item in related_data.get('items', []):
                related_video_id = item.get('id', {}).get('videoId')
                
                formatted_videos.append({
                    'videoId': related_video_id,
                    'title': item.get('snippet', {}).get('title'),
                    'channelTitle': item.get('snippet', {}).get('channelTitle'),
                    'publishedAt': item.get('snippet', {}).get('publishedAt'),
                    'description': item.get('snippet', {}).get('description'),
                    'thumbnails': item.get('snippet', {}).get('thumbnails'),
                    'url': f"https://www.youtube.com/watch?v={related_video_id}"
                })
                
            return {
                'videos': formatted_videos,
                'totalResults': len(formatted_videos),
                'originalVideoId': video_id,
                'searchQuery': related_data.get('searchQuery', '')
            }
        except Exception as e:
            logger.exception(f"Error in get_related_videos: {e}")
            return {'error': str(e)}
  • The core helper method in the YouTubeService class that implements the get_related_videos functionality. It retrieves the original video details, extracts keywords from the title, performs a YouTube search for similar content in the same category, filters out the original video, and returns the search results.
    def get_related_videos(self, video_id: str, max_results: Optional[int] = 10) -> Dict[str, Any]:
        """
        Get related videos for a specific YouTube video
        """
        video_id = self.parse_url(video_id)
        
        try:
            # Use search to find videos for a similar query to effectively get related content
            # First, get video details to use title for search
            video_details = self.get_video_details(video_id)
            if not video_details.get('items'):
                raise ValueError(f"Video with ID {video_id} not found")
            
            video_title = video_details['items'][0]['snippet']['title']
            # Extract a few keywords from the title for search
            search_query = ' '.join(video_title.split()[:3]) if video_title else ''
            
            # Search for videos with similar content
            response = self.youtube.search().list(
                part='snippet',
                q=search_query,
                type='video',
                maxResults=max_results,
                videoCategoryId=video_details['items'][0]['snippet'].get('categoryId', ''),
                relevanceLanguage='en'  # Can be adjusted based on requirements
            ).execute()
            
            # Filter out the original video from results
            if 'items' in response:
                response['items'] = [item for item in response['items'] 
                                    if item.get('id', {}).get('videoId') != video_id]
                # Adjust result count if original video was filtered
                if len(response['items']) < max_results:
                    response['pageInfo']['totalResults'] = len(response['items'])
                    response['pageInfo']['resultsPerPage'] = len(response['items'])
            
            # Add the search query to the response for reference
            response['searchQuery'] = search_query
            
            return response
        except HttpError as e:
            logger.error(f"Error getting related videos: {e}")
            raise e
  • server.py:672-692 (registration)
    The resource that lists all available tools, including 'get_related_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