Skip to main content
Glama
crazyrabbitLTC

Twitter MCP Server

getHashtagAnalytics

Analyze Twitter hashtag performance by tracking metrics like engagement and reach within specified time periods to measure campaign effectiveness.

Instructions

Get analytics for a specific hashtag

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
hashtagYesThe hashtag to analyze (with or without #)
startTimeNoStart time for the analysis (ISO 8601)
endTimeNoEnd time for the analysis (ISO 8601)

Implementation Reference

  • The core handler function for 'getHashtagAnalytics' that searches for tweets containing the specified hashtag (optionally within a time range), computes aggregate analytics (total tweets, likes, retweets, replies), and returns formatted results. Handles errors including API tier requirements.
    export const handleHashtagAnalytics: TwitterHandler<HashtagAnalyticsArgs> = async (
        client: TwitterClient | null,
        { hashtag, startTime, endTime }: HashtagAnalyticsArgs
    ): Promise<HandlerResponse> => {
        if (!client) {
            return createMissingTwitterApiKeyResponse('hashtagAnalytics');
        }
        try {
            const query = `#${hashtag.replace(/^#/, '')}`;
            const searchResult = await client.v2.search(query, {
                max_results: 100,
                'tweet.fields': 'public_metrics,created_at',
                start_time: startTime,
                end_time: endTime
            });
    
            const tweets = Array.isArray(searchResult.data) ? searchResult.data : [];
            if (tweets.length === 0) {
                return createResponse(`No tweets found for hashtag: ${hashtag}`);
            }
    
            const analytics = {
                totalTweets: tweets.length,
                totalLikes: tweets.reduce((sum: number, tweet: TweetV2) => 
                    sum + (tweet.public_metrics?.like_count || 0), 0),
                totalRetweets: tweets.reduce((sum: number, tweet: TweetV2) => 
                    sum + (tweet.public_metrics?.retweet_count || 0), 0),
                totalReplies: tweets.reduce((sum: number, tweet: TweetV2) => 
                    sum + (tweet.public_metrics?.reply_count || 0), 0)
            };
    
            return createResponse(`Hashtag Analytics for ${hashtag}:\n${JSON.stringify(analytics, null, 2)}`);
        } catch (error) {
            if (error instanceof Error) {
                if (error.message.includes('400') && error.message.includes('Invalid Request')) {
                    throw new Error(`Hashtag analytics requires Pro tier access ($5,000/month) or higher for search functionality. Current Basic tier ($200/month) does not include recent search API access. Consider upgrading at https://developer.x.com/en/portal/products/pro or use alternative analytics sources.`);
                }
                throw new Error(formatTwitterError(error, 'getting hashtag analytics'));
            }
            throw error;
        }
    }; 
  • Tool schema definition including description and input schema (hashtag required, startTime/endTime optional ISO 8601 strings) used for MCP tool listing and validation.
    getHashtagAnalytics: {
        description: 'Get analytics for a specific hashtag',
        inputSchema: {
            type: 'object',
            properties: {
                hashtag: {
                    type: 'string',
                    description: 'The hashtag to analyze (with or without #)'
                },
                startTime: {
                    type: 'string',
                    description: 'Start time for the analysis (ISO 8601)'
                },
                endTime: {
                    type: 'string',
                    description: 'End time for the analysis (ISO 8601)'
                }
            },
            required: ['hashtag']
        }
    },
  • src/index.ts:318-326 (registration)
    Switch case in the main CallToolRequestHandler that registers and dispatches 'getHashtagAnalytics' calls to the handleHashtagAnalytics function.
    case 'getHashtagAnalytics': {
        const { hashtag, startTime, endTime } = request.params.arguments as {
            hashtag: string;
            startTime?: string;
            endTime?: string;
        };
        response = await handleHashtagAnalytics(client, { hashtag, startTime, endTime });
        break;
    }
  • TypeScript interface defining input arguments for getHashtagAnalytics (note: slightly differs from runtime schema; possibly legacy or additional).
    export interface GetHashtagAnalyticsArgs {
        hashtag: string;
        maxResults?: number;
        tweetFields?: string[];
    }
  • Runtime type assertion function for validating getHashtagAnalytics arguments.
    export function assertGetHashtagAnalyticsArgs(args: unknown): asserts args is GetHashtagAnalyticsArgs {
        if (typeof args !== 'object' || args === null) {
            throw new Error('Invalid arguments: expected object');
        }
        if (!('hashtag' in args) || typeof (args as any).hashtag !== 'string') {
            throw new Error('Invalid arguments: expected hashtag string');
        }
        if ('maxResults' in args) {
            const maxResults = (args as any).maxResults;
            if (typeof maxResults !== 'number' || maxResults < 10 || maxResults > 100) {
                throw new Error('Invalid arguments: maxResults must be a number between 10 and 100');
            }
        }
        if ('tweetFields' in args) {
            if (!Array.isArray((args as any).tweetFields)) {
                throw new Error('Invalid arguments: expected tweetFields to be an array');
            }
            for (const field of (args as any).tweetFields) {
                if (typeof field !== 'string') {
                    throw new Error('Invalid arguments: expected tweetFields to be an array of strings');
                }
            }
        }
    } 
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 states the action ('Get analytics') but does not reveal traits like whether this is a read-only operation, requires authentication, has rate limits, or what the analytics include (e.g., engagement metrics, sentiment). This leaves significant gaps for a tool with no structured safety hints.

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 directly states the tool's purpose without unnecessary words. It is front-loaded and wastes no space, making it easy to parse quickly.

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?

Given the complexity of analytics tools and the lack of annotations and output schema, the description is incomplete. It does not specify what analytics are returned (e.g., metrics, format), behavioral constraints, or how it fits with siblings, leaving the agent with insufficient context for effective use.

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?

The input schema has 100% description coverage, with clear parameter descriptions (e.g., 'hashtag to analyze', 'start time for the analysis'). The description adds no additional meaning beyond this, such as explaining what 'analytics' entails or how time ranges affect results. With high schema coverage, the baseline score of 3 is appropriate as the schema handles the heavy lifting.

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

Purpose3/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description 'Get analytics for a specific hashtag' clearly states the verb ('Get') and resource ('analytics for a specific hashtag'), making the purpose understandable. However, it does not differentiate from sibling tools like 'getHashtagTrends' or 'trendingTopicsSearch', which might also involve hashtag-related data, leaving the scope vague in comparison.

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 lacks context such as whether this is for historical analysis, real-time monitoring, or how it differs from siblings like 'getHashtagTrends' or 'searchTweets', offering no explicit or implied usage rules.

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