Skip to main content
Glama

tiktok_search

Search TikTok videos by keyword to find content with metadata including author, description, views, URL, and hashtags. Specify query and result count to retrieve video information.

Instructions

Search TikTok videos by keyword. Returns metadata: author, description, views, URL, hashtags.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYesSearch query
countNoNumber of results (default 10)

Implementation Reference

  • The search_videos method in the TikTokBrowser class implements the search functionality by navigating to the TikTok search page, parsing video metadata from the page, and scrolling to load more results.
    async def search_videos(self, query: str, count: int = 10) -> list[dict]:
        """Search TikTok for videos matching a query."""
        from urllib.parse import quote_plus
        page = await self.goto_tiktok(f"/search/video?q={quote_plus(query)}")
        await asyncio.sleep(4)
    
        videos = []
        seen_ids = set()
        scroll_attempts = 0
    
        while len(videos) < count and scroll_attempts < count * 2:
            items = await page.evaluate("""() => {
                const videos = [];
                // Use the data-e2e search video item containers
                const cards = document.querySelectorAll('[data-e2e="search_video-item"], [data-e2e="search-card-desc"]');
                // If no e2e containers, fall back to class-based
                const containers = cards.length > 0 ? cards : document.querySelectorAll('[class*="DivItemContainerV2"]');
                
                containers.forEach(card => {
                    try {
                        const link = card.querySelector('a[href*="/video/"]');
                        if (!link) return;
                        const href = link.href;
                        const videoIdMatch = href.match(/video\\/([0-9]+)/);
                        if (!videoIdMatch) return;
                        
                        // Caption: data-e2e="search-card-video-caption" 
                        const captionEl = card.querySelector('[data-e2e="search-card-video-caption"]') ||
                                          card.closest('[class*="DivItemContainerV2"]')?.querySelector('[data-e2e="search-card-video-caption"]');
                        // Author: look for username in the card
                        const authorEl = card.querySelector('[data-e2e="search-card-user-unique-id"]') ||
                                         card.querySelector('a[href*="/@"] span') ||
                                         card.querySelector('[class*="SpanUniqueId"]');
                        // Views/plays from the overlay
                        const viewsEl = card.querySelector('[class*="SpanCount"]') ||
                                        card.querySelector('[class*="PlayLine"] strong') ||
                                        card.querySelector('strong');
                        // Date
                        const dateEl = card.querySelector('[class*="SpanDate"]') || card.querySelector('span[class*="date"]');
                        
                        // Extract hashtags from caption
                        const hashtagEls = card.querySelectorAll('a[href*="/tag/"]');
                        const hashtags = Array.from(hashtagEls).map(h => h.textContent.trim());
                        
                        videos.push({
                            video_id: videoIdMatch[1],
                            url: href,
                            description: captionEl?.textContent?.trim() || link.title || '',
                            author: authorEl?.textContent?.trim() || '',
                            views: viewsEl?.textContent?.trim() || '',
                            date: dateEl?.textContent?.trim() || '',
                            hashtags: hashtags,
                        });
                    } catch(e) {}
                });
                return videos;
            }""")
    
            for item in items:
                vid = item.get("video_id")
                if vid and vid not in seen_ids:
                    seen_ids.add(vid)
                    videos.append(item)
    
            await page.evaluate("window.scrollBy(0, 800)")
            await asyncio.sleep(random.uniform(1.5, 3.0))
            scroll_attempts += 1
    
        return videos[:count]
  • The tiktok_search tool is defined in the TOOLS list in server.py, which specifies its name, description, and input schema.
    Tool(
        name="tiktok_search",
        description="Search TikTok videos by keyword. Returns metadata: author, description, views, URL, hashtags.",
        inputSchema={
            "type": "object",
            "properties": {
                "query": {"type": "string", "description": "Search query"},
                "count": {"type": "integer", "description": "Number of results (default 10)", "default": 10},
            },
            "required": ["query"],
        },
    ),
  • The call_tool function in server.py routes requests with the name "tiktok_search" to the browser.search_videos handler.
    if name == "tiktok_search":
        results = await browser.search_videos(
            arguments["query"],
            arguments.get("count", 10),
        )
        return [TextContent(type="text", text=json.dumps(results, indent=2, ensure_ascii=False))]

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/follox42/tiktok-mcp'

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