Skip to main content
Glama

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; } }

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