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.

Refactor debug_image_download function and enhance ad set update logic

Yves Junqueira9372066e6fcd
diff --git a/meta_ads_mcp/api.py b/meta_ads_mcp/api.py
index bb0055f..2487a34 100644
--- a/meta_ads_mcp/api.py
+++ b/meta_ads_mcp/api.py
@@ -1190,37 +1190,26 @@ async def get_insights(
@mcp_server.tool()
@meta_api_tool
-async def debug_image_download(access_token: str = None, url: str = "", ad_id: str = "") -> str:
- """
- Debug image download issues and report detailed diagnostics.
+async def debug_image_download(url="", ad_id="", access_token=None):
+ """Debug image download issues and report detailed diagnostics."""
+ results = {}
- Args:
- access_token: Meta API access token (optional - will use cached token if not provided)
- url: Direct image URL to test (optional)
- ad_id: Meta Ads ad ID (optional, used if url is not provided)
- """
- results = {
- "diagnostics": {
- "timestamp": str(datetime.datetime.now()),
- "methods_tried": [],
- "request_details": [],
- "network_info": {}
- }
- }
-
- # If no URL provided but ad_id is, get URL from ad creative
- if not url and ad_id:
- print(f"Getting image URL from ad creative for ad {ad_id}")
- # Get the creative details
- creative_json = await get_ad_creatives(access_token=access_token, ad_id=ad_id)
- creative_data = json.loads(creative_json)
- results["creative_data"] = creative_data
-
- # Look for image URL in the creative
- if "full_image_url" in creative_data:
- url = creative_data.get("full_image_url")
- elif "thumbnail_url" in creative_data:
- url = creative_data.get("thumbnail_url")
+ if url:
+ results["image_url"] = url
+ else:
+ # If no URL provided but ad_id is, get URL from ad creative
+ if ad_id:
+ print(f"Getting image URL from ad creative for ad {ad_id}")
+ # Get the creative details
+ creative_json = await get_ad_creatives(access_token=access_token, ad_id=ad_id)
+ creative_data = json.loads(creative_json)
+ results["creative_data"] = creative_data
+
+ # Look for image URL in the creative
+ if "full_image_url" in creative_data:
+ url = creative_data.get("full_image_url")
+ elif "thumbnail_url" in creative_data:
+ url = creative_data.get("thumbnail_url")
if not url:
return json.dumps({
@@ -1229,29 +1218,13 @@ async def debug_image_download(access_token: str = None, url: str = "", ad_id: s
}, indent=2)
results["image_url"] = url
- print(f"Debug: Testing image URL: {url}")
-
- # Try to get network information to help debug
- try:
- import socket
- hostname = urlparse(url).netloc
- ip_address = socket.gethostbyname(hostname)
- results["diagnostics"]["network_info"] = {
- "hostname": hostname,
- "ip_address": ip_address,
- "is_facebook_cdn": "fbcdn" in hostname
- }
- except Exception as e:
- results["diagnostics"]["network_info"] = {
- "error": str(e)
- }
# Method 1: Basic download
method_result = {
"method": "Basic download with standard headers",
"success": False
}
- results["diagnostics"]["methods_tried"].append(method_result)
+ results["diagnostics"] = {"methods_tried": [method_result]}
try:
headers = {
diff --git a/meta_ads_mcp/core/adsets.py b/meta_ads_mcp/core/adsets.py
index 5241afc..1fa37cb 100644
--- a/meta_ads_mcp/core/adsets.py
+++ b/meta_ads_mcp/core/adsets.py
@@ -93,26 +93,23 @@ async def update_adset(adset_id: str, frequency_control_specs: List[Dict[str, An
if not adset_id:
return json.dumps({"error": "No ad set ID provided"}, indent=2)
- # Debug print
- print(f"DEBUG: update_adset called with adset_id: {adset_id}")
- print(f"DEBUG: frequency_control_specs: {frequency_control_specs}")
-
- # Build the changes dictionary directly from parameters
changes = {}
+
+ if frequency_control_specs is not None:
+ changes['frequency_control_specs'] = frequency_control_specs
+
if bid_strategy is not None:
changes['bid_strategy'] = bid_strategy
+
if bid_amount is not None:
changes['bid_amount'] = bid_amount
- if frequency_control_specs is not None:
- changes['frequency_control_specs'] = frequency_control_specs
+
if status is not None:
changes['status'] = status
if not changes:
return json.dumps({"error": "No update parameters provided"}, indent=2)
- print(f"DEBUG: Final changes to apply: {changes}")
-
# Get current ad set details for comparison
current_details_json = await get_adset_details(adset_id=adset_id, access_token=access_token)
current_details = json.loads(current_details_json)
diff --git a/meta_ads_mcp/core/api.py b/meta_ads_mcp/core/api.py
index 261e5b8..a573d1d 100644
--- a/meta_ads_mcp/core/api.py
+++ b/meta_ads_mcp/core/api.py
@@ -101,126 +101,25 @@ async def make_api_request(
# Generic wrapper for all Meta API tools
def meta_api_tool(func):
- """Decorator to handle authentication for all Meta API tools"""
+ """Decorator for Meta API tools that handles authentication and error handling."""
@functools.wraps(func)
async def wrapper(*args, **kwargs):
- # Handle various MCP invocation patterns
- if len(args) == 1 and isinstance(args[0], str):
- # If it's a string and looks like JSON, try to parse it
- try:
- parsed = json.loads(args[0]) if args[0] else {}
- if isinstance(parsed, dict):
- # If it has an 'args' key, use that for positional args
- if 'args' in parsed:
- args = (parsed['args'],)
- # If it has a 'kwargs' key, update kwargs
- if 'kwargs' in parsed:
- if isinstance(parsed['kwargs'], str):
- try:
- kwargs.update(json.loads(parsed['kwargs']))
- except:
- pass
- elif isinstance(parsed['kwargs'], dict):
- kwargs.update(parsed['kwargs'])
- else:
- # If it's not a dict, treat it as a single positional arg
- args = (args[0],)
- except:
- # If parsing fails, treat it as a single positional arg
- args = (args[0],)
-
- # Debug print the effective args and kwargs
- print(f"DEBUG: meta_api_tool wrapper called for {func.__name__}")
- print(f"DEBUG: args: {args}")
- print(f"DEBUG: kwargs: {kwargs}")
-
- # Check if access_token is provided in kwargs
- access_token = kwargs.get('access_token')
-
- # If not, try to get it from the auth manager
- if not access_token:
- try:
- print("DEBUG: No access_token in kwargs, trying to get from auth_manager")
- access_token = await get_current_access_token()
- if access_token:
- print(f"DEBUG: Got token from auth_manager (first 10 chars): {access_token[:10]}")
- else:
- print("DEBUG: No token available from auth_manager")
- # Set the global flag to indicate authentication is needed
- global needs_authentication
- needs_authentication = True
- except Exception as e:
- print(f"DEBUG: Error getting token: {e}")
- needs_authentication = True
-
- # If still no token, we need authentication
- if not access_token or needs_authentication:
- print("DEBUG: Initiating authentication flow")
- # Start the callback server
- port = start_callback_server()
-
- # Update auth manager's redirect URI with the current port
- auth_manager.redirect_uri = f"http://localhost:{port}/callback"
-
- # Generate the authentication URL
- login_url = auth_manager.get_auth_url()
-
- # Create a resource response that includes the markdown link format
- response = {
- "error": "Authentication required to use Meta Ads API",
- "login_url": login_url,
- "server_status": f"Callback server running on port {port}",
- "markdown_link": f"[Click here to authenticate with Meta Ads API]({login_url})",
- "message": "IMPORTANT: Please use the Markdown link format in your response to allow the user to click it.",
- "instructions_for_llm": "You must present this link as clickable Markdown to the user using the markdown_link format provided.",
- "note": "After authenticating, the token will be automatically saved."
- }
-
- # Wait a moment to ensure the server is fully started
- await asyncio.sleep(1)
-
- return json.dumps(response, indent=2)
-
- # Update kwargs with the token (this section won't be reached right now)
- kwargs['access_token'] = access_token
-
- # Call the original function
try:
- result = await func(*args, **kwargs)
-
- # If authentication is needed after the call (e.g., token was invalidated)
- if needs_authentication:
- # Start the callback server
- port = start_callback_server()
-
- # Update auth manager's redirect URI with the current port
- auth_manager.redirect_uri = f"http://localhost:{port}/callback"
-
- # Generate the authentication URL
- login_url = auth_manager.get_auth_url()
-
- # Create a resource response that includes the markdown link format
- response = {
- "error": "Session expired or token invalid. Please re-authenticate with Meta Ads API",
- "login_url": login_url,
- "server_status": f"Callback server running on port {port}",
- "markdown_link": f"[Click here to re-authenticate with Meta Ads API]({login_url})",
- "message": "IMPORTANT: Please use the Markdown link format in your response to allow the user to click it.",
- "instructions_for_llm": "You must present this link as clickable Markdown to the user using the markdown_link format provided.",
- "note": "After authenticating, the token will be automatically saved."
- }
-
- # Wait a moment to ensure the server is fully started
- await asyncio.sleep(1)
+ # If access_token is not in kwargs, try to get it from auth_manager
+ if 'access_token' not in kwargs or not kwargs['access_token']:
+ try:
+ access_token = await auth_manager.get_current_access_token()
+ if access_token:
+ kwargs['access_token'] = access_token
+ except Exception as e:
+ pass
+
+ if 'access_token' not in kwargs or not kwargs['access_token']:
+ needs_authentication = True
- return json.dumps(response, indent=2)
-
- return result
+ # Call the original function
+ return await func(*args, **kwargs)
except Exception as e:
- # Handle any unexpected errors
- error_result = {
- "error": f"Error calling Meta API: {str(e)}"
- }
- return json.dumps(error_result, indent=2)
+ return {"error": str(e)}
return wrapper
\ No newline at end of file
diff --git a/meta_ads_mcp/core/auth.py b/meta_ads_mcp/core/auth.py
index 301cd82..35cc365 100644
--- a/meta_ads_mcp/core/auth.py
+++ b/meta_ads_mcp/core/auth.py
@@ -587,11 +587,6 @@ class CallbackHandler(BaseHTTPRequestHandler):
self.end_headers()
self.wfile.write(b"Token received")
- # Debug prints
- print("DEBUG: Token received from Facebook")
- print(f"DEBUG: Token value (first 10 chars): {token_container['token'][:10] if token_container['token'] else 'None'}")
- print(f"DEBUG: Expires in: {token_container['expires_in']}")
-
# Process the token (save it) immediately
if token_container["token"]:
# Create token info and save to cache
@@ -600,30 +595,19 @@ class CallbackHandler(BaseHTTPRequestHandler):
expires_in=token_container["expires_in"]
)
- print(f"DEBUG: Created TokenInfo object with access_token (first 10 chars): {token_info.access_token[:10] if token_info.access_token else 'None'}")
- print(f"DEBUG: TokenInfo expires_in: {token_info.expires_in}")
-
- # Set token in auth_manager
- if 'auth_manager' in globals():
- auth_manager.token_info = token_info
- print("DEBUG: Set token_info in auth_manager")
- else:
- print("DEBUG: ERROR - auth_manager not in globals!")
-
try:
# Save to cache
- auth_manager._save_token_to_cache()
- print(f"DEBUG: Saved token to cache at {auth_manager._get_token_cache_path()}")
+ self._save_token_to_cache()
except Exception as e:
- print(f"DEBUG: ERROR saving token to cache: {str(e)}")
+ pass
# Reset auth needed flag
needs_authentication = False
- print(f"DEBUG: Token processed, needs_authentication = {needs_authentication}")
+ return token_container["token"]
else:
- print("DEBUG: ERROR - Received empty token from Facebook")
- return
+ needs_authentication = True
+ return None
# Silence server logs
def log_message(self, format, *args):
@@ -712,37 +696,49 @@ def start_callback_server():
raise e
-async def get_current_access_token() -> Optional[str]:
- """
- Get the current access token from cache
-
- Returns:
- Current access token or None if not available
- """
- print("DEBUG: get_current_access_token called")
+def process_token_response(token_container):
+ """Process the token response from Facebook."""
+ global needs_authentication
- if auth_manager:
- token = auth_manager.get_access_token()
- if token:
- print(f"DEBUG: Returned token from auth_manager (first 10 chars): {token[:10]}")
- else:
- print("DEBUG: No token available from auth_manager")
-
- # Check if token is in token_container but not in auth_manager
- if token_container and token_container.get("token") and not token:
- print("DEBUG: Found token in token_container but not in auth_manager, updating...")
- token_info = TokenInfo(
- access_token=token_container["token"],
- expires_in=token_container.get("expires_in")
- )
+ if token_container and token_container.get('token'):
+ token_info = TokenInfo(
+ access_token=token_container['token'],
+ expires_in=token_container.get('expires_in', 0)
+ )
+
+ try:
auth_manager.token_info = token_info
+ except NameError:
+ pass
+
+ try:
auth_manager._save_token_to_cache()
- return token_container["token"]
+ except Exception as e:
+ pass
- return token
+ needs_authentication = False
+ return True
else:
- print("DEBUG: auth_manager is not initialized")
- return None
+ needs_authentication = True
+ return False
+
+
+async def get_current_access_token():
+ """Get the current access token, either from auth_manager or token_container."""
+ try:
+ token = auth_manager.get_access_token()
+ if token:
+ return token
+ except Exception:
+ if token_container.get('token'):
+ auth_manager.token_info = TokenInfo(
+ access_token=token_container['token'],
+ expires_in=token_container.get('expires_in', 0)
+ )
+ return token_container['token']
+ pass
+
+ return None
def login():
diff --git a/meta_ads_mcp/core/insights.py b/meta_ads_mcp/core/insights.py
index 6d87300..8e7cf3c 100644
--- a/meta_ads_mcp/core/insights.py
+++ b/meta_ads_mcp/core/insights.py
@@ -84,7 +84,6 @@ async def debug_image_download(access_token: str = None, url: str = "", ad_id: s
}, indent=2)
results["image_url"] = url
- print(f"Debug: Testing image URL: {url}")
# Try to get network information to help debug
try: