facebook-ads-library-mcp-server

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Facebook Ads Library MCP Server

Facebook Ads Library MCP Server

Skill by ara.so — Marketing Skills collection
This MCP (Model Context Protocol) server enables AI agents to query Facebook's public Ads Library API, retrieve advertising data for brands, and perform AI-powered analysis of ad creative including images and videos. It supports batch processing for efficient multi-brand queries and includes intelligent caching and credit management.
ara.so开发的Skill — 营销技能合集
这款MCP(Model Context Protocol)服务器允许AI Agent查询Facebook公开的Ads Library API,获取品牌的广告数据,并对包含图片和视频的广告创意进行AI驱动的分析。它支持批量处理,可高效完成多品牌查询,还具备智能缓存和额度管理功能。

What It Does

功能介绍

  • Brand Search: Convert brand names to Meta platform IDs
  • Ad Retrieval: Fetch currently running ads for one or multiple brands
  • Image Analysis: Analyze ad images for visual elements, text, colors, and composition
  • Video Analysis: Deep analysis of video ads using Gemini AI (pacing, storytelling, messaging)
  • Batch Processing: Query multiple brands or platform IDs simultaneously with ~88% token savings
  • Smart Caching: Reduces API calls and improves performance
  • Credit Management: Automatic detection of API credit exhaustion
  • 品牌搜索:将品牌名称转换为Meta平台ID
  • 广告获取:获取一个或多个品牌当前投放的广告
  • 图像分析:分析广告图片的视觉元素、文本、色彩和构图
  • 视频分析:借助Gemini AI深度分析视频广告(节奏、叙事、信息传递)
  • 批量处理:同时查询多个品牌或平台ID,可节省约88%的token
  • 智能缓存:减少API调用次数,提升性能
  • 额度管理:自动检测API额度耗尽情况

Installation

安装步骤

Quick Install

快速安装

bash
git clone https://github.com/proxy-intell/facebook-ads-library-mcp.git
cd facebook-ads-library-mcp
bash
git clone https://github.com/proxy-intell/facebook-ads-library-mcp.git
cd facebook-ads-library-mcp

Run installer

Run installer

./install.sh # macOS/Linux
./install.sh # macOS/Linux

OR

OR

install.bat # Windows
undefined
install.bat # Windows
undefined

Manual Setup

手动配置

bash
undefined
bash
undefined

Clone repository

Clone repository

Create virtual environment

Create virtual environment

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

Configure environment

Configure environment

cp .env.template .env
cp .env.template .env

Edit .env and add:

Edit .env and add:

SCRAPECREATORS_API_KEY=your_key_here

SCRAPECREATORS_API_KEY=your_key_here

GEMINI_API_KEY=your_gemini_key_here (optional, for video analysis)

GEMINI_API_KEY=your_gemini_key_here (optional, for video analysis)

undefined
undefined

MCP Configuration

MCP配置

Claude Desktop (
~/Library/Application Support/Claude/claude_desktop_config.json
):
json
{
  "mcpServers": {
    "fb_ad_library": {
      "command": "/full/path/to/facebook-ads-library-mcp/venv/bin/python",
      "args": [
        "/full/path/to/facebook-ads-library-mcp/mcp_server.py"
      ]
    }
  }
}
Cursor (
~/.cursor/mcp.json
):
json
{
  "mcpServers": {
    "fb_ad_library": {
      "command": "/full/path/to/facebook-ads-library-mcp/venv/bin/python",
      "args": [
        "/full/path/to/facebook-ads-library-mcp/mcp_server.py"
      ]
    }
  }
}
Replace
/full/path/to/
with your actual project path.
Claude Desktop
~/Library/Application Support/Claude/claude_desktop_config.json
):
json
{
  "mcpServers": {
    "fb_ad_library": {
      "command": "/full/path/to/facebook-ads-library-mcp/venv/bin/python",
      "args": [
        "/full/path/to/facebook-ads-library-mcp/mcp_server.py"
      ]
    }
  }
}
Cursor
~/.cursor/mcp.json
):
json
{
  "mcpServers": {
    "fb_ad_library": {
      "command": "/full/path/to/facebook-ads-library-mcp/venv/bin/python",
      "args": [
        "/full/path/to/facebook-ads-library-mcp/mcp_server.py"
      ]
    }
  }
}
/full/path/to/
替换为你的实际项目路径。

