Skip to main content
Glama
duhlink

Instagram MCP Server

by duhlink

get_instagram_posts

Fetch recent Instagram posts from a profile using Chrome login. Specify username, limit (1-3 posts or all), and starting index for pagination.

Instructions

Get recent posts from an Instagram profile using existing Chrome login

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
limitNoNumber of posts to fetch (1-3) or "all" for continuous batches
startFromNoIndex to start fetching from (for pagination)
usernameYesInstagram username to fetch posts from

Implementation Reference

  • Core handler implementing the get_instagram_posts tool: uses Playwright for stealthy scraping of Instagram posts with caching, progress updates, and anti-detection behaviors.
    public async fetchPosts(
      username: string,
      limit?: number | 'all',
      startFrom: number = 0,
      onProgress?: ProgressCallback
    ): Promise<IInstagramPost[]> {
      if (!onProgress) throw new Error('Progress callback required');
      this.startHeartbeat(onProgress);
    
      try {
        this.currentProgress = 0;
        this.totalProgress = 5;
    
        const context = await this.initContext();
        const page = await context.newPage();
    
        try {
          this.sendProgress('Loading...', onProgress, true);
          
          // Human-like navigation to profile
          await this.humanNavigate(page, `https://www.instagram.com/${username}/`);
          
          const postLinks = await this.getCachedOrFetchLinks(page, startFrom + BATCH_SIZE);
          if (!postLinks.length) throw new InstagramError('No posts found');
    
          const fetchedPosts = await this.postSaver.loadFetchedPosts();
          const endIndex = limit === 'all' ? 
            Math.min(startFrom + BATCH_SIZE, postLinks.length) : 
            Math.min(startFrom + (limit || BATCH_SIZE), postLinks.length);
          
          const targetLinks = postLinks.slice(startFrom, endIndex);
          this.totalProgress = this.currentProgress + targetLinks.length;
          
          const posts: IInstagramPost[] = [];
          for (const postUrl of targetLinks) {
            try {
              // Human-like navigation to post
              await this.humanNavigate(page, postUrl);
    
              const postData = await this.extractPostData(page);
              if (!postData) continue;
    
              const post = await this.postProcessor.processPost(
                postData,
                this.config.instagram.defaultSaveDir,
                username
              );
    
              await this.postSaver.savePost(post, this.config.instagram.defaultSaveDir);
              fetchedPosts.set(postUrl, new Date().toISOString());
              await this.postSaver.saveFetchedPosts(fetchedPosts);
    
              posts.push(post);
              await this.randomDelay(2000, 5000); // Random delay between posts
            } catch (error) {
              log('Post error: %s', error instanceof Error ? error.message : String(error));
              continue;
            }
          }
    
          const hasMore = endIndex < postLinks.length;
          this.sendProgress(
            hasMore ? 'More available' : 'Complete',
            onProgress,
            hasMore
          );
          
          return posts;
        } finally {
          await page.close();
        }
      } catch (error) {
        log('Fatal error: %s', error instanceof Error ? error.message : String(error));
        throw error;
      } finally {
        this.stopHeartbeat();
      }
    }
  • src/server.ts:50-75 (registration)
    Registers the 'get_instagram_posts' tool with MCP server including name, description, and input schema.
    this.server.setRequestHandler(ListToolsRequestSchema, async () => ({
      tools: [
        {
          name: 'get_instagram_posts',
          description: 'Get recent posts from an Instagram profile using existing Chrome login',
          inputSchema: {
            type: 'object',
            properties: {
              username: {
                type: 'string',
                description: 'Instagram username to fetch posts from'
              },
              limit: {
                type: ['number', 'string'],
                description: 'Number of posts to fetch (1-3) or "all" for continuous batches'
              },
              startFrom: {
                type: 'number',
                description: 'Index to start fetching from (for pagination)'
              }
            },
            required: ['username']
          }
        }
      ]
    }));
  • MCP CallTool request handler: validates arguments, calls InstagramService.fetchPosts, handles progress notifications and response formatting.
    this.server.setRequestHandler(CallToolRequestSchema, async (request) => {
      if (request.params.name !== 'get_instagram_posts') {
        throw new McpError(
          ErrorCode.MethodNotFound,
          `Unknown tool: ${request.params.name}`
        );
      }
    
      const args = request.params.arguments;
      if (!this.isValidFetchArgs(args)) {
        throw new McpError(
          ErrorCode.InvalidParams,
          'Invalid fetch arguments'
        );
      }
    
      try {
        const posts = await this.instagramService.fetchPosts(
          args.username,
          args.limit,
          args.startFrom,
          ((message: string | IProgressUpdate) => {
            if (typeof message === 'string') {
              this.server.notification({
                method: 'progress',
                params: {
                  message,
                  progress: 0,
                  total: 0
                }
              });
            } else {
              this.server.notification({
                method: 'progress',
                params: {
                  message: message.message,
                  progress: message.progress,
                  total: message.total,
                  keepAlive: message.keepAlive
                }
              });
            }
          }) as ProgressCallback
        );
    
        return {
          content: [
            {
              type: 'json',
              json: {
                posts,
                pagination: {
                  currentBatch: {
                    start: args.startFrom || 0,
                    end: (args.startFrom || 0) + posts.length,
                    size: posts.length
                  },
                  nextStartFrom: (args.startFrom || 0) + posts.length,
                  hasMore: posts.length === 3
                }
              }
            }
          ]
        };
      } catch (error) {
        return {
          content: [
            {
              type: 'text',
              text: `Instagram error: ${error instanceof Error ? error.message : String(error)}`
            }
          ],
          isError: true
        };
      }
    });
  • TypeScript interface defining input arguments for get_instagram_posts tool.
    export interface IGetInstagramPostsArgs {
      username: string;
      limit?: number | 'all';
      saveDir?: string;
      delayBetweenPosts?: number;
    }
  • Configuration settings specific to the get_instagram_posts tool including paths, delays, and batch sizes.
        get_instagram_posts: {
          defaultSaveDir,
          postsLogFile: path.join(defaultSaveDir, 'fetched_posts.json'),
          defaultDelay: 5000,  // Increased to 5 seconds between posts
          maxPostsPerBatch: 25, // Reduced batch size
          batchBreakDelay: 60000, // Increased to 1 minute break between batches
          minDelay: 3000,  // Increased minimum delay
          chromeUserDataDir: env.CHROME_USER_DATA_DIR,
        },
      },
    },
