youtube_search
Search YouTube videos with filters for date range, duration, quality, region, and sorting to find specific content efficiently.
Instructions
Search for videos on YouTube with advanced filtering options
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| maxResults | No | Maximum number of results (1-50) | |
| order | No | Sort order for results | relevance |
| publishedAfter | No | Filter videos published after this date (ISO 8601 format) | |
| publishedBefore | No | Filter videos published before this date (ISO 8601 format) | |
| query | Yes | Search query for YouTube videos | |
| regionCode | No | Region code for localized results (e.g., "US", "GB") | |
| videoDefinition | No | Filter by video quality | any |
| videoDuration | No | Filter by video duration | any |
Implementation Reference
- src/tools/search.ts:20-107 (handler)The execute method in YouTubeSearchTool class implements the core logic for the youtube_search tool: input validation, caching, quota management, YouTube API search, result caching, and metadata 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 defining the input parameters and validation for the youtube_search tool.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:559-561 (registration)Registration in the tool dispatch switch statement: maps 'youtube_search' calls to the searchTool.execute method.case 'youtube_search': result = await this.searchTool.execute(args); break;
- src/index.ts:208-258 (registration)Tool registration in the ListTools response: defines name 'youtube_search', 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:171-171 (helper)Instantiation of the YouTubeSearchTool instance used for handling youtube_search calls.this.searchTool = new YouTubeSearchTool(this.youtubeClient, this.cache, this.quotaManager, this.logger);