API Keys Required

所需API密钥

  1. ScrapeCreators API (required): Sign up at scrapecreators.com
  2. Google Gemini API (optional, for video analysis): Get key at Google AI Studio
Store keys in
.env
file:
bash
SCRAPECREATORS_API_KEY=your_scrapecreators_key
GEMINI_API_KEY=your_gemini_key
  1. ScrapeCreators API(必填):在scrapecreators.com注册获取
  2. Google Gemini API(可选,用于视频分析):在Google AI Studio获取密钥
将密钥存储在
.env
文件中:
bash
SCRAPECREATORS_API_KEY=your_scrapecreators_key
GEMINI_API_KEY=your_gemini_key

Available MCP Tools

可用MCP工具

1. get_meta_platform_id

1. get_meta_platform_id

Converts brand name(s) to Meta platform ID(s).
Input: Single brand name (string) or multiple brands (array)
python
undefined
将品牌名称转换为Meta平台ID。
输入:单个品牌名称(字符串)或多个品牌(数组)
python
undefined

Single brand

单个品牌

{ "brand_name": "Nike" }
{ "brand_name": "Nike" }

Multiple brands (batch)

多个品牌(批量)

{ "brand_name": ["Nike", "Adidas", "Under Armour"] }

**Output**:
```json
{
  "Nike": "123456789",
  "Adidas": "987654321",
  "Under Armour": "456789123"
}
{ "brand_name": ["Nike", "Adidas", "Under Armour"] }

**输出**:
```json
{
  "Nike": "123456789",
  "Adidas": "987654321",
  "Under Armour": "456789123"
}

2. get_meta_ads

2. get_meta_ads

Retrieves currently running ads for platform ID(s).
Input: Single platform ID (string) or multiple IDs (array)
python
undefined
获取平台ID对应的当前投放广告。
输入:单个平台ID(字符串)或多个ID(数组)
python
undefined

Single platform

单个平台

{ "platform_id": "123456789" }
{ "platform_id": "123456789" }

Multiple platforms (batch)

多个平台(批量)

{ "platform_id": ["123456789", "987654321"] }

**Output**:
```json
{
  "123456789": {
    "ads": [
      {
        "id": "ad_id_123",
        "ad_creative_body": "Ad text content",
        "ad_snapshot_url": "https://...",
        "images": ["https://image1.jpg"],
        "videos": ["https://video1.mp4"]
      }
    ]
  }
}
{ "platform_id": ["123456789", "987654321"] }

**输出**:
```json
{
  "123456789": {
    "ads": [
      {
        "id": "ad_id_123",
        "ad_creative_body": "Ad text content",
        "ad_snapshot_url": "https://...",
        "images": ["https://image1.jpg"],
        "videos": ["https://video1.mp4"]
      }
    ]
  }
}

3. analyze_ad_image

3. analyze_ad_image

Analyzes visual elements in ad images.
Input:
python
{
  "image_url": "https://example.com/ad-image.jpg"
}
Output: Detailed analysis of colors, composition, text, people, emotions, and visual elements.
分析广告图片中的视觉元素。
输入
python
{
  "image_url": "https://example.com/ad-image.jpg"
}
输出:关于色彩、构图、文本、人物、情绪及视觉元素的详细分析。

4. analyze_ad_video

4. analyze_ad_video

Analyzes a single video ad using Gemini AI.
Input:
python
{
  "video_url": "https://example.com/ad-video.mp4"
}
Output: Comprehensive analysis including pacing, storytelling, brand messaging, visual techniques, and strategic insights.
借助Gemini AI分析单个视频广告。
输入
python
{
  "video_url": "https://example.com/ad-video.mp4"
}
输出:包含节奏、叙事、品牌信息传递、视觉技巧及战略洞察的全面分析。

5. analyze_ad_videos_batch

5. analyze_ad_videos_batch

