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
| Name | Required | Description | Default |
|---|---|---|---|
| query | Yes | Search query for YouTube videos | |
| maxResults | No | Maximum number of results (1-50) | |
| publishedAfter | No | Filter videos published after this date (ISO 8601 format) | |
| publishedBefore | No | Filter videos published before this date (ISO 8601 format) | |
| order | No | Sort order for results | relevance |
| videoDuration | No | Filter by video duration | any |
| videoDefinition | No | Filter by video quality | any |
| regionCode | No | Region code for localized results (e.g., "US", "GB") |
Implementation Reference
- src/tools/search.ts:20-107 (handler)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; } }
- src/types.ts:61-70 (schema)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);