Skip to main content
Glama
Talhelf
by Talhelf

search_trends

Analyze Google Trends data for adult entertainment keywords to track search interest over time, compare terms, and identify regional patterns.

Instructions

Search Google Trends for any keywords (performers, platforms, categories, etc.).

Args:
    keywords: List of search terms to analyze (max 5). Examples:
              ["Lana Rhoades", "Riley Reid"]
              ["pornhub", "onlyfans"]
              ["milf", "teen", "amateur"]
    timeframe: Time period. Options:
               'today 12-m' (past year, default)
               'today 3-m' (past 3 months)
               'today 5-y' (past 5 years)
               '2020-01-01 2024-12-31' (custom date range)
               Available back to 2004
    region: Geographic region code:
            'US' (USA, default)
            'GB' (UK)
            '' (Worldwide)
            Any ISO country code

Returns:
    Complete Google Trends analysis with interest over time, regional data, and related queries.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
keywordsYes
timeframeNotoday 12-m
regionNoUS

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • Main handler function for search_trends tool. Registered with @mcp.tool() decorator. Accepts keywords (list), timeframe (string), and region (string) parameters. Fetches Google Trends data, formats results using helper functions, and returns a comprehensive analysis with interest over time, regional data, and related queries.
    @mcp.tool()
    async def search_trends(
        keywords: list[str],
        timeframe: str = "today 12-m",
        region: str = "US"
    ) -> str:
        """
        Search Google Trends for any keywords (performers, platforms, categories, etc.).
        
        Args:
            keywords: List of search terms to analyze (max 5). Examples:
                      ["Lana Rhoades", "Riley Reid"]
                      ["pornhub", "onlyfans"]
                      ["milf", "teen", "amateur"]
            timeframe: Time period. Options:
                       'today 12-m' (past year, default)
                       'today 3-m' (past 3 months)
                       'today 5-y' (past 5 years)
                       '2020-01-01 2024-12-31' (custom date range)
                       Available back to 2004
            region: Geographic region code:
                    'US' (USA, default)
                    'GB' (UK)
                    '' (Worldwide)
                    Any ISO country code
        
        Returns:
            Complete Google Trends analysis with interest over time, regional data, and related queries.
        """
        
        if not pytrends:
            return "❌ Google Trends API is not available. Please check configuration."
        
        if len(keywords) > 5:
            return "⚠️  Maximum 5 keywords allowed per query. Please reduce your list."
        
        if len(keywords) == 0:
            return "⚠️  Please provide at least one keyword to search."
        
        # Fetch data
        data = get_trends_data(keywords, timeframe, region)
        
        # Format and return results
        result = [
            format_interest_over_time(data),
            "",
            format_regional_interest(data, top_n=10),
            format_related_queries(data),
            "",
            "📝 Notes:",
            "- Values are on a 0-100 scale where 100 = peak popularity for the time period",
            "- Data represents search interest, not absolute search volumes",
            f"- Data fetched: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
        ]
        
        return "\n".join(result)
  • Core helper function get_trends_data that interacts with Google Trends API. Handles caching, rate limiting, and fetches interest over time, interest by region, and related queries data. Returns a dictionary with all the trend data.
    def get_trends_data(keywords: list[str], timeframe: str = 'today 12-m', geo: str = 'US') -> dict:
        """
        Fetch Google Trends data for given keywords.
        
        Args:
            keywords: List of search terms to compare (max 5)
            timeframe: Time period (e.g., 'today 12-m', 'today 5-y', '2020-01-01 2024-12-31')
            geo: Geographic region (e.g., 'US', 'GB', '' for worldwide)
        
        Returns:
            Dictionary with trends data
        """
        if not pytrends:
            return {"error": "Google Trends API not available"}
        
        # Check cache
        cache_key = f"{','.join(keywords)}_{timeframe}_{geo}"
        if cache_key in TRENDS_CACHE:
            cached = TRENDS_CACHE[cache_key]
            age = (datetime.now() - datetime.fromisoformat(cached['fetched_at'])).seconds
            if age < 3600:  # Cache for 1 hour
                print(f"Using cached data (age: {age}s)", file=sys.stderr)
                return cached
        
        try:
            print(f"Fetching Google Trends: {keywords}, {timeframe}, {geo}", file=sys.stderr)
            
            # Build payload
            pytrends.build_payload(keywords, cat=0, timeframe=timeframe, geo=geo, gprop='')
            
            # Get interest over time
            interest_over_time_df = pytrends.interest_over_time()
            
            # Get interest by region
            try:
                interest_by_region_df = pytrends.interest_by_region(resolution='REGION', inc_low_vol=True, inc_geo_code=False)
            except Exception as e:
                print(f"Could not fetch regional data: {e}", file=sys.stderr)
                interest_by_region_df = pd.DataFrame()
            
            # Get related queries
            try:
                related_queries = pytrends.related_queries()
            except Exception as e:
                print(f"Could not fetch related queries: {e}", file=sys.stderr)
                related_queries = {}
            
            result = {
                "keywords": keywords,
                "timeframe": timeframe,
                "geo": geo,
                "interest_over_time": interest_over_time_df.to_dict() if not interest_over_time_df.empty else {},
                "interest_by_region": interest_by_region_df.to_dict() if not interest_by_region_df.empty else {},
                "related_queries": related_queries,
                "fetched_at": datetime.now().isoformat()
            }
            
            # Cache the result
            TRENDS_CACHE[cache_key] = result
            
            # Rate limiting
            time.sleep(1)
            
            return result
            
        except Exception as e:
            print(f"Error fetching Google Trends data: {e}", file=sys.stderr)
            return {"error": str(e)}
  • Helper function format_interest_over_time that formats the Google Trends time-series data into readable text, calculating statistics (average, peak, low, trend direction) for each keyword.
    def format_interest_over_time(data: dict) -> str:
        """Format interest over time data into readable text."""
        if "error" in data:
            return f"❌ Error: {data['error']}"
        
        if not data.get("interest_over_time"):
            return "No data available for the specified time period and keywords."
        
        lines = [
            f"📊 Google Trends Analysis",
            f"Keywords: {', '.join(data['keywords'])}",
            f"Region: {data['geo'] if data['geo'] else 'Worldwide'}",
            f"Period: {data['timeframe']}",
            "=" * 60,
            ""
        ]
        
        # Calculate statistics for each keyword
        interest_data = data['interest_over_time']
        if interest_data:
            lines.append("📈 Search Interest Statistics (0-100 scale):")
            lines.append("")
            
            for keyword in data['keywords']:
                if keyword in interest_data:
                    values = [v for v in interest_data[keyword].values() if isinstance(v, (int, float))]
                    if values:
                        avg = sum(values) / len(values)
                        max_val = max(values)
                        min_val = min(values)
                        
                        lines.append(f"'{keyword}':")
                        lines.append(f"   Average: {avg:.1f}")
                        lines.append(f"   Peak: {max_val}")
                        lines.append(f"   Low: {min_val}")
                        
                        # Trend direction
                        if len(values) >= 2:
                            recent_avg = sum(values[-4:]) / min(4, len(values[-4:]))
                            older_avg = sum(values[:4]) / min(4, len(values[:4]))
                            if recent_avg > older_avg * 1.1:
                                lines.append(f"   Trend: 📈 Growing ({((recent_avg/older_avg - 1) * 100):.0f}%)")
                            elif recent_avg < older_avg * 0.9:
                                lines.append(f"   Trend: 📉 Declining ({((1 - recent_avg/older_avg) * 100):.0f}%)")
                            else:
                                lines.append(f"   Trend: ➡️  Stable")
                        
                        lines.append("")
        
        return "\n".join(lines)
  • Helper function format_regional_interest that formats regional interest data, sorting and displaying the top N regions by search interest for each keyword.
    def format_regional_interest(data: dict, top_n: int = 10) -> str:
        """Format regional interest data into readable text."""
        if "error" in data:
            return f"❌ Error: {data['error']}"
        
        if not data.get("interest_by_region"):
            return "No regional data available."
        
        lines = [
            f"🌎 Regional Interest",
            "=" * 60,
            ""
        ]
        
        region_data = data['interest_by_region']
        for keyword in data['keywords']:
            if keyword in region_data:
                lines.append(f"Top regions for '{keyword}':")
                
                # Sort regions by interest
                regions = {region: value for region, value in region_data[keyword].items() 
                          if isinstance(value, (int, float)) and value > 0}
                sorted_regions = sorted(regions.items(), key=lambda x: x[1], reverse=True)[:top_n]
                
                if sorted_regions:
                    for i, (region, value) in enumerate(sorted_regions, 1):
                        lines.append(f"   {i}. {region}: {value}/100")
                else:
                    lines.append("   No regional data available")
                lines.append("")
        
        return "\n".join(lines)
  • Helper function format_related_queries that formats related and rising queries data, showing top related searches and breakout/rising search terms.
    def format_related_queries(data: dict) -> str:
        """Format related queries data."""
        if "error" in data or not data.get("related_queries"):
            return ""
        
        lines = [
            "",
            "🔍 Related & Trending Queries",
            "=" * 60,
            ""
        ]
        
        related = data['related_queries']
        for keyword in data['keywords']:
            if keyword in related:
                lines.append(f"Related to '{keyword}':")
                
                # Top related queries
                if 'top' in related[keyword] and related[keyword]['top'] is not None:
                    top_df = related[keyword]['top']
                    if not top_df.empty:
                        lines.append("  Top:")
                        for idx, row in top_df.head(5).iterrows():
                            lines.append(f"    • {row['query']} ({row['value']})")
                
                # Rising queries
                if 'rising' in related[keyword] and related[keyword]['rising'] is not None:
                    rising_df = related[keyword]['rising']
                    if not rising_df.empty:
                        lines.append("  Rising:")
                        for idx, row in rising_df.head(5).iterrows():
                            growth = row['value']
                            if growth == 'Breakout':
                                lines.append(f"    • {row['query']} (🔥 Breakout)")
                            else:
                                lines.append(f"    • {row['query']} (+{growth}%)")
                
                lines.append("")
        
        return "\n".join(lines)