Analyzes multiple videos in a single API call (~88% token savings).
Input:
python
{
  "video_urls": [
    "https://example.com/video1.mp4",
    "https://example.com/video2.mp4",
    "https://example.com/video3.mp4"
  ]
}
Output: Array of analyses, one per video, with comparative insights.
单次API调用分析多个视频(可节省约88%的token)。
输入
python
{
  "video_urls": [
    "https://example.com/video1.mp4",
    "https://example.com/video2.mp4",
    "https://example.com/video3.mp4"
  ]
}
输出:每个视频对应的分析结果数组,包含对比洞察。

6. get_cache_stats

6. get_cache_stats

Returns statistics about cached media.
Output:
json
{
  "total_cached_items": 42,
  "images": 30,
  "videos": 12,
  "total_size_mb": 156.7,
  "oldest_cache": "2025-01-15T10:30:00Z"
}
返回缓存媒体的统计信息。
输出
json
{
  "total_cached_items": 42,
  "images": 30,
  "videos": 12,
  "total_size_mb": 156.7,
  "oldest_cache": "2025-01-15T10:30:00Z"
}

7. search_cached_media

7. search_cached_media

Searches previously analyzed media.
Input:
python
{
  "brand": "Nike",          # Optional
  "colors": ["red", "blue"], # Optional
  "has_people": true,       # Optional
  "media_type": "image"     # Optional: "image" or "video"
}
搜索已分析过的媒体内容。
输入
python
{
  "brand": "Nike",          # 可选
  "colors": ["red", "blue"], # 可选
  "has_people": true,       # 可选
  "media_type": "image"     # 可选:"image" 或 "video"
}

8. cleanup_media_cache

8. cleanup_media_cache

Removes old cached media files.
Input:
python
{
  "days_old": 30  # Remove cache older than 30 days
}
删除旧的缓存媒体文件。
输入
python
{
  "days_old": 30  # 删除30天前的缓存
}

Common Usage Patterns

常见使用场景

Single Brand Analysis

单品牌分析

python
undefined
python
undefined

Agent workflow:

Agent工作流:

1. Get platform ID

1. 获取平台ID

platform_id_result = get_meta_platform_id({"brand_name": "Nike"}) platform_id = platform_id_result["Nike"]
platform_id_result = get_meta_platform_id({"brand_name": "Nike"}) platform_id = platform_id_result["Nike"]

2. Get ads

2. 获取广告

ads_result = get_meta_ads({"platform_id": platform_id}) ads = ads_result[platform_id]["ads"]
ads_result = get_meta_ads({"platform_id": platform_id}) ads = ads_result[platform_id]["ads"]

3. Analyze first video ad

3. 分析第一个视频广告

video_url = ads[0]["videos"][0] video_analysis = analyze_ad_video({"video_url": video_url})
undefined
video_url = ads[0]["videos"][0] video_analysis = analyze_ad_video({"video_url": video_url})
undefined

Multi-Brand Competitive Analysis

多品牌竞品分析

python
undefined
python
undefined

Agent workflow for batch processing:

批量处理的Agent工作流:

brands = ["Nike", "Adidas", "Under Armour", "Puma"]
brands = ["Nike", "Adidas", "Under Armour", "Puma"]

1. Get all platform IDs at once (batch)

1. 批量获取所有平台ID

platform_ids = get_meta_platform_id({"brand_name": brands})
platform_ids = get_meta_platform_id({"brand_name": brands})

2. Get all ads at once (batch)

2. 批量获取所有广告

all_platform_ids = list(platform_ids.values()) ads_data = get_meta_ads({"platform_id": all_platform_ids})
all_platform_ids = list(platform_ids.values()) ads_data = get_meta_ads({"platform_id": all_platform_ids})

3. Collect video URLs

3. 收集视频URL

video_urls = [] for platform_id, data in ads_data.items(): for ad in data["ads"]: if ad.get("videos"): video_urls.extend(ad["videos"][:2]) # First 2 videos per brand
video_urls = [] for platform_id, data in ads_data.items(): for ad in data["ads"]: if ad.get("videos"): video_urls.extend(ad["videos"][:2]) # 每个品牌取前2个视频

4. Batch analyze all videos (huge token savings)

4. 批量分析所有视频(大幅节省token)

