Skip to main content
Glama
efikuta

YouTube Knowledge MCP

by efikuta

youtube_search

Search YouTube videos with filters for date, duration, quality, region, and sort order to find specific content efficiently.

Instructions

Search for videos on YouTube with advanced filtering options

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYesSearch query for YouTube videos
maxResultsNoMaximum number of results (1-50)
publishedAfterNoFilter videos published after this date (ISO 8601 format)
publishedBeforeNoFilter videos published before this date (ISO 8601 format)
orderNoSort order for resultsrelevance
videoDurationNoFilter by video durationany
videoDefinitionNoFilter by video qualityany
regionCodeNoRegion code for localized results (e.g., "US", "GB")

Implementation Reference

  • Core handler implementation in YouTubeSearchTool.execute(). Handles validation, caching, quota checks, YouTube API search, result caching and enrichment.
    async execute(args: unknown): Promise<YouTubeSearchResult> {
      // Validate input parameters
      const params = YouTubeSearchSchema.parse(args);
      
      this.logger.info(`Executing YouTube search for: "${params.query}"`);
    
      // Generate cache key
      const cacheKey = this.cache.getSearchKey(params.query, params);
    
      // Check cache first
      const cached = await this.cache.get<YouTubeSearchResult>(cacheKey);
      if (cached) {
        this.logger.info(`Returning cached search results for: "${params.query}"`);
        return cached;
      }
    
      // Check quota before making API call
      const operationCost = QuotaManager.getOperationCost('search');
      if (!this.quotaManager.canPerformOperation(operationCost)) {
        throw new QuotaExceededError('Insufficient quota for search operation');
      }
    
      // Optimize operation based on quota availability
      const optimizedMaxResults = this.quotaManager.optimizeOperation('search', params.maxResults);
      if (optimizedMaxResults === 0) {
        throw new QuotaExceededError('Cannot perform search operation due to quota constraints');
      }
    
      // Update params with optimized values
      const optimizedParams: YouTubeSearchParams = {
        ...params,
        maxResults: optimizedMaxResults
      };
    
      try {
        // Perform the search
        const result = await this.youtubeClient.searchVideos(optimizedParams);
        
        // Record quota usage
        await this.quotaManager.recordUsage(operationCost, 'search');
        
        // Cache the result
        await this.cache.set(cacheKey, result);
        
        this.logger.info(
          `Search completed for "${params.query}": ${result.videos.length} videos found`
        );
    
        // Add additional metadata to response
        const enrichedResult: YouTubeSearchResult & { 
          metadata?: { 
            quotaUsed: number; 
            cached: boolean; 
            optimized?: boolean; 
          } 
        } = {
          ...result,
          metadata: {
            quotaUsed: operationCost,
            cached: false,
            optimized: optimizedMaxResults !== params.maxResults
          }
        };
    
        return enrichedResult;
    
      } catch (error) {
        this.logger.error(`Search failed for "${params.query}":`, error);
        
        // If quota exceeded, try to return cached results even if expired
        if (error instanceof QuotaExceededError) {
          const expiredCache = await this.getCachedResultIgnoreExpiry(cacheKey);
          if (expiredCache) {
            this.logger.warn('Returning expired cache due to quota limits');
            return {
              ...expiredCache,
              metadata: {
                quotaUsed: 0,
                cached: true,
                expired: true
              }
            } as any;
          }
        }
        
        throw error;
      }
    }
  • Zod schema for input validation of youtube_search tool parameters.
    export const YouTubeSearchSchema = z.object({
      query: z.string().describe('Search query for YouTube videos'),
      maxResults: z.number().min(1).max(50).default(10).describe('Maximum number of results to return'),
      publishedAfter: z.string().optional().describe('Filter videos published after this date (ISO 8601)'),
      publishedBefore: z.string().optional().describe('Filter videos published before this date (ISO 8601)'),
      order: z.enum(['relevance', 'date', 'rating', 'viewCount', 'title']).default('relevance').describe('Sort order for results'),
      videoDuration: z.enum(['any', 'short', 'medium', 'long']).default('any').describe('Filter by video duration'),
      videoDefinition: z.enum(['any', 'high', 'standard']).default('any').describe('Filter by video quality'),
      regionCode: z.string().optional().describe('Region code for localized results (e.g., "US", "GB")'),
    });
  • src/index.ts:209-258 (registration)
    Registration of 'youtube_search' tool in the ListToolsRequestSchema handler, including name, description, and input schema.
      name: 'youtube_search',
      description: 'Search for videos on YouTube with advanced filtering options',
      inputSchema: {
        type: 'object',
        properties: {
          query: {
            type: 'string',
            description: 'Search query for YouTube videos'
          },
          maxResults: {
            type: 'number',
            description: 'Maximum number of results (1-50)',
            minimum: 1,
            maximum: 50,
            default: 10
          },
          publishedAfter: {
            type: 'string',
            description: 'Filter videos published after this date (ISO 8601 format)'
          },
          publishedBefore: {
            type: 'string',
            description: 'Filter videos published before this date (ISO 8601 format)'
          },
          order: {
            type: 'string',
            enum: ['relevance', 'date', 'rating', 'viewCount', 'title'],
            default: 'relevance',
            description: 'Sort order for results'
          },
          videoDuration: {
            type: 'string',
            enum: ['any', 'short', 'medium', 'long'],
            default: 'any',
            description: 'Filter by video duration'
          },
          videoDefinition: {
            type: 'string',
            enum: ['any', 'high', 'standard'],
            default: 'any',
            description: 'Filter by video quality'
          },
          regionCode: {
            type: 'string',
            description: 'Region code for localized results (e.g., "US", "GB")'
          }
        },
        required: ['query']
      }
    },
  • src/index.ts:559-561 (registration)
    Dispatching logic in CallToolRequestSchema handler that routes 'youtube_search' calls to the searchTool handler.
    case 'youtube_search':
      result = await this.searchTool.execute(args);
      break;
  • src/index.ts:171-171 (registration)
    Instantiation of the YouTubeSearchTool instance used for handling youtube_search requests.
    this.searchTool = new YouTubeSearchTool(this.youtubeClient, this.cache, this.quotaManager, this.logger);
