Meta Ads (Facebook/Instagram) MCP server for Claude, ChatGPT, Perplexity & Cursor — the Meta node of Pipeboard’s 5-platform family (+ Google, TikTok, Snap, Reddit). Hosted remote MCP, badged Meta Business Partner, free plan — no self-hosting required.
Python advertisingai-agentschatgptclaudefacebook-adsinstagram-adsmcpmeta-adsmodel-context-protocolpipeboard
Initial commit of Meta Ads MCP server
Yves Junqueiraa5ced480bed3
diff --git a/.gitignore b/.gitignorenew file mode 100644index 0000000..505a3b1--- /dev/null+++ b/.gitignore@@ -0,0 +1,10 @@+# Python-generated files+__pycache__/+*.py[oc]+build/+dist/+wheels/+*.egg-info++# Virtual environments+.venvdiff --git a/.python-version b/.python-versionnew file mode 100644index 0000000..2c07333--- /dev/null+++ b/.python-version@@ -0,0 +1 @@+3.11diff --git a/README.md b/README.mdnew file mode 100644index 0000000..baa73b3--- /dev/null+++ b/README.md@@ -0,0 +1,114 @@+# Meta Ads MCP Server++A Model Context Protocol (MCP) server that provides tools for querying the Meta Ads API.++## Setup++1. Install dependencies:+```bash+# Using pip+pip install mcp>=1.2.0 httpx>=0.26.0++# Or using Poetry+poetry add mcp httpx++# Or using uv (recommended)+uv pip install mcp>=1.2.0 httpx>=0.26.0+```++2. Run the server:+```bash+# Direct execution (for development only)+python meta_ads.py++# Using uv (recommended)+uv run python meta_ads.py+```++Note: The server uses stdio transport, so it won't output anything when run directly. It's meant to be used with an MCP client like Claude for Desktop or Cursor.++## Tools++This MCP server provides the following tools:++1. `get_ads` - Retrieves ads from a Meta Ads account+2. `get_campaigns` - Retrieves campaigns from a Meta Ads account+3. `get_adsets` - Retrieves ad sets from a Meta Ads account++## Configuration with Claude for Desktop++To use this MCP server with Claude for Desktop, add the following to your Claude configuration file:++1. Open your Claude for Desktop configuration:+ - macOS: `~/Library/Application Support/Claude/claude_desktop_config.json`+ - Windows: `%AppData%\Claude\claude_desktop_config.json`++2. Add the server configuration:+```json+{+ "mcpServers": {+ "meta-ads": {+ "command": "uv",+ "args": [+ "--directory",+ "/ABSOLUTE/PATH/TO/PARENT/FOLDER",+ "run",+ "python",+ "meta_ads.py"+ ]+ }+ }+}+```++3. Replace `/ABSOLUTE/PATH/TO/PARENT/FOLDER` with the absolute path to the directory containing your `meta_ads.py` file. For example: `/Users/username/projects/meta-ads-mcp`++4. Restart Claude for Desktop.++## Configuration with Cursor++To use this MCP server with Cursor:++1. Edit the Cursor MCP configuration file:+ - macOS: `~/.cursor/mcp.json`+ - Windows: `%AppData%\Cursor\User\mcp.json`++2. Add the server configuration:+```json+{+ "mcpServers": {+ "meta-ads": {+ "command": "uv",+ "args": [+ "--directory",+ "/ABSOLUTE/PATH/TO/PARENT/FOLDER",+ "run",+ "python",+ "meta_ads.py"+ ],+ "description": "Meta Ads API MCP server",+ "autoconnect": true+ }+ }+}+```++3. Replace `/ABSOLUTE/PATH/TO/PARENT/FOLDER` with the absolute path to the directory containing your `meta_ads.py` file.++4. Restart Cursor or reconnect to the MCP server.++## Usage with Claude or Cursor++You can now ask about your Meta Ads account. Example prompts:+- "Show me the ads in my Meta Ads account with ID act_123456789"+- "What campaigns do I have running in my Meta Ads account?"+- "List the ad sets for my Meta account"++The assistant will use the provided access token and account ID to fetch the requested information.++## Important Notes++- You need a valid Meta Ads API access token to use these tools+- Your account ID should be in the format `act_XXXXXXXXX`+- The server will fetch a maximum of 10 items by default (configurable with the `limit` parameter)+- Using UV is recommended for better dependency management\ No newline at end of filediff --git a/meta_ads.py b/meta_ads.pynew file mode 100644index 0000000..0b4901e--- /dev/null+++ b/meta_ads.py@@ -0,0 +1,156 @@+from typing import Any+import httpx+from mcp.server.fastmcp import FastMCP++# Initialize FastMCP server+# = FastMCP("meta-ads")+# dont use mcp name because it conflicts with the mcp module+mcp_server = FastMCP("meta-ads")++# Constants+META_ADS_API_BASE = "https://graph.facebook.com/v20.0"+USER_AGENT = "meta-ads-mcp/1.0"++async def make_meta_request(url: str, access_token: str) -> dict[str, Any] | None:+ """Make a request to the Meta Ads API with proper error handling."""+ headers = {+ "User-Agent": USER_AGENT,+ }+ params = {+ "access_token": access_token+ }+ async with httpx.AsyncClient() as client:+ try:+ response = await client.get(url, headers=headers, params=params, timeout=30.0)+ response.raise_for_status()+ return response.json()+ except Exception as e:+ return {"error": str(e)}++def format_ad(ad: dict) -> str:+ """Format an ad into a readable string."""+ return f"""+Ad ID: {ad.get('id', 'Unknown')}+Name: {ad.get('name', 'Unknown')}+Status: {ad.get('status', 'Unknown')}+Created Time: {ad.get('created_time', 'Unknown')}+"""++def format_campaign(campaign: dict) -> str:+ """Format a campaign into a readable string."""+ return f"""+Campaign ID: {campaign.get('id', 'Unknown')}+Name: {campaign.get('name', 'Unknown')}+Status: {campaign.get('status', 'Unknown')}+Objective: {campaign.get('objective', 'Unknown')}+"""++def format_adset(adset: dict) -> str:+ """Format an adset into a readable string."""+ return f"""+AdSet ID: {adset.get('id', 'Unknown')}+Name: {adset.get('name', 'Unknown')}+Status: {adset.get('status', 'Unknown')}+Daily Budget: {adset.get('daily_budget', 'Unknown')}+"""++@mcp_server.tool()+async def get_ads(access_token: str, account_id: str, limit: int = 10) -> str:+ """Get ads for a Meta Ads account.++ Args:+ access_token: Meta API access token+ account_id: Meta Ads account ID (format: act_XXXXXXXXX)+ limit: Maximum number of ads to return (default: 10)+ """+ url = f"{META_ADS_API_BASE}/{account_id}/ads"+ params = {+ "limit": limit,+ "fields": "id,name,status,created_time"+ }++ # Add parameters to the URL+ param_str = "&".join(f"{k}={v}" for k, v in params.items())+ full_url = f"{url}?{param_str}"++ data = await make_meta_request(full_url, access_token)++ if not data or "data" not in data:+ if "error" in data:+ return f"Error fetching ads: {data['error']}"+ return "Unable to fetch ads or no ads found."++ if not data["data"]:+ return "No ads found for this account."++ ads = [format_ad(ad) for ad in data["data"]]+ return "\n---\n".join(ads)++@mcp_server.tool()+async def get_campaigns(access_token: str, account_id: str, limit: int = 10) -> str:+ """Get campaigns for a Meta Ads account.++ Args:+ access_token: Meta API access token+ account_id: Meta Ads account ID (format: act_XXXXXXXXX)+ limit: Maximum number of campaigns to return (default: 10)+ """+ url = f"{META_ADS_API_BASE}/{account_id}/campaigns"+ params = {+ "limit": limit,+ "fields": "id,name,status,objective"+ }++ # Add parameters to the URL+ param_str = "&".join(f"{k}={v}" for k, v in params.items())+ full_url = f"{url}?{param_str}"++ data = await make_meta_request(full_url, access_token)++ if not data or "data" not in data:+ if "error" in data:+ return f"Error fetching campaigns: {data['error']}"+ return "Unable to fetch campaigns or no campaigns found."++ if not data["data"]:+ return "No campaigns found for this account."++ campaigns = [format_campaign(campaign) for campaign in data["data"]]+ return "\n---\n".join(campaigns)++@mcp_server.tool()+async def get_adsets(access_token: str, account_id: str, limit: int = 10) -> str:+ """Get ad sets for a Meta Ads account.++ Args:+ access_token: Meta API access token+ account_id: Meta Ads account ID (format: act_XXXXXXXXX)+ limit: Maximum number of ad sets to return (default: 10)+ """+ url = f"{META_ADS_API_BASE}/{account_id}/adsets"+ params = {+ "limit": limit,+ "fields": "id,name,status,daily_budget"+ }++ # Add parameters to the URL+ param_str = "&".join(f"{k}={v}" for k, v in params.items())+ full_url = f"{url}?{param_str}"++ data = await make_meta_request(full_url, access_token)++ if not data or "data" not in data:+ if "error" in data:+ return f"Error fetching ad sets: {data['error']}"+ return "Unable to fetch ad sets or no ad sets found."++ if not data["data"]:+ return "No ad sets found for this account."++ adsets = [format_adset(adset) for adset in data["data"]]+ return "\n---\n".join(adsets)++if __name__ == "__main__":+ # Initialize and run the server+ mcp_server.run(transport='stdio')+diff --git a/pyproject.toml b/pyproject.tomlnew file mode 100644index 0000000..0b07c62--- /dev/null+++ b/pyproject.toml@@ -0,0 +1,11 @@+[project]+name = "meta-ads-mcp"+version = "0.1.0"+description = "Add your description here"+readme = "README.md"+requires-python = ">=3.11"+dependencies = [+ "mcp[cli]>=1.6.0",+ "python-dotenv>=1.1.0",+ "requests>=2.32.3",+]diff --git a/requirements.txt b/requirements.txtnew file mode 100644index 0000000..6fc2df0--- /dev/null+++ b/requirements.txt@@ -0,0 +1,4 @@+mcp>=1.2.0+httpx>=0.26.0+anyio>=4.0.0+pydantic>=2.0.0