video_analyses = analyze_ad_videos_batch({"video_urls": video_urls})
undefined
video_analyses = analyze_ad_videos_batch({"video_urls": video_urls})
undefined

Filtering and Search

筛选与搜索

python
undefined
python
undefined

Find all Nike ads with people in red/white colors

查找所有包含人物且主色调为红/白的Nike广告

cached_results = search_cached_media({ "brand": "Nike", "colors": ["red", "white"], "has_people": True, "media_type": "image" })
cached_results = search_cached_media({ "brand": "Nike", "colors": ["red", "white"], "has_people": True, "media_type": "image" })

Get fresh data and analyze

获取最新数据并分析

for result in cached_results: print(f"Ad ID: {result['ad_id']}") print(f"Analysis: {result['analysis']}")
undefined
for result in cached_results: print(f"广告ID: {result['ad_id']}") print(f"分析结果: {result['analysis']}")
undefined

Code Examples

代码示例

Example 1: Basic Brand Ad Check

示例1:基础品牌广告查询

python
import json
from mcp import get_meta_platform_id, get_meta_ads
python
import json
from mcp import get_meta_platform_id, get_meta_ads

Get Nike's platform ID

获取Nike的平台ID

platform_data = get_meta_platform_id({"brand_name": "Nike"}) nike_id = platform_data["Nike"]
platform_data = get_meta_platform_id({"brand_name": "Nike"}) nike_id = platform_data["Nike"]

Get their current ads

获取他们当前的广告

ads = get_meta_ads({"platform_id": nike_id}) nike_ads = ads[nike_id]["ads"]
print(f"Nike is running {len(nike_ads)} ads") for ad in nike_ads: print(f"- {ad['ad_creative_body'][:100]}...")
undefined
ads = get_meta_ads({"platform_id": nike_id}) nike_ads = ads[nike_id]["ads"]
print(f"Nike当前投放{len(nike_ads)}条广告") for ad in nike_ads: print(f"- {ad['ad_creative_body'][:100]}...")
undefined

Example 2: Competitor Video Strategy Comparison

示例2:竞品视频策略对比

python
from mcp import get_meta_platform_id, get_meta_ads, analyze_ad_videos_batch
python
from mcp import get_meta_platform_id, get_meta_ads, analyze_ad_videos_batch

Define competitors

定义竞品品牌

brands = ["Coca-Cola", "Pepsi", "Dr Pepper"]
brands = ["Coca-Cola", "Pepsi", "Dr Pepper"]

Get platform IDs (batch)

批量获取平台ID

platform_ids = get_meta_platform_id({"brand_name": brands})
platform_ids = get_meta_platform_id({"brand_name": brands})

Get all ads (batch)

批量获取所有广告

all_ids = list(platform_ids.values()) all_ads = get_meta_ads({"platform_id": all_ids})
all_ids = list(platform_ids.values()) all_ads = get_meta_ads({"platform_id": all_ids})

Collect video URLs

收集视频URL

video_map = {} # Maps video URL to brand for brand, pid in platform_ids.items(): for ad in all_ads[pid]["ads"]: if ad.get("videos"): for video_url in ad["videos"][:1]: # First video only video_map[video_url] = brand
video_map = {} # 映射视频URL到品牌 for brand, pid in platform_ids.items(): for ad in all_ads[pid]["ads"]: if ad.get("videos"): for video_url in ad["videos"][:1]: # 仅取第一个视频 video_map[video_url] = brand

Batch analyze

批量分析

video_urls = list(video_map.keys()) analyses = analyze_ad_videos_batch({"video_urls": video_urls})
video_urls = list(video_map.keys()) analyses = analyze_ad_videos_batch({"video_urls": video_urls})

Map results back to brands

将结果映射回品牌

brand_strategies = {} for i, video_url in enumerate(video_urls): brand = video_map[video_url] if brand not in brand_strategies: brand_strategies[brand] = [] brand_strategies[brand].append(analyses[i])
brand_strategies = {} for i, video_url in enumerate(video_urls): brand = video_map[video_url] if brand not in brand_strategies: brand_strategies[brand] = [] brand_strategies[brand].append(analyses[i])

Print comparison

