Skip to main content
Glama
README.md
# Facebook Ads Automation

An MCP server for Claude Code that gives you full read/write access to the Meta Marketing API. Manage campaigns, analyze performance, generate AI creatives, and get optimization recommendations — all through natural language.

**77 MCP tools** | **7 AI agents** | **PDF reports** | **AI creative generation** | **Multi-account support**

Built on [FastMCP](https://github.com/jlowin/fastmcp) + [Facebook Marketing API v24.0](https://developers.facebook.com/docs/marketing-apis/).

## How It Works

```
YOU (natural language in Claude Code)
  |
  v
SLASH COMMANDS      /fb-ads:daily-check, /fb-ads:weekly-report, /fb-ads:optimize, ...
  |
  v
AGENTS (7)          Report, Market Analyst, Creative Strategist, Creative Generator,
                    Performance Optimizer, Competitive Intel, Ads Optimizer
  |
  v
KNOWLEDGE           Per-client context: business goals, brand voice, audience, competitors
  |
  v
MCP SERVER (77)     Facebook API tools + Analytics engine + AI creative generation
```

## What You Can Do

- **Manage campaigns** — Create, read, update, pause/activate campaigns, ad sets, ads, and creatives
- **Analyze performance** — Get insights, run analytics, detect creative fatigue, check audience saturation
- **Generate creatives** — AI image/video generation via Freepik (14 image + 24 video models), Gemini (Imagen 3 + Veo), and OpenAI (DALL-E 3 + Sora)
- **Edit images** — Upscale, remove backgrounds, reimagine, recolor, inpaint, and more (9 editing operations)
- **Optimize** — Get data-driven recommendations based on your KPIs, thresholds, and business rules
- **Generate reports** — KPMG-style PDF reports with charts, KPIs, and recommendations
- **Research competitors** — Search the Facebook Ad Library and analyze competitor strategies
- **Manage multiple accounts** — Switch between ad accounts with labeled aliases

## Quick Start

### 1. Install

```bash
git clone https://github.com/your-username/fb-ads-automation.git
cd fb-ads-automation

python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
```

### 2. Configure

```bash
cp .env.example .env
cp .mcp.json.example .mcp.json
```

Edit `.env` with your Facebook credentials (see [Setup Guide](docs/setup.md) for step-by-step instructions on getting each credential):

```bash
FB_APP_ID=your_app_id
FB_APP_SECRET=your_app_secret
FB_ACCESS_TOKEN=your_access_token
FB_AD_ACCOUNT_ID=act_your_account_id
```

Edit `.mcp.json` with absolute paths to your Python and server:

```json
{
  "mcpServers": {
    "fb-ads": {
      "command": "/absolute/path/to/.venv/bin/python3",
      "args": ["/absolute/path/to/fb_ads_mcp_server/server.py"]
    }
  }
}
```

### 3. Verify

Open Claude Code in the project directory:

```
check_token_status
```

If you see your token info, you're ready.

### 4. Onboard Your First Client

```
/fb-ads:onboard-client
```

This interactive wizard validates your account, interviews you about your business, and creates the knowledge files that agents use.

## Tool Groups

Only 8 core tools load at startup. Load more on demand:

```
enable_tools(groups="crud,insights")   # Campaign management + reporting
enable_tools(groups="creative_gen")    # AI image/video generation
enable_tools(groups="all")             # Everything (77 tools)
```

| Group         | Tools | What It Does                                        |
| ------------- | ----- | --------------------------------------------------- |
| **core**      | 8     | Account management, token tools, tool loading       |
| crud          | 21    | Create/read/update campaigns, ad sets, ads, creatives |
| insights      | 5     | Performance data and breakdowns                     |
| analytics     | 7     | Trends, fatigue detection, saturation analysis      |
| targeting     | 3     | Interest search, audience estimation, suggestions   |
| pages         | 5     | Facebook Page management and insights               |
| instagram     | 4     | Instagram account and media management              |
| ad_library    | 2     | Competitor ad research                              |
| creative_gen  | 7     | AI image and video generation                       |
| image_editing | 9     | Upscale, remove BG, reimagine, recolor, inpaint     |
| stock         | 3     | Search Freepik image/icon/video libraries           |
| audio         | 3     | AI music, sound effects, vocal isolation            |

Full tool reference: [docs/mcp-tools.md](docs/mcp-tools.md)

## Agents

Seven specialized agents live in `agents/`. Activate by saying "Load [agent name]":

| Agent                  | What It Does                                                  |
| ---------------------- | ------------------------------------------------------------- |
| Report Agent           | Generates KPMG-style PDF reports with charts and KPIs         |
| Market Analyst         | Audience research, demographic analysis, expansion planning   |
| Creative Strategist    | Ad copy, messaging angles, A/B test design                    |
| Creative Generator     | AI image/video generation with brand-aware prompts            |
| Performance Optimizer  | Data-driven optimization recommendations                     |
| Competitive Intel      | Ad Library research, competitor strategy analysis             |
| Ads Optimizer          | Campaign-level optimization (deprecated, kept for reference)  |

Agents auto-read your knowledge files for business context, brand voice, audience data, and competitive landscape.

## Slash Commands

| Command                     | What It Does                                 |
| --------------------------- | -------------------------------------------- |
| `/fb-ads:onboard-client`    | Set up a new client (interactive wizard)     |
| `/fb-ads:daily-check`       | Morning health check on your ad account      |
| `/fb-ads:weekly-report`     | Weekly performance summary                   |
| `/fb-ads:optimize`          | Analyze and get optimization recommendations |
| `/fb-ads:new-campaign`      | Interactive campaign creation wizard         |
| `/fb-ads:creative-refresh`  | Check for creative fatigue + guide refresh   |
| `/fb-ads:generate-creative` | Generate AI images/videos for ads            |
| `/fb-ads:competitor-check`  | Research competitor ads via Ad Library        |

## Knowledge System

Agents use per-client knowledge files to understand your business:

```
knowledge/
  playbook.md              # Global optimization thresholds
  accounts.md              # Account registry
  report-specs.md          # PDF report configuration
  clients/
    _templates/            # Blank templates to copy
    _example/              # Filled example (fictional cafe)
    your-client/           # Your client's knowledge files
      business-context.md  # Company, product, KPIs, strategy
      brand-voice.md       # Tone, messaging, visual direction
      audience-research.md # Segments, demographics, saturation
      competitive-landscape.md  # Competitors, benchmarks, gaps
```

## Important Notes

**Budgets** use the smallest currency unit. USD uses cents ($50/day = `daily_budget: 5000`). INR uses paisa (Rs 1,000/day = `daily_budget: 100000`).

**Campaign objectives** must be OUTCOME-based: `OUTCOME_TRAFFIC`, `OUTCOME_ENGAGEMENT`, `OUTCOME_LEADS`, `OUTCOME_AWARENESS`, `OUTCOME_SALES`, `OUTCOME_APP_PROMOTION`.

**Rate limits** are ~200 API calls/hour/user. Analytics tools make multiple calls per invocation.

**Tokens** expire after ~60 days. Use `check_token_status` and `refresh_access_token` to manage them.

## Optional: AI Creative Generation

The core ads management works without these. Add API keys for creative generation:

| Provider     | Models                          | Key Required      |
| ------------ | ------------------------------- | ----------------- |
| Freepik      | 14 image + 24 video + editing   | `FREEPIK_API_KEY` |
| Google Gemini| Imagen 3 + Veo                  | `GEMINI_API_KEY`  |
| OpenAI       | DALL-E 3 + Sora                 | `OPENAI_API_KEY`  |

See [docs/freepik.md](docs/freepik.md) for model selection guides.

## Documentation

| Doc | Contents |
| --- | -------- |
| [Setup Guide](docs/setup.md) | Step-by-step installation and credential setup |
| [MCP Tools Reference](docs/mcp-tools.md) | All 77 tools by group with descriptions |
| [Agents & Clients](docs/agents-and-clients.md) | Agent system, onboarding, code structure |
| [Freepik Guide](docs/freepik.md) | AI models, editing operations, parameters |
| [Dashboard](docs/dashboard.md) | Client dashboard architecture and deployment |

## Project Structure

```
fb_ads_mcp_server/         # MCP server
  server.py                # Entry point (FastMCP)
  api/                     # Pure Facebook SDK wrappers (no MCP coupling)
  tools/                   # MCP tool registration (thin orchestrators)
  analytics/               # Pure computation functions
  rules/                   # Business rule engine
  providers/               # AI provider abstraction (Gemini, OpenAI, Freepik)
agents/                    # 7 agent instruction files
knowledge/                 # Global + per-client knowledge files
reports/                   # PDF report generator + charts
dashboard/                 # Static client dashboard (Netlify-ready)
docs/                      # Documentation
tests/                     # Test suite
```

## Contributing

See [CONTRIBUTING.md](CONTRIBUTING.md) for development setup, testing, and PR guidelines.

## License

MIT - see [LICENSE](LICENSE).