Skip to main content
Glama
Talhelf
by Talhelf

historical_analysis

Analyze historical search trends for adult entertainment keywords across years to identify growth patterns, peaks, and regional variations.

Instructions

Analyze historical trends for a keyword across multiple years.

Args:
    keyword: Single keyword to analyze (performer, platform, or category)
            Example: "Lana Rhoades", "onlyfans", "milf"
    start_year: Starting year (2004 or later)
    end_year: Ending year (default: 2024)
    region: Region code (default: US)

Returns:
    Multi-year trend analysis showing growth, peaks, and patterns.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
keywordYes
start_yearNo
end_yearNo
regionNoUS

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • Main implementation of the historical_analysis tool. Decorated with @mcp.tool(), it analyzes historical trends for a keyword across multiple years using Google Trends data. Handles input validation (year >= 2004, start_year < end_year) and formats the timeframe before delegating to search_trends helper.
    @mcp.tool()
    async def historical_analysis(
        keyword: str,
        start_year: int = 2020,
        end_year: int = 2024,
        region: str = "US"
    ) -> str:
        """
        Analyze historical trends for a keyword across multiple years.
        
        Args:
            keyword: Single keyword to analyze (performer, platform, or category)
                    Example: "Lana Rhoades", "onlyfans", "milf"
            start_year: Starting year (2004 or later)
            end_year: Ending year (default: 2024)
            region: Region code (default: US)
        
        Returns:
            Multi-year trend analysis showing growth, peaks, and patterns.
        """
        
        if start_year < 2004:
            return "⚠️  Google Trends data is only available from 2004 onwards."
        
        if start_year >= end_year:
            return "⚠️  Start year must be before end year."
        
        timeframe = f"{start_year}-01-01 {end_year}-12-31"
        
        result = await search_trends([keyword], timeframe, region)
        
        return f"📅 Historical Analysis: {start_year}-{end_year}\n\n{result}"
  • Core search_trends helper function called by historical_analysis. Fetches and formats Google Trends data for given keywords, timeframe, and region. Validates inputs (max 5 keywords), calls get_trends_data, and formats results with interest over time, regional data, and related queries.
    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)
  • Low-level get_trends_data helper function that interfaces with the Google Trends API (pytrends). Builds API payload, fetches interest over time, regional data, and related queries. Implements caching (1 hour) and rate limiting to avoid excessive API calls.
    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)}
Behavior2/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. It mentions the tool returns 'Multi-year trend analysis showing growth, peaks, and patterns,' which gives some output context, but it lacks critical details: it doesn't specify data sources, rate limits, authentication needs, error conditions, or whether it's a read-only operation. For a tool with no annotations, this leaves significant gaps in understanding its behavior.

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 and appropriately sized. It front-loads the purpose in the first sentence, then lists parameters and returns in clear sections. Every sentence adds value, with no redundant or vague phrasing. Minor improvements could include briefer examples or combining some details, but overall it's efficient.

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 (4 parameters, no annotations, but has an output schema), the description is partially complete. It covers the purpose and parameters well, and the output schema likely handles return values, reducing the need for detailed output explanation. However, it lacks behavioral context (e.g., data sources, limitations) and usage guidelines, making it adequate but with clear gaps for an agent to operate effectively.

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

Parameters4/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. It adds meaningful semantics beyond the schema: it explains that 'keyword' can be a performer, platform, or category with examples ('Lana Rhoades', 'onlyfans', 'milf'), specifies constraints for 'start_year' ('2004 or later'), and clarifies defaults for 'end_year' and 'region'. This effectively documents all parameters, though it could provide more detail on format (e.g., region code standards).

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: 'Analyze historical trends for a keyword across multiple years.' It specifies the verb ('analyze'), resource ('historical trends'), and scope ('keyword across multiple years'), making it easy to understand what the tool does. However, it doesn't explicitly differentiate this from sibling tools like 'analyze_category_trends' or 'compare_performers', which likely have overlapping functionality.

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. It doesn't mention sibling tools like 'analyze_category_trends' or 'compare_performers', nor does it specify prerequisites, exclusions, or typical use cases. The agent must infer usage from the purpose alone, which is insufficient for optimal tool selection.

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