Skip to main content
Glama
crazyrabbitLTC

Twitter MCP Server

getHashtagTrends

Analyze hashtag performance and trends over specified timeframes to track engagement patterns and identify trending topics on Twitter.

Instructions

Analyze hashtag trends and performance over time

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
hashtagYesHashtag to analyze (with or without #)
timeframeNoAnalysis timeframe (default: "daily")
periodNoNumber of periods to analyze (default: 7)

Implementation Reference

  • Main handler implementation for getHashtagTrends tool. Searches recent tweets for the hashtag, groups them by specified timeframe (hourly/daily/weekly), calculates engagement metrics per period, identifies peaks and trends, and provides content insights.
    export const handleGetHashtagTrends: SocialDataHandler<HashtagTrendsArgs> = async (
        _client: any,
        { hashtag, timeframe = 'daily', period = 7 }: HashtagTrendsArgs
    ) => {
        try {
            const socialClient = getSocialDataClient();
            
            if (!socialClient) {
                return createMissingApiKeyResponse('Hashtag Trends Analysis');
            }
            
            // Clean hashtag
            const cleanHashtag = hashtag.replace(/^#/, '');
            const searchQuery = `#${cleanHashtag}`;
            
            // Get recent tweets with the hashtag
            const result = await socialClient.searchTweets({
                query: searchQuery,
                maxResults: 100
            });
    
            const tweets = result.data || [];
            
            if (tweets.length === 0) {
                return createSocialDataResponse(`No recent data found for hashtag #${cleanHashtag}`);
            }
    
            // Group tweets by time periods
            const now = new Date();
            const timeGroups = new Map();
            
            tweets.forEach((tweet: any) => {
                const tweetDate = new Date(tweet.tweet_created_at);
                let groupKey: string;
                
                if (timeframe === 'hourly') {
                    groupKey = tweetDate.toISOString().substring(0, 13); // YYYY-MM-DDTHH
                } else if (timeframe === 'daily') {
                    groupKey = tweetDate.toISOString().substring(0, 10); // YYYY-MM-DD
                } else {
                    const weekStart = new Date(tweetDate);
                    weekStart.setDate(tweetDate.getDate() - tweetDate.getDay());
                    groupKey = weekStart.toISOString().substring(0, 10);
                }
                
                if (!timeGroups.has(groupKey)) {
                    timeGroups.set(groupKey, []);
                }
                timeGroups.get(groupKey).push(tweet);
            });
    
            // Calculate trend metrics
            const trendData = Array.from(timeGroups.entries())
                .map(([period, periodTweets]: [string, any[]]) => {
                    const totalEngagement = periodTweets.reduce((sum, tweet) => 
                        sum + (tweet.favorite_count || 0) + (tweet.retweet_count || 0), 0);
                    
                    return {
                        period,
                        tweet_count: periodTweets.length,
                        total_engagement: totalEngagement,
                        avg_engagement: Math.round(totalEngagement / periodTweets.length),
                        top_tweet: periodTweets.sort((a, b) => 
                            ((b.favorite_count || 0) + (b.retweet_count || 0)) - 
                            ((a.favorite_count || 0) + (a.retweet_count || 0))
                        )[0]
                    };
                })
                .sort((a, b) => a.period.localeCompare(b.period));
    
            const trends = {
                hashtag: `#${cleanHashtag}`,
                timeframe,
                period_analyzed: period,
                total_tweets: tweets.length,
                trend_data: trendData,
                trend_analysis: {
                    peak_period: trendData.reduce((max, current) => 
                        current.tweet_count > max.tweet_count ? current : max),
                    trending_direction: trendData.length > 1 ? 
                        (trendData[trendData.length - 1].tweet_count > trendData[0].tweet_count ? 'Rising' : 'Declining') : 'Stable',
                    engagement_trend: trendData.length > 1 ?
                        (trendData[trendData.length - 1].avg_engagement > trendData[0].avg_engagement ? 'Increasing' : 'Decreasing') : 'Stable'
                },
                content_insights: {
                    most_engaging_tweet: {
                        text: tweets.sort((a: any, b: any) => 
                            ((b.favorite_count || 0) + (b.retweet_count || 0)) - 
                            ((a.favorite_count || 0) + (a.retweet_count || 0))
                        )[0]?.text?.substring(0, 200),
                        engagement: ((tweets[0]?.favorite_count || 0) + (tweets[0]?.retweet_count || 0))
                    },
                    avg_tweet_length: Math.round(tweets.reduce((sum: number, tweet: any) => 
                        sum + (tweet.text?.length || 0), 0) / tweets.length)
                }
            };
    
            return createSocialDataResponse(
                formatAnalytics(trends, `Hashtag Trends Analysis: #${cleanHashtag}`)
            );
        } catch (error) {
            throw new Error(formatSocialDataError(error as Error, 'hashtag trends analysis'));
        }
    };
  • TypeScript interface defining input arguments for the handleGetHashtagTrends handler.
    interface HashtagTrendsArgs {
        hashtag: string;
        timeframe: 'hourly' | 'daily' | 'weekly';
        period?: number;
    }
  • MCP tool schema definition for getHashtagTrends, including input schema with properties matching the handler args.
    getHashtagTrends: {
        description: 'Analyze hashtag trends and performance over time',
        inputSchema: {
            type: 'object',
            properties: {
                hashtag: {
                    type: 'string',
                    description: 'Hashtag to analyze (with or without #)'
                },
                timeframe: {
                    type: 'string',
                    enum: ['hourly', 'daily', 'weekly'],
                    description: 'Analysis timeframe (default: "daily")'
                },
                period: {
                    type: 'number',
                    description: 'Number of periods to analyze (default: 7)',
                    minimum: 1,
                    maximum: 30
                }
            },
            required: ['hashtag']
        }
    },
  • src/index.ts:489-492 (registration)
    Tool dispatch/registration in the main MCP server request handler switch statement, calling the handler function.
    case 'getHashtagTrends': {
        const args = request.params.arguments as any;
        response = await handleGetHashtagTrends(client, args);
        break;
  • src/index.ts:80-82 (registration)
    Import statement bringing in the handleGetHashtagTrends handler for use in the MCP server.
    handleGetHashtagTrends,
    handleAnalyzeSentiment,
    handleTrackVirality
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. While 'analyze' suggests a read-only operation, the description doesn't clarify whether this requires authentication, has rate limits, returns paginated results, or what format the analysis output takes. Significant behavioral details are missing.

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 a single, efficient sentence that gets straight to the point with zero wasted words. It's appropriately sized for a tool with three parameters and front-loads the essential information.

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

Completeness2/5

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

For a tool with no annotations and no output schema, the description is insufficiently complete. It doesn't explain what 'analyze' returns (metrics, charts, time series data?), doesn't address authentication requirements or rate limits, and doesn't differentiate from similar sibling tools. The agent would have significant gaps in understanding how to properly use this tool.

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 already documents all three parameters thoroughly. The description doesn't add any meaningful parameter semantics beyond what's in the schema - it doesn't explain how the parameters interact or what 'analyze' specifically entails. Baseline 3 is appropriate when the schema does the heavy lifting.

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 with a specific verb ('analyze') and resource ('hashtag trends and performance over time'), making it easy to understand what the tool does. However, it doesn't explicitly differentiate from sibling tools like 'getHashtagAnalytics' or 'trendingTopicsSearch', which appear to have related 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. With sibling tools like 'getHashtagAnalytics' and 'trendingTopicsSearch' available, there's no indication of how this tool differs or when it should be preferred over those options.

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/crazyrabbitLTC/mcp-twitter-server'

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