analyze_post_comments
Examine Instagram post comments to detect sentiment, uncover key themes, and identify potential leads based on user interactions. Provide the post URL and optional limit for comment analysis.
Instructions
Analyze comments on an Instagram post to identify sentiment, themes, and potential leads
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| maxComments | No | Maximum number of comments to analyze (default: 100) | |
| postUrl | Yes | URL of the Instagram post to analyze |
Implementation Reference
- src/index.ts:301-361 (handler)The primary handler function that executes the 'analyze_post_comments' tool. It validates the post URL, extracts the media ID, fetches up to maxComments comments using Instagram Private API, performs basic analysis including sentiment (placeholder), themes, potential leads based on keywords, and returns sample comments.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}`); } }
- src/index.ts:129-146 (registration)Registers the 'analyze_post_comments' tool in the MCP server's ListTools response, defining its name, description, and input schema for validation.{ 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:28-31 (schema)TypeScript interface defining the expected input parameters for the analyze_post_comments handler function.interface AnalyzeCommentsArgs { postUrl: string; maxComments?: number; }
- src/index.ts:777-824 (helper)Key helper function used by the handler to resolve Instagram post URL to a media ID (PK or shortcode), essential for fetching comments via the API.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; } }
- src/index.ts:59-61 (helper)Utility function to validate if a given URL is a valid Instagram post URL format, used in the handler for input validation.const isValidPostUrl = (url: string): boolean => { return /^https:\/\/(www\.)?instagram\.com\/p\/[A-Za-z0-9_-]+\/?/.test(url); };