打印对比结果

for brand, strategies in brand_strategies.items(): print(f"\n{brand} Video Strategy:") print(json.dumps(strategies[0], indent=2))
undefined
for brand, strategies in brand_strategies.items(): print(f"\n{brand}视频策略:") print(json.dumps(strategies[0], indent=2))
undefined

Example 3: Image Analysis with Filtering

示例3:带筛选的图像分析

python
from mcp import get_meta_ads, analyze_ad_image
python
from mcp import get_meta_ads, analyze_ad_image

Get ads for a platform

获取某平台的广告

ads = get_meta_ads({"platform_id": "123456789"})
ads = get_meta_ads({"platform_id": "123456789"})

Analyze images

分析图片

for ad in ads["123456789"]["ads"]: if ad.get("images"): image_url = ad["images"][0] analysis = analyze_ad_image({"image_url": image_url})
    # Check if red color is dominant
    colors = analysis.get("dominant_colors", [])
    if any("red" in c.lower() for c in colors):
        print(f"Red-dominant ad found: {ad['id']}")
        print(f"Colors: {colors}")
        print(f"Has people: {analysis.get('has_people', False)}")
undefined
for ad in ads["123456789"]["ads"]: if ad.get("images"): image_url = ad["images"][0] analysis = analyze_ad_image({"image_url": image_url})
    # 检查是否以红色为主色调
    colors = analysis.get("dominant_colors", [])
    if any("red" in c.lower() for c in colors):
        print(f"发现红色主色调广告: {ad['id']}")
        print(f"色彩: {colors}")
        print(f"包含人物: {analysis.get('has_people', False)}")
undefined

Environment Variables

环境变量

All configuration is stored in
.env
:
bash
undefined
所有配置存储在
.env
文件中:
bash
undefined

Required for ad retrieval

广告获取必填

SCRAPECREATORS_API_KEY=your_api_key_here
SCRAPECREATORS_API_KEY=your_api_key_here

Optional for video analysis

视频分析可选

GEMINI_API_KEY=your_gemini_api_key_here
GEMINI_API_KEY=your_gemini_api_key_here

Optional cache settings (defaults shown)

可选缓存设置(默认值如下)

CACHE_DIR=./cache MAX_CACHE_SIZE_MB=1000 CACHE_EXPIRY_DAYS=30
undefined
CACHE_DIR=./cache MAX_CACHE_SIZE_MB=1000 CACHE_EXPIRY_DAYS=30
undefined

Troubleshooting

故障排查

API Credits Exhausted

API额度耗尽

Error: "ScrapeCreators API credits exhausted"
Solution: Top up credits at ScrapeCreators Dashboard. The server will automatically resume once credits are available.
错误信息:"ScrapeCreators API credits exhausted"
解决方案:在ScrapeCreators控制台充值额度。额度恢复后服务器将自动继续运行。

Rate Limit Exceeded

超出速率限制

Error: Rate limit messages with wait time
Solution:
  • Space out large batch requests
  • Use batch operations to reduce total API calls
  • Wait the specified time before retrying
错误信息:包含等待时间的速率限制提示
解决方案
  • 拆分大型批量请求,分散执行
  • 使用批量操作减少总API调用次数
  • 等待指定时间后重试

Video Analysis Not Working

视频分析无法工作

Problem: Video analysis returns errors or empty results
Check:
  1. Ensure
    GEMINI_API_KEY
    is set in
    .env
  2. Verify Gemini API key is valid at Google AI Studio
  3. Check video URL is accessible
  4. Ensure video file size is under Gemini's limits
问题:视频分析返回错误或空结果
检查项
  1. 确保
    .env
    文件中已设置
    GEMINI_API_KEY
  2. Google AI Studio验证Gemini API密钥有效性
  3. 检查视频URL是否可访问
  4. 确保视频文件大小在Gemini的限制范围内

MCP Server Connection Issues

MCP服务器连接问题

Problem: Agent can't connect to MCP server
Check:
  1. Verify virtual environment is activated and dependencies installed
  2. Check MCP config file points to correct Python path (
    venv/bin/python
    )
  3. Ensure
    .env
    file exists with API keys
  4. Restart Claude Desktop or Cursor after config changes
  5. Check logs in Claude Desktop:
    ~/Library/Logs/Claude/
