Skip to main content
Glama
Bob-lance

Instagram Engagement MCP

analyze_post_comments

Analyze Instagram post comments to identify sentiment, detect key themes, and find potential leads for marketing and engagement insights.

Instructions

Analyze comments on an Instagram post to identify sentiment, themes, and potential leads

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
postUrlYesURL of the Instagram post to analyze
maxCommentsNoMaximum number of comments to analyze (default: 100)

Implementation Reference

  • Main execution logic for the 'analyze_post_comments' tool. Validates input, fetches post media ID, retrieves and paginates comments using instagram-private-api, performs basic sentiment/theme/lead analysis, and returns structured results.
    private async handleAnalyzePostComments(args: AnalyzeCommentsArgs) {
      console.error('[Tool] handleAnalyzePostComments called with args:', args);
      const { postUrl, maxComments = 100 } = args;
    
      if (!isValidPostUrl(postUrl)) {
        throw new McpError(ErrorCode.InvalidParams, 'Invalid post URL format.');
      }
    
      const mediaId = await this.getMediaIdFromUrl(postUrl);
      if (!mediaId) {
        throw new McpError(ErrorCode.InvalidParams, 'Could not extract media ID from post URL.');
      }
      
      console.error(`[Tool] Analyzing comments for media ID: ${mediaId}`);
    
      try {
        const commentsFeed = this.ig.feed.mediaComments(mediaId);
        let comments: any[] = [];
        let commentCount = 0;
        
        // Basic pagination handling
        do {
            const items = await commentsFeed.items();
            comments = comments.concat(items);
            commentCount += items.length;
            console.error(`[Tool] Fetched ${items.length} comments (total: ${commentCount})`);
            if (commentCount >= maxComments) break;
            await new Promise(resolve => setTimeout(resolve, 500 + Math.random() * 500)); // Small delay
        } while (commentsFeed.isMoreAvailable());
        
        comments = comments.slice(0, maxComments); // Trim to maxComments
    
        console.error(`[Tool] Analyzing ${comments.length} comments.`);
    
        // Basic analysis (replace with more sophisticated logic if needed)
        const analysis = {
          totalCommentsFetched: comments.length,
          // Placeholder for sentiment/themes - requires NLP library
          sentiment: 'neutral', 
          topThemes: ['general', 'engagement'],
          potentialLeads: comments.filter(c => c.text.includes('interested') || c.text.includes('DM')).map(c => ({
            username: c.user.username,
            comment: c.text.substring(0, 100), // Truncate long comments
          })),
          sampleComments: comments.slice(0, 5).map(c => ({
            username: c.user.username,
            text: c.text.substring(0, 100),
            timestamp: new Date(c.created_at_utc * 1000).toISOString(),
          })),
        };
    
        return { results: analysis };
      } catch (error: any) {
        console.error(`[API Error] Failed to analyze comments for ${mediaId}:`, error.message || error);
        // Re-throw as McpError or handle specifically
        if (error.name === 'IgNotFoundError') {
            throw new McpError(ErrorCode.InvalidParams, `Post with media ID ${mediaId} not found or access denied.`);
        }
        throw new McpError(ErrorCode.InternalError, `Failed to fetch or analyze comments: ${error.message}`);
      }
    }
  • TypeScript interface defining the expected input parameters for the tool: postUrl (required string) and optional maxComments (number). Matches the inputSchema in registration.
    interface AnalyzeCommentsArgs {
      postUrl: string;
      maxComments?: number;
    }
  • src/index.ts:129-146 (registration)
    Tool definition registered in the ListToolsRequestSchema handler, providing name, description, and JSON schema for inputs.
    {
      name: 'analyze_post_comments',
      description: 'Analyze comments on an Instagram post to identify sentiment, themes, and potential leads',
      inputSchema: {
        type: 'object',
        properties: {
          postUrl: {
            type: 'string',
            description: 'URL of the Instagram post to analyze',
          },
          maxComments: {
            type: 'number',
            description: 'Maximum number of comments to analyze (default: 100)',
          },
        },
        required: ['postUrl'],
      },
    },
  • src/index.ts:266-267 (registration)
    Dispatch case in the CallToolRequestSchema handler that routes execution to the specific handler function.
    case 'analyze_post_comments':
      return await this.handleAnalyzePostComments(args as unknown as AnalyzeCommentsArgs);
  • Helper function used by the handler to resolve Instagram post URL to media ID (PK or shortcode) required for API calls.
    private async getMediaIdFromUrl(url: string): Promise<string | null> {
      try {
         // Extract shortcode first
         const shortcode = extractPostIdFromUrl(url);
         if (!shortcode) return null;
         
         // Getting the numeric media PK (required by many feed functions) from URL/shortcode is unreliable.
         // Option 1: Use a library method if exists (e.g., getIdFromUrl - hypothetical)
         // Option 2: Use media.info(pk) - but we don't have pk!
         // Option 3: Use media.getByUrl(url) - might exist in some versions
         // Option 4: Return the shortcode and hope feed functions accept it (sometimes works)
         // Option 5: Oembed (public, might give ID)
    
         let mediaId: string | null = null;
         
         try {
             // Try using getByUrl if it exists in the installed library version
             // @ts-ignore // Ignore potential TS error if method doesn't exist on type
             const mediaInfo = await this.ig.media.getByUrl(url);
             if (mediaInfo && mediaInfo.pk) {
                  console.log(`[Helper] Found media PK ${mediaInfo.pk} using getByUrl for ${url}`);
                  mediaId = mediaInfo.pk; // pk is the numeric ID
             } else {
                  console.warn(`[Helper Warn] ig.media.getByUrl did not return expected info for ${url}.`);
             }
         } catch(lookupError: any) {
             console.warn(`[Helper Warn] Failed to get media PK using getByUrl for ${url}: ${lookupError.message}.`);
             // If getByUrl fails or doesn't exist, fall back to using the shortcode directly.
             // Note: Some feeds (like mediaComments) require the numeric PK and will fail with the shortcode.
             mediaId = shortcode; 
             console.log(`[Helper] Falling back to using shortcode ${shortcode} as media ID for ${url}`);
         }
         
         if (!mediaId) {
            console.error(`[Helper Error] Could not resolve media ID for shortcode: ${shortcode}`);
            return null;
         }
         
         return mediaId;
    
      } catch (error: any) {
        console.error(`[Helper Error] Failed to get media ID from URL ${url}:`, error.message);
        if (error.name === 'IgNotFoundError') {
            return null;
        }
        return null;
      }
    }
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 mentions analysis outputs (sentiment, themes, leads) but doesn't describe how the analysis is performed, what the return format looks like, whether it requires authentication, rate limits, or potential errors. For a tool with no annotations, this leaves significant gaps in understanding its behavior.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence that states the tool's purpose without unnecessary words. It's front-loaded with the core action ('analyze comments') and key outputs. However, it could be slightly more structured by separating the analysis outputs for clarity.

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 (analysis tool with no annotations and no output schema), the description is incomplete. It doesn't explain the return values, error conditions, or how the analysis is conducted. For a tool that performs sentiment and theme analysis, more context on output format and limitations would be necessary for an AI agent to use it effectively.

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%, so the input schema already documents both parameters ('postUrl' and 'maxComments') with clear descriptions. The description adds no additional semantic context beyond what the schema provides, such as URL format examples or analysis depth implications. Baseline 3 is appropriate when the schema does the heavy lifting.

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 tool's purpose: analyzing Instagram post comments to identify sentiment, themes, and potential leads. It specifies the resource (Instagram post comments) and the analysis outputs (sentiment, themes, leads). However, it doesn't explicitly differentiate from sibling tools like 'identify_leads' or 'generate_engagement_report', which might have overlapping functionality.

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 when to choose this over sibling tools like 'identify_leads' (which might focus on lead identification specifically) or 'generate_engagement_report' (which could involve broader metrics). No exclusions or prerequisites are stated.

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