Behavior2/5

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

With no annotations, the description carries full burden but only mentions 'using existing Chrome login' as a behavioral trait, hinting at authentication needs. It fails to disclose critical behaviors like rate limits, pagination mechanics (implied by 'startFrom' but not explained), error handling, or what 'recent' means temporally, leaving significant gaps.

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 core action and key constraint ('using existing Chrome login'). It's front-loaded with the main purpose, though it could be slightly more structured by separating functional from implementation details.

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 no annotations and no output schema, the description is incomplete for a tool with 3 parameters and behavioral complexity. It lacks details on return values (e.g., post format, errors), authentication specifics, or operational limits, making it inadequate for full agent understanding.

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?

Schema description coverage is 100%, so the schema fully documents parameters like 'limit' and 'startFrom'. The description adds no additional meaning beyond what's in the schema, such as clarifying 'recent' in relation to parameters or usage context, meeting the baseline for high 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 ('Get recent posts') and target resource ('from an Instagram profile'), making the purpose understandable. However, it doesn't differentiate from siblings (none exist), and the phrase 'using existing Chrome login' adds implementation detail rather than clarifying the core purpose, slightly reducing specificity.

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, prerequisites, or constraints beyond the implied need for Chrome login. With no siblings, differentiation isn't needed, but it lacks context like when to fetch posts (e.g., for monitoring, analysis) or any exclusions, leaving usage unclear.

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

Related 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/duhlink/instagram-server-next-mcp'

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