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

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

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
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 but offers minimal information. It implies a read-only operation ('Get') but doesn't specify rate limits, authentication needs, error conditions, or what 'related' means algorithmically (e.g., based on YouTube's recommendations). This is inadequate for a tool that likely interacts with an external API.

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, clear sentence with no wasted words, making it highly concise and front-loaded. It directly states the tool's function without unnecessary elaboration, which is efficient for an agent to parse quickly.

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 has an output schema (which reduces the need to describe return values) but no annotations and low schema coverage, the description is minimally complete. It covers the basic purpose but lacks details on behavior, parameters, and usage context, making it adequate only for simple cases where the agent can rely on the structured fields.

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 'a specific YouTube video' which hints at the video_id parameter, but with 0% schema description coverage, it doesn't explain parameter meanings beyond this. It doesn't address max_results or provide context like valid ranges or defaults. Since schema coverage is low, the description should compensate more but only adds marginal value, warranting a baseline score.

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') and resource ('videos related to a specific YouTube video'), making the purpose immediately understandable. It distinguishes this from siblings like get_video_details or search_videos by focusing on related content rather than direct video information or broad searches. However, it doesn't explicitly contrast with get_trending_videos, which might also return videos, leaving slight ambiguity.

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 prerequisites (e.g., needing a valid video ID), exclusions, or comparisons to siblings like search_videos for broader queries or get_video_details for metadata. This leaves the agent to infer usage context solely from the tool name and description.

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