Skip to main content
Glama
jikime

YouTube Toolbox

search_videos

Find YouTube videos using specific queries with filters for channel, date, duration, quality, captions, and region to locate relevant content.

Instructions

Search for YouTube videos with advanced filtering options

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYes
max_resultsNo
channel_idNo
orderNo
video_durationNo
published_afterNo
published_beforeNo
video_captionNo
video_definitionNo
region_codeNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • MCP tool handler function for search_videos. Registers the tool with @mcp.tool decorator, defines input schema via parameters, handles arguments, calls helper method, formats response.
    @mcp.tool(
        name="search_videos",
        description="Search for YouTube videos with advanced filtering options",
    )
    async def search_videos(
        query: str, 
        max_results: Optional[int] = 10, 
        channel_id: Optional[str] = None,
        order: Optional[str] = None,
        video_duration: Optional[str] = None,
        published_after: Optional[str] = None,
        published_before: Optional[str] = None,
        video_caption: Optional[str] = None,
        video_definition: Optional[str] = None,
        region_code: Optional[str] = None
    ) -> Dict[str, Any]:
        """
        Search for YouTube videos with advanced filtering options
        
        Args:
            query (str): Search term
            max_results (int): Number of results to return (1-50)
            channel_id (str, optional): Filter by specific channel
            order (str, optional): Sort by date, rating, viewCount, relevance, title
            video_duration (str, optional): Filter by length (short: <4min, medium: 4-20min, long: >20min)
            published_after (str, optional): Filter by publish date after (ISO format)
            published_before (str, optional): Filter by publish date before (ISO format)
            video_caption (str, optional): Filter by caption availability
            video_definition (str, optional): Filter by quality (standard/high)
            region_code (str, optional): Filter by country (ISO country code)
        
        Returns:
            Dict[str, Any]: Search results
        """
        try:
            options = {
                'channelId': channel_id,
                'order': order,
                'videoDuration': video_duration,
                'publishedAfter': published_after,
                'publishedBefore': published_before,
                'videoCaption': video_caption,
                'videoDefinition': video_definition,
                'regionCode': region_code
            }
            
            search_results = youtube_service.search_videos(query, max_results, **options)
            
            # Format the response
            formatted_results = []
            for item in search_results.get('items', []):
                video_id = item.get('id', {}).get('videoId')
                
                formatted_results.append({
                    'videoId': video_id,
                    'title': item.get('snippet', {}).get('title'),
                    'channelId': item.get('snippet', {}).get('channelId'),
                    '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={video_id}"
                })
                
            return {
                'items': formatted_results,
                'totalResults': search_results.get('pageInfo', {}).get('totalResults', 0),
                'nextPageToken': search_results.get('nextPageToken')
            }
        except Exception as e:
            logger.exception(f"Error in search_videos: {e}")
            return {'error': str(e)}
  • Core helper method in YouTubeService class that constructs YouTube API search parameters and executes the search.list API call.
    def search_videos(self, query: str, max_results: int = 10, **options) -> Dict[str, Any]:
        """
        Search for YouTube videos based on query and options
        """
        try:
            search_params = {
                'part': 'snippet',
                'q': query,
                'maxResults': max_results,
                'type': options.get('type', 'video')
            }
            
            # Add optional parameters if provided
            for param in ['channelId', 'order', 'videoDuration', 'publishedAfter', 
                        'publishedBefore', 'videoCaption', 'videoDefinition', 'regionCode']:
                if param in options and options[param]:
                    search_params[param] = options[param]
            
            response = self.youtube.search().list(**search_params).execute()
            return response
        except HttpError as e:
            logger.error(f"Error searching videos: {e}")
            raise e
  • server.py:679-691 (registration)
    The tool is listed in the available-youtube-tools resource, which provides a list of all available tools including search_videos.
    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
  • Input schema defined by the function parameters with type hints and defaults, used by MCP for tool calling.
        query: str, 
        max_results: Optional[int] = 10, 
        channel_id: Optional[str] = None,
        order: Optional[str] = None,
        video_duration: Optional[str] = None,
        published_after: Optional[str] = None,
        published_before: Optional[str] = None,
        video_caption: Optional[str] = None,
        video_definition: Optional[str] = None,
        region_code: Optional[str] = None
    ) -> Dict[str, Any]:
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden of behavioral disclosure. It states the tool searches with filtering but doesn't mention key traits like whether it's read-only, has rate limits, requires authentication, returns paginated results, or what the output format entails. For a search tool with 10 parameters and 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: 'Search for YouTube videos with advanced filtering options.' It's front-loaded with the core purpose and avoids unnecessary words, making it highly concise and well-structured for quick understanding.

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 complexity (10 parameters, no annotations, but has an output schema), the description is incomplete. It covers the basic purpose but lacks usage guidelines, behavioral details, and parameter explanations. The presence of an output schema means return values are documented elsewhere, but for a tool with many parameters and no annotations, more context is needed to guide effective use.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters2/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, meaning parameter titles (e.g., 'Query', 'Max Results') lack detailed descriptions in the schema. The description adds minimal value by hinting at 'advanced filtering options' but doesn't explain what parameters like 'order', 'video_duration', or 'region_code' mean or how to use them. It fails to compensate for the low schema coverage, leaving most parameters semantically unclear.

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: 'Search for YouTube videos with advanced filtering options.' It specifies the verb ('search'), resource ('YouTube videos'), and scope ('advanced filtering options'), which is specific and actionable. However, it doesn't explicitly differentiate from sibling tools like 'get_related_videos' or 'get_trending_videos,' which might also involve video retrieval, so it's not a perfect 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. It mentions 'advanced filtering options' but doesn't specify scenarios where this is preferred over siblings like 'get_trending_videos' (for trending content) or 'get_related_videos' (for context-based retrieval). Without such context, the agent lacks clear usage rules.

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