Skip to content

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.

Add generated Meta Ads API implementation

Yves Junqueira12f6ddbfb17b
diff --git a/README.md b/README.md
index baa73b3..bfa5d0c 100644
--- a/README.md
+++ b/README.md
@@ -111,4 +111,40 @@ The assistant will use the provided access token and account ID to fetch the req
- 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 file
+- Using UV is recommended for better dependency management
+
+## Generated Meta Ads API Implementation
+
+This project now includes an alternative implementation (`meta_ads_generated.py`) that provides a more complete interface to the Meta Ads API using Facebook's Graph API. This implementation:
+
+1. Offers more detailed parameters and fields for each endpoint
+2. Provides additional functionality like filtering campaigns by status
+3. Adds support for creating new campaigns
+4. Includes enhanced error handling and debugging
+
+### Additional Tools in Generated Implementation
+
+The generated implementation includes all the tools from the original implementation, plus:
+
+1. `get_ad_accounts` - Get ad accounts accessible by a user
+2. `get_account_info` - Get detailed information about a specific ad account
+3. `get_campaign_details` - Get detailed information about a specific campaign
+4. `get_adset_details` - Get detailed information about a specific ad set
+5. `get_ad_details` - Get detailed information about a specific ad
+6. `create_campaign` - Create a new campaign in a Meta Ads account
+7. `get_insights` - Get performance insights with optional breakdowns
+
+### Using the Generated Implementation
+
+To use the generated implementation with Cursor:
+
+1. The configuration is already included in your Cursor MCP configuration
+2. Run the server using the provided script:
+```bash
+./run_mcp_generated.sh
+```
+
+3. When talking to Claude in Cursor, you can access the new tools with queries like:
+ - "Show me detailed performance insights for my campaign"
+ - "Get all my ad accounts"
+ - "Create a new campaign for my Meta Ads account"
\ No newline at end of file
diff --git a/meta_ads_generated.py b/meta_ads_generated.py
new file mode 100644
index 0000000..65f1538
--- /dev/null
+++ b/meta_ads_generated.py
@@ -0,0 +1,408 @@
+from typing import Any, Dict, List, Optional
+import httpx
+from mcp.server.fastmcp import FastMCP
+
+# Initialize FastMCP server
+mcp_server = FastMCP("meta-ads-generated")
+
+# Constants
+META_GRAPH_API_VERSION = "v20.0"
+META_GRAPH_API_BASE = f"https://graph.facebook.com/{META_GRAPH_API_VERSION}"
+USER_AGENT = "meta-ads-mcp/1.0"
+
+class GraphAPIError(Exception):
+ """Exception raised for errors from the Graph API."""
+ def __init__(self, error_data: Dict[str, Any]):
+ self.error_data = error_data
+ self.message = error_data.get('message', 'Unknown Graph API error')
+ super().__init__(self.message)
+
+async def make_api_request(
+ endpoint: str,
+ access_token: str,
+ params: Optional[Dict[str, Any]] = None,
+ method: str = "GET"
+) -> Dict[str, Any]:
+ """
+ Make a request to the Meta Graph API.
+
+ Args:
+ endpoint: API endpoint path (without base URL)
+ access_token: Meta API access token
+ params: Additional query parameters
+ method: HTTP method (GET, POST, DELETE)
+
+ Returns:
+ API response as a dictionary
+ """
+ url = f"{META_GRAPH_API_BASE}/{endpoint}"
+
+ headers = {
+ "User-Agent": USER_AGENT,
+ }
+
+ request_params = params or {}
+ request_params["access_token"] = access_token
+
+ # Print the request details (masking the token for security)
+ masked_params = {k: "***TOKEN***" if k == "access_token" else v for k, v in request_params.items()}
+ print(f"Making {method} request to: {url}")
+ print(f"Params: {masked_params}")
+
+ async with httpx.AsyncClient() as client:
+ try:
+ if method == "GET":
+ response = await client.get(url, params=request_params, headers=headers, timeout=30.0)
+ elif method == "POST":
+ response = await client.post(url, json=request_params, headers=headers, timeout=30.0)
+ elif method == "DELETE":
+ response = await client.delete(url, params=request_params, headers=headers, timeout=30.0)
+ else:
+ raise ValueError(f"Unsupported HTTP method: {method}")
+
+ response.raise_for_status()
+ return response.json()
+
+ except httpx.HTTPStatusError as e:
+ error_info = {}
+ try:
+ error_info = e.response.json()
+ except:
+ error_info = {"status_code": e.response.status_code, "text": e.response.text}
+
+ print(f"HTTP Error: {e.response.status_code} - {error_info}")
+ return {"error": f"HTTP Error: {e.response.status_code}", "details": error_info}
+
+ except Exception as e:
+ print(f"Request Error: {str(e)}")
+ return {"error": str(e)}
+
+#
+# Ad Account Endpoints
+#
+
+@mcp_server.tool()
+async def get_ad_accounts(access_token: str, user_id: str = "me", limit: int = 10) -> str:
+ """
+ Get ad accounts accessible by a user.
+
+ Args:
+ access_token: Meta API access token
+ user_id: Meta user ID or "me" for the current user
+ limit: Maximum number of accounts to return (default: 10)
+ """
+ endpoint = f"{user_id}/adaccounts"
+ params = {
+ "fields": "id,name,account_id,account_status,amount_spent,balance,currency,age,business_city,business_country_code",
+ "limit": limit
+ }
+
+ data = await make_api_request(endpoint, access_token, params)
+
+ import json
+ return json.dumps(data, indent=2)
+
+@mcp_server.tool()
+async def get_account_info(access_token: str, account_id: str) -> str:
+ """
+ Get detailed information about a specific ad account.
+
+ Args:
+ access_token: Meta API access token
+ account_id: Meta Ads account ID (format: act_XXXXXXXXX)
+ """
+ # Ensure account_id has the 'act_' prefix for API compatibility
+ if not account_id.startswith("act_"):
+ account_id = f"act_{account_id}"
+
+ endpoint = f"{account_id}"
+ params = {
+ "fields": "id,name,account_id,account_status,amount_spent,balance,currency,age,funding_source_details,business_city,business_country_code,timezone_name,owner"
+ }
+
+ data = await make_api_request(endpoint, access_token, params)
+
+ import json
+ return json.dumps(data, indent=2)
+
+#
+# Campaign Endpoints
+#
+
+@mcp_server.tool()
+async def get_campaigns(access_token: str, account_id: str, limit: int = 10, status_filter: str = "") -> str:
+ """
+ Get campaigns for a Meta Ads account with optional filtering.
+
+ 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)
+ status_filter: Filter by status (empty for all, or 'ACTIVE', 'PAUSED', etc.)
+ """
+ endpoint = f"{account_id}/campaigns"
+ params = {
+ "fields": "id,name,objective,status,daily_budget,lifetime_budget,buying_type,start_time,stop_time,created_time,updated_time,bid_strategy",
+ "limit": limit
+ }
+
+ if status_filter:
+ params["effective_status"] = [status_filter]
+
+ data = await make_api_request(endpoint, access_token, params)
+
+ import json
+ return json.dumps(data, indent=2)
+
+@mcp_server.tool()
+async def get_campaign_details(access_token: str, campaign_id: str) -> str:
+ """
+ Get detailed information about a specific campaign.
+
+ Args:
+ access_token: Meta API access token
+ campaign_id: Meta Ads campaign ID
+ """
+ endpoint = f"{campaign_id}"
+ params = {
+ "fields": "id,name,objective,status,daily_budget,lifetime_budget,buying_type,start_time,stop_time,created_time,updated_time,bid_strategy,special_ad_categories,special_ad_category_country,budget_remaining,configured_status"
+ }
+
+ data = await make_api_request(endpoint, access_token, params)
+
+ import json
+ return json.dumps(data, indent=2)
+
+@mcp_server.tool()
+async def create_campaign(
+ access_token: str,
+ account_id: str,
+ name: str,
+ objective: str,
+ status: str = "PAUSED",
+ special_ad_categories: List[str] = None,
+ daily_budget: Optional[int] = None,
+ lifetime_budget: Optional[int] = None
+) -> str:
+ """
+ Create a new campaign in a Meta Ads account.
+
+ Args:
+ access_token: Meta API access token
+ account_id: Meta Ads account ID (format: act_XXXXXXXXX)
+ name: Campaign name
+ objective: Campaign objective (AWARENESS, TRAFFIC, ENGAGEMENT, etc.)
+ status: Initial campaign status (default: PAUSED)
+ special_ad_categories: List of special ad categories if applicable
+ daily_budget: Daily budget in account currency (in cents)
+ lifetime_budget: Lifetime budget in account currency (in cents)
+ """
+ endpoint = f"{account_id}/campaigns"
+
+ params = {
+ "name": name,
+ "objective": objective,
+ "status": status,
+ }
+
+ if special_ad_categories:
+ params["special_ad_categories"] = special_ad_categories
+
+ if daily_budget:
+ params["daily_budget"] = daily_budget
+
+ if lifetime_budget:
+ params["lifetime_budget"] = lifetime_budget
+
+ data = await make_api_request(endpoint, access_token, params, method="POST")
+
+ import json
+ return json.dumps(data, indent=2)
+
+#
+# Ad Set Endpoints
+#
+
+@mcp_server.tool()
+async def get_adsets(access_token: str, account_id: str, limit: int = 10, campaign_id: str = "") -> str:
+ """
+ Get ad sets for a Meta Ads account with optional filtering by campaign.
+
+ 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)
+ campaign_id: Optional campaign ID to filter by
+ """
+ endpoint = f"{account_id}/adsets"
+ params = {
+ "fields": "id,name,campaign_id,status,daily_budget,lifetime_budget,targeting,bid_amount,bid_strategy,optimization_goal,billing_event,start_time,end_time,created_time,updated_time",
+ "limit": limit
+ }
+
+ if campaign_id:
+ params["campaign_id"] = campaign_id
+
+ data = await make_api_request(endpoint, access_token, params)
+
+ import json
+ return json.dumps(data, indent=2)
+
+@mcp_server.tool()
+async def get_adset_details(access_token: str, adset_id: str) -> str:
+ """
+ Get detailed information about a specific ad set.
+
+ Args:
+ access_token: Meta API access token
+ adset_id: Meta Ads ad set ID
+ """
+ endpoint = f"{adset_id}"
+ params = {
+ "fields": "id,name,campaign_id,status,daily_budget,lifetime_budget,targeting,bid_amount,bid_strategy,optimization_goal,billing_event,start_time,end_time,created_time,updated_time,attribution_spec,destination_type,promoted_object,pacing_type,budget_remaining"
+ }
+
+ data = await make_api_request(endpoint, access_token, params)
+
+ import json
+ return json.dumps(data, indent=2)
+
+#
+# Ad Endpoints
+#
+
+@mcp_server.tool()
+async def get_ads(
+ access_token: str,
+ account_id: str,
+ limit: int = 10,
+ campaign_id: str = "",
+ adset_id: str = ""
+) -> str:
+ """
+ Get ads for a Meta Ads account with optional filtering.
+
+ 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)
+ campaign_id: Optional campaign ID to filter by
+ adset_id: Optional ad set ID to filter by
+ """
+ endpoint = f"{account_id}/ads"
+ params = {
+ "fields": "id,name,adset_id,campaign_id,status,creative,created_time,updated_time,bid_amount,conversion_domain,tracking_specs",
+ "limit": limit
+ }
+
+ if campaign_id:
+ params["campaign_id"] = campaign_id
+
+ if adset_id:
+ params["adset_id"] = adset_id
+
+ data = await make_api_request(endpoint, access_token, params)
+
+ import json
+ return json.dumps(data, indent=2)
+
+@mcp_server.tool()
+async def get_ad_details(access_token: str, ad_id: str) -> str:
+ """
+ Get detailed information about a specific ad.
+
+ Args:
+ access_token: Meta API access token
+ ad_id: Meta Ads ad ID
+ """
+ endpoint = f"{ad_id}"
+ params = {
+ "fields": "id,name,adset_id,campaign_id,status,creative,created_time,updated_time,bid_amount,conversion_domain,tracking_specs,preview_shareable_link"
+ }
+
+ data = await make_api_request(endpoint, access_token, params)
+
+ import json
+ return json.dumps(data, indent=2)
+
+@mcp_server.tool()
+async def get_ad_creatives(access_token: str, ad_id: str) -> str:
+ """
+ Get creative details for a specific ad.
+
+ Args:
+ access_token: Meta API access token
+ ad_id: Meta Ads ad ID
+ """
+ # First, get the creative ID from the ad
+ endpoint = f"{ad_id}"
+ params = {
+ "fields": "creative"
+ }
+
+ ad_data = await make_api_request(endpoint, access_token, params)
+
+ if "error" in ad_data:
+ import json
+ return json.dumps(ad_data, indent=2)
+
+ if "creative" not in ad_data:
+ import json
+ return json.dumps({"error": "No creative found for this ad"}, indent=2)
+
+ creative_id = ad_data.get("creative", {}).get("id")
+ if not creative_id:
+ import json
+ return json.dumps({"error": "Creative ID not found", "ad_data": ad_data}, indent=2)
+
+ # Now get the creative details
+ creative_endpoint = f"{creative_id}"
+ creative_params = {
+ "fields": "id,name,title,body,image_url,object_story_spec,url_tags,link_url,thumbnail_url,video_id,call_to_action_type,asset_feed_spec,object_type"
+ }
+
+ creative_data = await make_api_request(creative_endpoint, access_token, creative_params)
+
+ import json
+ return json.dumps(creative_data, indent=2)
+
+#
+# Insights Endpoints
+#
+
+@mcp_server.tool()
+async def get_insights(
+ access_token: str,
+ object_id: str,
+ time_range: str = "last_30_days",
+ breakdown: str = "",
+ level: str = "ad"
+) -> str:
+ """
+ Get performance insights for a campaign, ad set, ad or account.
+
+ Args:
+ access_token: Meta API access token
+ object_id: ID of the campaign, ad set, ad or account
+ time_range: Time range for insights (default: last_30_days, options: today, yesterday, last_7_days, last_30_days)
+ breakdown: Optional breakdown dimension (e.g., age, gender, country)
+ level: Level of aggregation (ad, adset, campaign, account)
+ """
+ endpoint = f"{object_id}/insights"
+ params = {
+ "date_preset": time_range,
+ "fields": "account_id,account_name,campaign_id,campaign_name,adset_id,adset_name,ad_id,ad_name,impressions,clicks,spend,cpc,cpm,ctr,reach,frequency,actions,conversions,unique_clicks,cost_per_action_type",
+ "level": level
+ }
+
+ if breakdown:
+ params["breakdowns"] = breakdown
+
+ data = await make_api_request(endpoint, access_token, params)
+
+ import json
+ return json.dumps(data, indent=2)
+
+if __name__ == "__main__":
+ # Initialize and run the server
+ mcp_server.run(transport='stdio')
\ No newline at end of file