问题:Agent无法连接到MCP服务器
检查项
  1. 验证虚拟环境已激活且依赖包已安装
  2. 检查MCP配置文件指向正确的Python路径(
    venv/bin/python
  3. 确保
    .env
    文件存在且包含API密钥
  4. 修改配置后重启Claude Desktop或Cursor
  5. 查看Claude Desktop日志:
    ~/Library/Logs/Claude/

Import Errors

导入错误

Error:
ModuleNotFoundError
or import failures
Solution:
bash
cd facebook-ads-library-mcp
./venv/bin/pip install -r requirements.txt --upgrade
错误信息
ModuleNotFoundError
或导入失败
解决方案
bash
cd facebook-ads-library-mcp
./venv/bin/pip install -r requirements.txt --upgrade

Cache Issues

缓存问题

Problem: Stale or incorrect cached data
Solution:
python
undefined
问题:缓存数据过期或不正确
解决方案
python
undefined

Clean old cache (older than 7 days)

清理旧缓存(7天前的内容)

cleanup_media_cache({"days_old": 7})
cleanup_media_cache({"days_old": 7})

Or manually remove cache directory

或手动删除缓存目录

rm -rf ./cache
undefined
rm -rf ./cache
undefined

Performance Tips

性能优化建议

  1. Use Batch Operations: Always prefer batch API calls when analyzing multiple brands
  2. Leverage Cache: Check
    search_cached_media
    before making new API requests
  3. Video Batch Analysis: Use
    analyze_ad_videos_batch
    instead of multiple single calls (88% token savings)
  4. Limit Results: When querying ads, process only what you need (e.g., first 5 ads per brand)
  5. Monitor Credits: Check ScrapeCreators dashboard regularly to avoid interruptions
  1. 使用批量操作:分析多个品牌时优先选择批量API调用
  2. 利用缓存:发起新API请求前先调用
    search_cached_media
    检查缓存
  3. 视频批量分析:使用
    analyze_ad_videos_batch
    替代多次单个调用(节省88%token)
  4. 限制结果数量:查询广告时仅处理所需内容(例如每个品牌取前5条广告)
  5. 监控额度:定期查看ScrapeCreators控制台,避免因额度耗尽中断服务

Integration Examples

集成示例

With LangChain

与LangChain集成

python
from langchain.tools import Tool
from mcp import get_meta_platform_id, get_meta_ads

tools = [
    Tool(
        name="get_facebook_ads",
        func=lambda brand: get_meta_ads({
            "platform_id": get_meta_platform_id({"brand_name": brand})[brand]
        }),
        description="Get current Facebook ads for a brand"
    )
]
python
from langchain.tools import Tool
from mcp import get_meta_platform_id, get_meta_ads

tools = [
    Tool(
        name="get_facebook_ads",
        func=lambda brand: get_meta_ads({
            "platform_id": get_meta_platform_id({"brand_name": brand})[brand]
        }),
        description="Get current Facebook ads for a brand"
    )
]

With Custom Python Scripts

与自定义Python脚本集成

python
#!/usr/bin/env python3
import sys
import json
from pathlib import Path
python
#!/usr/bin/env python3
import sys
import json
from pathlib import Path

Add MCP server to path

Add MCP server to path

sys.path.insert(0, str(Path(file).parent / "facebook-ads-library-mcp"))
from mcp_server import get_meta_platform_id, get_meta_ads
def main(): brand = input("Enter brand name: ") platform_id = get_meta_platform_id({"brand_name": brand})[brand] ads = get_meta_ads({"platform_id": platform_id}) print(json.dumps(ads, indent=2))
if name == "main": main()
undefined
sys.path.insert(0, str(Path(file).parent / "facebook-ads-library-mcp"))
from mcp_server import get_meta_platform_id, get_meta_ads
def main(): brand = input("输入品牌名称: ") platform_id = get_meta_platform_id({"brand_name": brand})[brand] ads = get_meta_ads({"platform_id": platform_id}) print(json.dumps(ads, indent=2))
if name == "main": main()
undefined