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
Add frequency control specifications and update adset function
Yves Junqueirad3c56055fadd
diff --git a/meta_ads_mcp/core/adsets.py b/meta_ads_mcp/core/adsets.pyindex e755a55..e61622f 100644--- a/meta_ads_mcp/core/adsets.py+++ b/meta_ads_mcp/core/adsets.py@@ -5,6 +5,8 @@ from typing import Optional, Dict, Any, Listfrom .api import meta_api_tool, make_api_requestfrom .accounts import get_ad_accountsfrom .server import mcp_server+import asyncio+from .auth import start_callback_server, update_confirmation@mcp_server.tool()@@ -74,46 +76,78 @@ async def get_adset_details(access_token: str = None, adset_id: str = None) -> s@mcp_server.tool()@meta_api_tool-async def update_adset(access_token: str = None, adset_id: str = None,- bid_strategy: Optional[str] = None,- bid_amount: Optional[int] = None,- frequency_control_specs: Optional[List[Dict[str, Any]]] = None,- status: Optional[str] = None) -> str:+async def update_adset(args: str = "", kwargs: str = None, access_token: str = None) -> str:"""Update an existing ad set with new settings including frequency caps.Args:+ args: Meta Ads ad set ID+ kwargs: JSON string containing update parameters:+ - bid_strategy: Bid strategy (e.g., 'LOWEST_COST_WITH_BID_CAP')+ - bid_amount: Bid amount in account currency (in cents for USD)+ - frequency_control_specs: List of frequency control specifications+ - status: Update ad set status (ACTIVE, PAUSED, etc.)access_token: Meta API access token (optional - will use cached token if not provided)- adset_id: Meta Ads ad set ID- bid_strategy: Bid strategy (e.g., 'LOWEST_COST_WITH_BID_CAP')- bid_amount: Bid amount in your account's currency (in cents for USD)- frequency_control_specs: List of frequency control specifications. Each spec should have:- - event: Type of event (e.g., 'IMPRESSIONS')- - interval_days: Number of days for the frequency cap- - max_frequency: Maximum number of times to show the ad- status: Update ad set status (ACTIVE, PAUSED, etc.)"""+ # Extract adset_id from args+ adset_id = args+if not adset_id:return json.dumps({"error": "No ad set ID provided"}, indent=2)- endpoint = f"{adset_id}"- params = {}-- if bid_strategy:- params["bid_strategy"] = bid_strategy-- if bid_amount is not None:- params["bid_amount"] = bid_amount-- if frequency_control_specs:- params["frequency_control_specs"] = frequency_control_specs-- if status:- params["status"] = status-- if not params:+ # Try to read parameters from file if not provided+ if not kwargs:+ try:+ with open('frequency_cap.json', 'r') as f:+ kwargs = f.read().strip()+ except (FileNotFoundError, IOError):+ # If file doesn't exist, use default empty object+ kwargs = "{}"++ # Extract optional parameters+ try:+ if isinstance(kwargs, (dict, list)):+ kwargs_dict = kwargs+ else:+ kwargs_dict = json.loads(kwargs) if kwargs else {}+ except (json.JSONDecodeError, TypeError) as e:+ return json.dumps({"error": f"Invalid kwargs format: {str(e)}, received: {kwargs}"}, indent=2)+ except Exception as e:+ return json.dumps({"error": f"Error parsing kwargs: {str(e)}, received: {kwargs}"}, indent=2)++ # Build the changes dictionary directly from kwargs_dict+ changes = {}+ for key in ['bid_strategy', 'bid_amount', 'frequency_control_specs', 'status']:+ if key in kwargs_dict and kwargs_dict[key] is not None:+ changes[key] = kwargs_dict[key]++ if not changes:return json.dumps({"error": "No update parameters provided"}, indent=2)- data = await make_api_request(endpoint, access_token, params, method="POST")+ # Get current ad set details for comparison+ current_details = await get_adset_details(args=adset_id, kwargs="", access_token=access_token)+ current_details = json.loads(current_details)++ # Start the callback server if not already running+ port = start_callback_server()++ # Generate confirmation URL with properly encoded parameters+ changes_json = json.dumps(changes)+ confirmation_url = f"http://localhost:{port}/confirm-update?adset_id={adset_id}&token={access_token}&changes={changes_json}"++ # Reset the update confirmation+ update_confirmation.clear()+ update_confirmation.update({"approved": False})++ # Return the confirmation link+ response = {+ "message": "Please confirm the ad set update",+ "confirmation_url": confirmation_url,+ "markdown_link": f"[Click here to confirm ad set update]({confirmation_url})",+ "current_details": current_details,+ "proposed_changes": changes,+ "instructions_for_llm": "You must present this link as clickable Markdown to the user using the markdown_link format provided.",+ "note": "A confirmation page will open in your browser. Please review and confirm the changes."+ }- return json.dumps(data, indent=2)\ No newline at end of file+ return json.dumps(response, indent=2)\ No newline at end of filediff --git a/meta_ads_mcp/core/auth.py b/meta_ads_mcp/core/auth.pyindex 839dff1..fce13ee 100644--- a/meta_ads_mcp/core/auth.py+++ b/meta_ads_mcp/core/auth.py@@ -18,6 +18,12 @@ AUTH_SCOPE = "ads_management,ads_read,business_management"AUTH_REDIRECT_URI = "http://localhost:8888/callback"AUTH_RESPONSE_TYPE = "token"+# Global token container for communication between threads+token_container = {"token": None, "expires_in": None, "user_id": None}++# Global container for update confirmations+update_confirmation = {"approved": False}+# Global flag for authentication stateneeds_authentication = False@@ -27,9 +33,6 @@ callback_server_lock = threading.Lock()callback_server_running = Falsecallback_server_port = None-# Global token container for communication between threads-token_container = {"token": None, "expires_in": None, "user_id": None}-class TokenInfo:"""Stores token information including expiration"""def __init__(self, access_token: str, expires_in: int = None, user_id: str = None):@@ -240,6 +243,137 @@ class CallbackHandler(BaseHTTPRequestHandler):self.wfile.write(html.encode())return+ if self.path.startswith("/confirm-update"):+ # Parse query parameters+ query = parse_qs(urlparse(self.path).query)+ adset_id = query.get("adset_id", [""])[0]+ token = query.get("token", [""])[0]+ changes = query.get("changes", ["{}"])[0]++ try:+ changes_dict = json.loads(changes)+ except json.JSONDecodeError:+ changes_dict = {}++ # Return confirmation page+ self.send_response(200)+ self.send_header("Content-type", "text/html")+ self.end_headers()++ html = """+ <html>+ <head>+ <title>Confirm Ad Set Update</title>+ <style>+ body { font-family: Arial, sans-serif; margin: 20px; }+ .warning { color: #d73a49; margin: 20px 0; }+ .changes { background: #f6f8fa; padding: 15px; border-radius: 6px; }+ .buttons { margin-top: 20px; }+ button { padding: 10px 20px; margin-right: 10px; border-radius: 6px; cursor: pointer; }+ .approve { background: #2ea44f; color: white; border: none; }+ .cancel { background: #d73a49; color: white; border: none; }+ .diff-table { width: 100%; border-collapse: collapse; margin: 15px 0; }+ .diff-table td { padding: 8px; border: 1px solid #ddd; }+ .diff-table .header { background: #f1f8ff; font-weight: bold; }+ </style>+ </head>+ <body>+ <h1>Confirm Ad Set Update</h1>+ <p>You are about to update Ad Set: <strong>""" + adset_id + """</strong></p>++ <div class="warning">+ <strong>⚠️ Warning:</strong> These changes will be applied immediately upon approval.+ """ + ("<br><strong>🔴 Important:</strong> This update includes status changes that may affect billing." if "status" in changes_dict else "") + """+ </div>++ <h2>Proposed Changes:</h2>+ <div class="changes">+ <table class="diff-table">+ <tr class="header">+ <td>Setting</td>+ <td>New Value</td>+ </tr>+ """ + "\n".join(f"""+ <tr>+ <td>{k}</td>+ <td>{v}</td>+ </tr>+ """ for k, v in changes_dict.items()) + """+ </table>+ </div>++ <div class="buttons">+ <button class="approve" onclick="approveChanges()">Approve Changes</button>+ <button class="cancel" onclick="cancelChanges()">Cancel</button>+ </div>++ <script>+ function approveChanges() {+ fetch('/update-confirm?' + new URLSearchParams({+ adset_id: '""" + adset_id + """',+ token: '""" + token + """',+ changes: '""" + changes + """',+ action: 'approve'+ }))+ .then(response => response.json())+ .then(data => {+ alert('Changes approved and applied successfully!');+ window.close();+ })+ .catch(error => {+ alert('Error applying changes: ' + error);+ });+ }++ function cancelChanges() {+ fetch('/update-confirm?' + new URLSearchParams({+ adset_id: '""" + adset_id + """',+ action: 'cancel'+ }))+ .then(() => {+ alert('Update cancelled.');+ window.close();+ });+ }+ </script>+ </body>+ </html>+ """+ self.wfile.write(html.encode())+ return++ if self.path.startswith("/update-confirm"):+ # Handle update confirmation response+ query = parse_qs(urlparse(self.path).query)+ action = query.get("action", [""])[0]++ self.send_response(200)+ self.send_header("Content-type", "application/json")+ self.end_headers()++ if action == "approve":+ adset_id = query.get("adset_id", [""])[0]+ token = query.get("token", [""])[0]+ changes = query.get("changes", ["{}"])[0]++ # Store the approval in a global variable for the main thread to process+ global update_confirmation+ update_confirmation = {+ "approved": True,+ "adset_id": adset_id,+ "token": token,+ "changes": changes+ }++ self.wfile.write(json.dumps({"status": "approved"}).encode())+ else:+ # Store the cancellation+ update_confirmation = {+ "approved": False+ }+ self.wfile.write(json.dumps({"status": "cancelled"}).encode())+ return+if self.path.startswith("/token"):# Extract token from query paramsquery = parse_qs(urlparse(self.path).query)