Skip to main content
Glama
abdulsammad-lgtm

Instagram MCP Server

README.md
# Instagram MCP Server

A production-ready Model Context Protocol (MCP) server for interacting with Instagram/Meta APIs. Enables AI agents to manage content, analyze performance, research competitors, and handle publishing workflows through structured MCP tools.

## Features

- **Account Management**: Profile retrieval, account insights, media listing
- **Content Analytics**: Post, Reel, and Story insights with engagement metrics
- **Content Generation**: Reel ideas, captions, hashtags, content calendars
- **Competitor Research**: Profile analysis, content comparison, competitor reports
- **Comment Management**: Classification, moderation, auto-reply workflows
- **Publishing Workflow**: Container creation, media publishing, status tracking
- **Lead Scoring**: Business lead analysis with scoring tiers
- **Audit Logging**: Full request/response logging with execution metrics

## Prerequisites

- Python 3.10+
- Meta Developer App with Instagram Graph API access
- Instagram Business Account connected to your Meta App

## Quick Start

### 1. Clone and Install

```bash
git clone <repository-url>
cd instagram-mcp
pip install -r requirements.txt
```

### 2. Configure Environment

```bash
cp .env.example .env
```

Edit `.env` with your credentials:

```
META_APP_ID=your_meta_app_id
META_APP_SECRET=your_meta_app_secret
INSTAGRAM_ACCESS_TOKEN=your_instagram_access_token
INSTAGRAM_BUSINESS_ACCOUNT_ID=your_instagram_business_account_id
```

### 3. Run the Server

```bash
python server.py
```

### Docker

```bash
docker-compose up --build
```

## MCP Client Configuration

Add to your MCP client configuration (e.g., Claude Desktop, Cursor):

```json
{
  "mcpServers": {
    "instagram": {
      "command": "python",
      "args": ["server.py"],
      "cwd": "/path/to/instagram-mcp"
    }
  }
}
```

## Available Tools

### Account Tools

| Tool | Description |
|------|-------------|
| `instagram_get_profile` | Get profile information |
| `instagram_get_account_insights` | Get account-level analytics |
| `instagram_get_media` | List media posts |
| `instagram_get_media_details` | Get detailed post info |

### Analytics Tools

| Tool | Description |
|------|-------------|
| `instagram_get_post_insights` | Post performance metrics |
| `instagram_get_reel_insights` | Reel performance metrics |
| `instagram_get_story_insights` | Story performance metrics |
| `instagram_get_top_content` | Top-performing content |
| `instagram_compare_content` | Period-over-period comparison |

### Content Tools

| Tool | Description |
|------|-------------|
| `instagram_analyze_content` | Analyze post structure |
| `instagram_generate_reel_ideas` | Generate Reel concepts |
| `instagram_generate_caption` | Generate captions with hashtags |
| `instagram_generate_hashtags` | Generate relevant hashtags |
| `instagram_generate_content_calendar` | Create multi-day calendars |
| `instagram_find_content_patterns` | Identify content patterns |

### Competitor Tools

| Tool | Description |
|------|-------------|
| `instagram_analyze_competitor` | Analyze competitor profile |
| `instagram_compare_accounts` | Compare multiple accounts |
| `instagram_find_competitor_content` | Find top competitor content |
| `instagram_competitor_report` | Full competitor report |

### Comment Tools

| Tool | Description |
|------|-------------|
| `instagram_get_comments` | Get and classify comments |
| `instagram_reply_comment` | Reply to a comment |
| `instagram_moderate_comments` | Moderate with classification |

### Publishing Tools

| Tool | Description |
|------|-------------|
| `instagram_create_media_container` | Create publish container |
| `instagram_publish_media` | Publish to Instagram |
| `instagram_get_publish_status` | Check publish status |

### Lead Tools

| Tool | Description |
|------|-------------|
| `instagram_analyze_leads` | Score and analyze leads |

## Example Natural Language Commands

```
"What were my best performing Reels last month?"
→ instagram_get_reel_insights (multiple calls) → sort → analyze → top results

"Generate a 30-day content calendar for an AI automation agency"
→ instagram_generate_content_calendar

"Analyze my competitor @examplebrand"
→ instagram_analyze_competitor → instagram_find_competitor_content

"What comments need moderation on my latest post?"
→ instagram_get_comments → classify → filter

"Compare my engagement with @competitor1 and @competitor2"
→ instagram_compare_accounts
```

## AI Decision Layer

The server implements an internal decision pipeline:

1. **User Request** - Natural language input
2. **Intent Detection** - Determine required operation
3. **Permission Check** - Validate API access
4. **Tool Selection** - Map to appropriate MCP tool
5. **Instagram API** - Execute authorized API call
6. **Data Validation** - Validate response data
7. **Analytics/Reasoning** - Process and analyze results
8. **Structured Response** - Return formatted JSON

## Comment Classification

Comments are automatically classified into:

| Category | Description |
|----------|-------------|
| `positive` | Praise, compliments, positive feedback |
| `negative` | Complaints, criticism, negative sentiment |
| `question` | Questions, inquiries |
| `lead` | Purchase intent, business inquiries |
| `spam` | Promotional spam, scam content |
| `support` | Support requests, issue reports |
| `other` | Unclassified comments |

## Lead Scoring

| Score Range | Tier |
|-------------|------|
| 81-100 | Very High |
| 61-80 | High |
| 31-60 | Medium |
| 0-30 | Low |

Scoring factors: follower count, posting frequency, business category, identified needs, website presence.

## Error Handling

All tools return structured error responses:

```json
{
  "success": false,
  "error": {
    "code": "RATE_LIMIT",
    "message": "Instagram API rate limit reached.",
    "retryable": true
  }
}
```

Error codes: `UNAUTHORIZED`, `FORBIDDEN`, `NOT_FOUND`, `RATE_LIMIT`, `SERVER_ERROR`, `NETWORK_ERROR`, `INVALID_MEDIA`, `PERMISSION_MISSING`

## Project Structure

```
instagram-mcp/
├── server.py              # Main MCP server with tool definitions
├── config.py              # Configuration management
├── requirements.txt       # Python dependencies
├── .env.example           # Environment template
├── Dockerfile             # Container configuration
├── docker-compose.yml     # Docker Compose setup
├── mcp/
│   ├── tools/             # MCP tool implementations
│   │   ├── account.py     # Account tools
│   │   ├── analytics.py   # Analytics tools
│   │   ├── content.py     # Content generation tools
│   │   ├── comments.py    # Comment management tools
│   │   ├── publishing.py  # Publishing workflow tools
│   │   └── competitors.py # Competitor research tools
│   └── schemas/           # Pydantic data models
│       ├── account.py
│       ├── content.py
│       └── analytics.py
├── services/              # Business logic layer
│   ├── instagram_api.py   # Instagram Graph API client
│   ├── analytics.py       # Analytics calculations
│   ├── content_ai.py      # Content generation engine
│   └── lead_scoring.py    # Lead analysis and scoring
├── database/              # Data persistence
│   ├── models.py          # SQLAlchemy models
│   └── repository.py      # Database operations
└── tests/                 # Unit tests
    ├── test_account.py
    ├── test_analytics.py
    ├── test_publishing.py
    └── test_errors.py
```

## Running Tests

```bash
pytest tests/ -v
```

## Security

- OAuth 2.0 authentication via Meta Graph API
- Access tokens stored in environment variables
- No credential scraping or session extraction
- Permission validation before operations
- Rate-limit handling with retry logic
- Audit logging for all tool executions
- Never exposes tokens or secrets in responses

## License

MIT