trackVirality
Analyze tweet engagement velocity and spread patterns to identify viral content trends on Twitter.
Instructions
Track viral spread patterns and engagement velocity
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| tweetId | Yes | Tweet ID to track virality for | |
| trackingPeriod | No | Period to track (default: "24h") | |
| analyzeSpread | No | Include detailed spread analysis (default: true) |
Implementation Reference
- The core handler function that implements the trackVirality tool logic. It searches for retweets, quotes, and discussions related to a given tweet ID, analyzes spread patterns over time, calculates virality metrics including velocity, peak hours, top spreaders, and a viral score.export const handleTrackVirality: SocialDataHandler<ViralityTrackingArgs> = async ( _client: any, { tweetId, trackingPeriod = '24h', analyzeSpread = true }: ViralityTrackingArgs ) => { try { const socialClient = getSocialDataClient(); if (!socialClient) { return createMissingApiKeyResponse('Virality Tracking'); } // Search for retweets and mentions of the tweet const viralQuery = `${tweetId} OR url:${tweetId}`; const viralResult = await socialClient.searchTweets({ query: viralQuery, maxResults: 100 }); // Search for quotes and discussions const discussionQuery = `"${tweetId}"`; const discussionResult = await socialClient.searchTweets({ query: discussionQuery, maxResults: 50 }); const allInteractions = [...(viralResult.data || []), ...(discussionResult.data || [])]; if (allInteractions.length === 0) { return createSocialDataResponse(`No viral spread detected for tweet ${tweetId}`); } // Analyze spread pattern const spreadAnalysis: any = { tweet_id: tweetId, tracking_period: trackingPeriod, total_interactions: allInteractions.length, spread_metrics: { direct_shares: viralResult.data?.length || 0, discussions: discussionResult.data?.length || 0, unique_users: new Set(allInteractions.map(t => t.user?.screen_name)).size } }; if (analyzeSpread) { // Group by time to see spread velocity const timeGroups = new Map(); allInteractions.forEach((tweet: any) => { const hour = new Date(tweet.tweet_created_at).toISOString().substring(0, 13); if (!timeGroups.has(hour)) { timeGroups.set(hour, []); } timeGroups.get(hour).push(tweet); }); const spreadVelocity = Array.from(timeGroups.entries()) .map(([hour, tweets]: [string, any[]]) => ({ hour, interactions: tweets.length, cumulative: 0 // Will be calculated below })) .sort((a, b) => a.hour.localeCompare(b.hour)); // Calculate cumulative spread let cumulative = 0; spreadVelocity.forEach(period => { cumulative += period.interactions; period.cumulative = cumulative; }); // Find peak spread hour const peakHour = spreadVelocity.reduce((max, current) => current.interactions > max.interactions ? current : max); // Analyze influential spreaders const userEngagement = new Map(); allInteractions.forEach((tweet: any) => { const user = tweet.user?.screen_name; if (user) { const engagement = (tweet.favorite_count || 0) + (tweet.retweet_count || 0); userEngagement.set(user, (userEngagement.get(user) || 0) + engagement); } }); const topSpreaders = Array.from(userEngagement.entries()) .sort(([,a], [,b]) => b - a) .slice(0, 10) .map(([user, engagement]) => ({ user, engagement })); spreadAnalysis.virality_analysis = { spread_velocity: spreadVelocity, peak_spread_hour: peakHour.hour, viral_coefficient: Math.round(allInteractions.length / Math.max(1, timeGroups.size)), spread_pattern: spreadVelocity.length > 5 ? (peakHour.interactions > spreadVelocity[0].interactions * 3 ? 'Exponential' : 'Linear') : 'Limited', top_spreaders: topSpreaders, reach_estimate: topSpreaders.reduce((sum, spreader) => sum + spreader.engagement, 0), viral_score: Math.min(100, Math.round( (allInteractions.length * 0.3) + (userEngagement.size * 0.4) + (peakHour.interactions * 0.3) )) }; } return createSocialDataResponse( formatAnalytics(spreadAnalysis, `Virality Tracking for Tweet ${tweetId}`) ); } catch (error) { throw new Error(formatSocialDataError(error as Error, 'virality tracking')); } };
- src/socialdata-tools.ts:367-387 (schema)JSON Schema definition for the trackVirality tool, defining input parameters, descriptions, and requirements for tool discovery and validation.trackVirality: { description: 'Track viral spread patterns and engagement velocity', inputSchema: { type: 'object', properties: { tweetId: { type: 'string', description: 'Tweet ID to track virality for' }, trackingPeriod: { type: 'string', description: 'Period to track (default: "24h")' }, analyzeSpread: { type: 'boolean', description: 'Include detailed spread analysis (default: true)' } }, required: ['tweetId'] } }
- TypeScript interface defining the typed arguments for the handleTrackVirality function.interface ViralityTrackingArgs { tweetId: string; trackingPeriod?: string; analyzeSpread?: boolean; }
- src/index.ts:499-503 (registration)Registration in the main MCP server tool request handler switch statement, dispatching calls to the trackVirality tool to the appropriate handler function.case 'trackVirality': { const args = request.params.arguments as any; response = await handleTrackVirality(client, args); break; }