Skip to main content
Glama
Bob-lance

Instagram Engagement MCP

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
NameRequiredDescriptionDefault
accountsYesList of Instagram account handles to compare
metricsNoMetrics to compare (default: all)

Implementation Reference

  • 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 };
    }
  • 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);
  • 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);
    };
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure. It states what the tool does but lacks details on permissions, rate limits, data freshness, or output format. For a tool that likely accesses external data (Instagram accounts), this omission is significant and leaves behavioral traits unclear.

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 appropriately sized, making it easy for an agent 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 comparing engagement metrics across accounts, the lack of annotations and output schema means the description is incomplete. It doesn't explain what the comparison outputs (e.g., a table, summary, or raw data), how metrics are calculated, or any limitations, which are crucial for effective tool 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 schema description coverage is 100%, with clear descriptions for both parameters (e.g., 'List of Instagram account handles to compare' and 'Metrics to compare (default: all)'). The description adds no additional parameter semantics beyond what the schema provides, so it meets the baseline for adequate but not enhanced coverage.

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 action ('compare') and the resource ('engagement metrics across different Instagram accounts'), providing a specific purpose. However, it doesn't explicitly differentiate this tool from its sibling tools (like 'generate_engagement_report' or 'analyze_post_comments'), which might also involve engagement metrics analysis.

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 doesn't mention prerequisites, context for comparison, or how it differs from sibling tools such as 'generate_engagement_report' or 'analyze_post_comments', leaving the agent to infer usage scenarios.

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/Bob-lance/instagram-engagement-mcp'

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