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))]
Behavior2/5

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

No annotations are provided, so the description carries full burden. It discloses the return format ('Returns metadata: author, description, views, URL, hashtags'), which is valuable. However, it doesn't mention behavioral aspects like rate limits, authentication requirements, pagination, or whether results are real-time/historical. For a search tool with zero annotation coverage, this leaves significant gaps in understanding its operation.

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 extremely concise and front-loaded: two sentences that directly state the action and output. Every word earns its place—no fluff or redundancy. It efficiently communicates core functionality without unnecessary elaboration.

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 tool's moderate complexity (search with two parameters), no annotations, and no output schema, the description is partially complete. It covers the purpose and return metadata but lacks details on authentication, rate limits, error handling, or how results are ordered/filtered. Without an output schema, the description should ideally explain return values more thoroughly, but it does list key metadata fields.

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 fully documents both parameters (query and count). The description adds no parameter-specific information beyond what's in the schema. According to scoring rules, with high schema coverage (>80%), the baseline is 3 even with no param info in description, which applies here.

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 TikTok videos by keyword' specifies the verb (search) and resource (TikTok videos). It distinguishes from siblings like 'tiktok_trending' (browse trending) or 'tiktok_user_videos' (user-specific), but doesn't explicitly differentiate from 'tiktok_hashtag' (which might also search). The description is specific but not fully sibling-differentiated.

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. With siblings like 'tiktok_hashtag' (likely hashtag-based search), 'tiktok_trending' (trending content), and 'tiktok_feed' (personalized feed), there's no indication of when keyword search is preferred over other search methods or content discovery tools. Usage is implied but not articulated.

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

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