Behavior4/5

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

With no annotations provided, the description carries full burden and does well by specifying parameter constraints (max 5 keywords, timeframe options back to 2004, region codes). It also describes the return format ('interest over time, regional data, and related queries'), though it doesn't mention rate limits or authentication needs.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is well-structured with clear sections (Args, Returns) and uses bullet points efficiently. It's appropriately sized but could be slightly more concise by integrating some details into the opening sentence.

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

Completeness5/5

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

Given the complexity of a 3-parameter tool with no annotations, the description provides complete context: clear purpose, detailed parameter semantics, and output description. With an output schema present, it doesn't need to explain return values in depth, making this comprehensive.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters5/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, so the description must compensate fully. It provides detailed semantics for all 3 parameters: keywords with examples and max limit, timeframe with options and date range availability, and region with codes and defaults. This adds significant value beyond the bare schema.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/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 with a specific verb ('Search Google Trends') and resource ('for any keywords'), listing examples of keyword types. It distinguishes from siblings by focusing on general keyword search rather than specific comparisons or historical analysis.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage for analyzing search trends with keywords, but doesn't explicitly state when to use this tool versus alternatives like 'compare_performers' or 'historical_analysis'. No exclusions or specific contexts are provided beyond the general purpose.

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/Talhelf/ph-mcp'

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