compare_accounts
Analyze and compare Instagram account performance by evaluating key engagement metrics like followers, posts, comments, and likes to inform strategy decisions.
Instructions
Compare engagement metrics across different Instagram accounts
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| accounts | Yes | List of Instagram account handles to compare | |
| metrics | No | Metrics to compare (default: all) |
Implementation Reference
- src/index.ts:363-426 (handler)The handler function that executes the compare_accounts tool. It validates input accounts, fetches Instagram user info using IgApiClient, calculates metrics like followers, posts, engagement rate from recent posts, and returns comparison results.private async handleCompareAccounts(args: CompareAccountsArgs) { console.error('[Tool] handleCompareAccounts called with args:', args); const { accounts, metrics = ['followers', 'engagement', 'posts'] } = args; if (!accounts || accounts.length === 0) { throw new McpError(ErrorCode.InvalidParams, 'At least one account handle must be provided.'); } if (accounts.some(acc => !isValidUsername(acc))) { throw new McpError(ErrorCode.InvalidParams, 'One or more account handles are invalid.'); } const comparisonResults: any = {}; for (const username of accounts) { console.error(`[Tool] Fetching data for account: ${username}`); try { const userId = await this.ig.user.getIdByUsername(username); const userInfo = await this.ig.user.info(userId); // Basic metrics calculation const followerCount = userInfo.follower_count; const followingCount = userInfo.following_count; const postCount = userInfo.media_count; // Placeholder for engagement - requires fetching recent posts and calculating average likes/comments let engagementRate = 0; if (followerCount > 0) { // Fetch recent posts - limited scope for example const postsFeed = this.ig.feed.user(userId); const recentPosts = await postsFeed.items(); if (recentPosts.length > 0) { const totalLikes = recentPosts.reduce((sum, post) => sum + (post.like_count || 0), 0); const totalComments = recentPosts.reduce((sum, post) => sum + (post.comment_count || 0), 0); const avgLikes = totalLikes / recentPosts.length; const avgComments = totalComments / recentPosts.length; engagementRate = ((avgLikes + avgComments) / followerCount) * 100; } } comparisonResults[username] = { userId: userId, fullName: userInfo.full_name, isPrivate: userInfo.is_private, isVerified: userInfo.is_verified, followers: metrics.includes('followers') ? followerCount : undefined, following: metrics.includes('following') ? followingCount : undefined, // Added following as potential metric posts: metrics.includes('posts') ? postCount : undefined, engagementRate: metrics.includes('engagement') ? parseFloat(engagementRate.toFixed(2)) : undefined, // Simplified engagement // 'likes' and 'comments' metrics would typically be per post, not overall account. }; console.error(`[Tool] Successfully fetched data for ${username}`); await new Promise(resolve => setTimeout(resolve, 300 + Math.random() * 400)); // Small delay } catch (error: any) { console.error(`[API Error] Failed to get info for account ${username}:`, error.message || error); comparisonResults[username] = { error: `Failed to fetch data: ${error.message}` }; if (error.name === 'IgNotFoundError') { comparisonResults[username] = { error: 'Account not found.' }; } } } return { results: comparisonResults }; }
- src/index.ts:33-36 (schema)TypeScript interface defining the input arguments for the compare_accounts tool: array of account usernames and optional metrics to compare.interface CompareAccountsArgs { accounts: string[]; metrics?: string[]; }
- src/index.ts:147-170 (registration)Tool registration in the ListTools response, including name, description, and inputSchema matching the CompareAccountsArgs interface.{ name: 'compare_accounts', description: 'Compare engagement metrics across different Instagram accounts', inputSchema: { type: 'object', properties: { accounts: { type: 'array', items: { type: 'string', }, description: 'List of Instagram account handles to compare', }, metrics: { type: 'array', items: { type: 'string', enum: ['followers', 'engagement', 'posts', 'comments', 'likes'], }, description: 'Metrics to compare (default: all)', }, }, required: ['accounts'], },
- src/index.ts:268-269 (registration)Dispatch case in the CallToolRequestSchema handler that routes to the compare_accounts handler function.case 'compare_accounts': return await this.handleCompareAccounts(args as unknown as CompareAccountsArgs);
- src/index.ts:69-72 (helper)Utility function to validate Instagram usernames, used in the handler for input validation.// Utility function to validate Instagram username const isValidUsername = (username: string): boolean => { return /^[A-Za-z0-9._]+$/.test(username); };