get_social_analytics
Analyze Facebook and Instagram performance metrics including reach, engagement, and top-performing posts to measure social media effectiveness.
Instructions
Get performance analytics from Facebook and Instagram including reach, engagement, and top posts.
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| period | No | Number of days to analyze (default: 7) | |
| platform | Yes | Platform: facebook or instagram |
Implementation Reference
- src/index.ts:1200-1241 (handler)The primary handler logic for the 'get_social_analytics' tool. It checks configuration, parses input parameters (platform and period), calls socialMediaManager.getFacebookAnalytics for Facebook, and formats the response with metrics and top posts.case 'get_social_analytics': { if (!socialMediaManager.isConfigured()) { return { content: [{ type: 'text', text: `⚠️ Social media not configured. See FACEBOOK_INSTAGRAM_SETUP.md for setup instructions.` }] }; } const platform = String(args?.platform || 'facebook'); const period = Number(args?.period || 7); try { if (platform.toLowerCase() === 'facebook') { const analytics = await socialMediaManager.getFacebookAnalytics(period); return { content: [{ type: 'text', text: `📊 Facebook Analytics - ${analytics.period}\n\n📈 Performance Metrics:\n 👥 Reach: ${analytics.metrics.reach.toLocaleString()}\n 👁️ Impressions: ${analytics.metrics.impressions.toLocaleString()}\n 💬 Engagement: ${analytics.metrics.engagement.toLocaleString()}\n ⭐ Followers: ${analytics.metrics.followers.toLocaleString()}\n\n🏆 Top Posts:\n${analytics.topPosts.map((post, i) => `${i + 1}. ${post.content}\n ❤️ ${post.likes} | 💬 ${post.comments} | 🔄 ${post.shares}` ).join('\n\n')}\n\n💡 Insight: Post more content like your top performers to boost engagement!` }] }; } else { return { content: [{ type: 'text', text: `📊 Instagram Analytics coming soon! Currently only Facebook analytics are available.` }] }; } } catch (error: any) { return { content: [{ type: 'text', text: `❌ Failed to fetch analytics: ${error.message}` }] }; } }
- src/index.ts:402-413 (schema)The tool's input schema definition, specifying required 'platform' parameter and optional 'period' for the number of days.{ name: 'get_social_analytics', description: 'Get performance analytics from Facebook and Instagram including reach, engagement, and top posts.', inputSchema: { type: 'object', properties: { platform: { type: 'string', description: 'Platform: facebook or instagram' }, period: { type: 'number', description: 'Number of days to analyze (default: 7)' }, }, required: ['platform'], }, },
- src/social-media.ts:275-352 (helper)Core helper function getFacebookAnalytics that fetches page insights and posts from Facebook Graph API, parses metrics like reach, impressions, engagement, followers, and top performing posts.async getFacebookAnalytics(days: number = 7): Promise<Analytics> { if (!this.isConfigured()) { throw new Error('Facebook API not configured'); } try { // Get page insights const insightsUrl = `https://graph.facebook.com/${this.apiVersion}/${this.fbPageId}/insights`; const params = new URLSearchParams({ metric: 'page_impressions,page_engaged_users,page_fans', period: 'day', since: Math.floor((Date.now() - (days * 24 * 60 * 60 * 1000)) / 1000).toString(), access_token: this.fbPageToken }); const response = await fetch(`${insightsUrl}?${params}`); const result = await response.json() as any; // Get recent posts for top posts const postsUrl = `https://graph.facebook.com/${this.apiVersion}/${this.fbPageId}/posts`; const postsParams = new URLSearchParams({ fields: 'message,likes.summary(true),comments.summary(true),shares', limit: '10', access_token: this.fbPageToken }); const postsResponse = await fetch(`${postsUrl}?${postsParams}`); const postsResult = await postsResponse.json() as any; // Parse metrics let reach = 0; let engagement = 0; let followers = 0; if (result.data) { for (const metric of result.data) { if (metric.name === 'page_impressions' && metric.values.length > 0) { reach = metric.values.reduce((sum: number, v: any) => sum + (v.value || 0), 0); } if (metric.name === 'page_engaged_users' && metric.values.length > 0) { engagement = metric.values.reduce((sum: number, v: any) => sum + (v.value || 0), 0); } if (metric.name === 'page_fans' && metric.values.length > 0) { followers = metric.values[metric.values.length - 1].value || 0; } } } // Parse top posts const topPosts = []; if (postsResult.data) { for (const post of postsResult.data.slice(0, 5)) { topPosts.push({ id: post.id, content: (post.message || '').substring(0, 100) + '...', likes: post.likes?.summary?.total_count || 0, comments: post.comments?.summary?.total_count || 0, shares: post.shares?.count || 0 }); } } return { platform: 'facebook', period: `last ${days} days`, metrics: { reach: reach, impressions: reach, // Simplified engagement: engagement, followers: followers, followerGrowth: 0 // Would need historical comparison }, topPosts: topPosts }; } catch (error: any) { throw new Error(`Failed to fetch analytics: ${error.message}`); } }
- src/social-media.ts:34-51 (schema)TypeScript interface defining the structure of the Analytics object returned by getFacebookAnalytics, used for output validation.interface Analytics { platform: string; period: string; metrics: { reach: number; impressions: number; engagement: number; followers: number; followerGrowth: number; }; topPosts: Array<{ id: string; content: string; likes: number; comments: number; shares: number; }>; }
- src/index.ts:516-518 (registration)Registration of all tools including 'get_social_analytics' via the ListToolsRequestSchema handler that returns the tools array containing the tool definition.server.setRequestHandler(ListToolsRequestSchema, async () => { return { tools }; });