Behavior2/5

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

With no annotations provided, the description carries full burden for behavioral disclosure. While 'Search' implies a read operation, it doesn't address authentication requirements, rate limits, pagination behavior, error handling, or what the response format looks like. For a search tool with 8 parameters and no output schema, this leaves significant behavioral gaps.

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 that communicates the core purpose without waste. It's appropriately sized for a search tool and front-loads the essential information. Every word earns its place.

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

Completeness2/5

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

For a search tool with 8 parameters, no annotations, and no output schema, the description is incomplete. It doesn't address what the search returns (video metadata, URLs, thumbnails?), authentication needs, rate limits, or error conditions. The agent lacks sufficient context to use this tool effectively beyond basic parameter passing.

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?

Schema description coverage is 100%, so the schema already documents all 8 parameters thoroughly. The description adds minimal value beyond stating 'advanced filtering options' - it doesn't explain parameter relationships, provide usage examples, or add semantic context not already in the schema descriptions. Baseline 3 is appropriate when schema does the heavy lifting.

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 as 'Search for videos on YouTube with advanced filtering options' - a specific verb ('Search') and resource ('videos on YouTube') with scope ('advanced filtering options'). It doesn't explicitly differentiate from sibling tools like 'search_channels' or 'get_trending_videos', but the focus on video search is clear.

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 like 'search_channels' (for channel search) or 'get_trending_videos' (for trending content). There's no mention of prerequisites, use cases, or when-not-to-use scenarios. The agent must infer usage from tool names alone.

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/efikuta/youtube-knowledge-mcp'

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