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 debugging tools for Meta API token management

Yves Junqueira11120cfc3779
diff --git a/debug_meta_api_tool.py b/debug_meta_api_tool.py
new file mode 100644
index 0000000..2de6a2f
--- /dev/null
+++ b/debug_meta_api_tool.py
@@ -0,0 +1,248 @@
+#!/usr/bin/env python
+"""
+A modified version of the meta_api_tool wrapper function with enhanced debugging
+to understand how tokens are managed.
+"""
+
+import os
+import asyncio
+import json
+import logging
+import inspect
+from functools import wraps
+from typing import Any, Dict, Optional
+
+# Set up logging
+logging.basicConfig(
+ level=logging.DEBUG,
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
+)
+logger = logging.getLogger("meta_api_wrapper_debug")
+
+# Import needed components
+from meta_ads_mcp.core.pipeboard_auth import pipeboard_auth_manager
+from meta_ads_mcp.api import get_ad_accounts
+
+# Flag to track if authentication is needed
+needs_authentication = False
+
+async def debug_get_current_access_token() -> Optional[str]:
+ """
+ Debug version of get_current_access_token with detailed logging
+ """
+ logger.debug("debug_get_current_access_token called")
+
+ # Try to get token from pipeboard_auth_manager
+ if pipeboard_auth_manager:
+ token = pipeboard_auth_manager.get_access_token()
+ if token:
+ logger.debug(f"Token retrieved from pipeboard_auth_manager: {token[:10]}...{token[-5:]}")
+ return token
+ else:
+ logger.debug("No token returned from pipeboard_auth_manager")
+ else:
+ logger.debug("pipeboard_auth_manager is not available")
+
+ logger.debug("Returning None from debug_get_current_access_token")
+ return None
+
+def debug_meta_api_tool(func):
+ """Debugging version of meta_api_tool decorator with enhanced logging"""
+ @wraps(func)
+ async def wrapper(*args, **kwargs):
+ global needs_authentication
+
+ logger.debug(f"debug_meta_api_tool wrapper called for {func.__name__}")
+ logger.debug(f"Args: {args}")
+ logger.debug(f"Kwargs: {kwargs}")
+
+ # Handle various MCP invocation patterns
+ if len(args) == 1:
+ logger.debug("Single argument detected, checking type")
+ # MCP might pass a single string argument that contains JSON
+ if isinstance(args[0], str):
+ logger.debug(f"String argument: {args[0][:50]}...")
+ try:
+ # Try to parse the single string argument as JSON dictionary
+ parsed_kwargs = json.loads(args[0]) if args[0] else {}
+ logger.debug(f"Parsed string to JSON: {parsed_kwargs}")
+ # Clear args and use parsed_kwargs
+ args = ()
+ kwargs.update(parsed_kwargs)
+ logger.debug(f"Updated kwargs: {kwargs}")
+ except Exception as e:
+ logger.debug(f"JSON parsing error: {e}")
+ # MCP might also pass a single dictionary argument
+ elif isinstance(args[0], dict):
+ logger.debug(f"Dict argument: {args[0]}")
+ # Treat the dict as kwargs
+ kwargs.update(args[0])
+ args = ()
+ logger.debug(f"Updated kwargs from dict: {kwargs}")
+
+ # Check if we have a 'kwargs' parameter, which means MCP is nesting the real parameters
+ if 'kwargs' in kwargs and isinstance(kwargs['kwargs'], (str, dict)):
+ logger.debug("'kwargs' parameter found in kwargs")
+ # If it's a string, try to parse as JSON
+ if isinstance(kwargs['kwargs'], str):
+ logger.debug(f"'kwargs' is a string: {kwargs['kwargs'][:50]}...")
+ try:
+ parsed_inner_kwargs = json.loads(kwargs['kwargs']) if kwargs['kwargs'] else {}
+ logger.debug(f"Parsed inner_kwargs: {parsed_inner_kwargs}")
+ kwargs.update(parsed_inner_kwargs)
+ except Exception as e:
+ logger.debug(f"Inner JSON parsing error: {e}")
+ # If parsing fails, just keep the original kwargs
+ pass
+ # If it's already a dict, just update kwargs
+ elif isinstance(kwargs['kwargs'], dict):
+ logger.debug(f"'kwargs' is a dict: {kwargs['kwargs']}")
+ kwargs.update(kwargs['kwargs'])
+
+ # Remove the 'kwargs' parameter to avoid confusion
+ del kwargs['kwargs']
+ logger.debug(f"Updated kwargs after processing nested kwargs: {kwargs}")
+
+ # Handle 'args' parameter if it exists
+ if 'args' in kwargs:
+ logger.debug("'args' parameter found in kwargs, removing it")
+ # We don't use positional args, so just remove it
+ del kwargs['args']
+
+ # Check if access_token is provided in kwargs
+ access_token = kwargs.get('access_token')
+ if access_token:
+ logger.debug(f"access_token found in kwargs: {access_token[:10]}...{access_token[-5:]}")
+ else:
+ logger.debug("No access_token found in kwargs, trying to get from auth manager")
+
+ # If not, try to get it from the auth manager
+ if not access_token:
+ access_token = await debug_get_current_access_token()
+ if access_token:
+ logger.debug(f"Token retrieved from debug_get_current_access_token: {access_token[:10]}...{access_token[-5:]}")
+ kwargs['access_token'] = access_token
+ logger.debug("Added access_token to kwargs")
+ else:
+ logger.debug("No token returned from debug_get_current_access_token")
+
+ # If still no token, we need authentication
+ if not access_token:
+ logger.debug("No access_token available, setting needs_authentication=True")
+ needs_authentication = True
+
+ # Check if we're using Pipeboard authentication
+ using_pipeboard = bool(os.environ.get("PIPEBOARD_API_TOKEN", ""))
+ logger.debug(f"Using Pipeboard authentication: {using_pipeboard}")
+
+ if using_pipeboard:
+ # For Pipeboard, we use a different authentication flow
+ try:
+ logger.debug("Initiating Pipeboard auth flow")
+ # Here we'd import dynamically to avoid circular imports
+ # Already imported pipeboard_auth_manager at the top
+
+ # Initiate the Pipeboard auth flow
+ auth_data = pipeboard_auth_manager.initiate_auth_flow()
+ login_url = auth_data.get("loginUrl")
+ logger.debug(f"Auth flow initiated, login URL: {login_url[:50]}...")
+
+ # Return a user-friendly authentication required response for Pipeboard
+ response = {
+ "error": "Authentication Required",
+ "details": {
+ "message": "You need to authenticate with the Meta API via Pipeboard",
+ "action_required": "Please authenticate using the link below",
+ "login_url": login_url,
+ "markdown_link": f"[Click here to authenticate with Meta Ads API via Pipeboard]({login_url})",
+ "authentication_method": "pipeboard"
+ }
+ }
+ logger.debug(f"Returning authentication required response: {response}")
+ return json.dumps(response, indent=2)
+ except Exception as e:
+ logger.error(f"Error initiating Pipeboard auth flow: {e}")
+ response = {
+ "error": f"Pipeboard Authentication Error: {str(e)}",
+ "details": {
+ "message": "Failed to initiate Pipeboard authentication flow",
+ "action_required": "Please check your PIPEBOARD_API_TOKEN environment variable"
+ }
+ }
+ logger.debug(f"Returning error response: {response}")
+ return json.dumps(response, indent=2)
+
+ # Call the original function
+ try:
+ logger.debug(f"Calling original function {func.__name__} with kwargs: {kwargs}")
+ result = await func(**kwargs)
+ logger.debug(f"Original function returned result type: {type(result)}")
+
+ # If authentication is needed after the call (e.g., token was invalidated)
+ if needs_authentication:
+ logger.debug("needs_authentication flag is True after function call")
+ # Similar authentication logic as above...
+ # (omitted for brevity, add back in if needed)
+ pass
+
+ return result
+ except Exception as e:
+ logger.error(f"Error calling original function: {e}")
+ # Handle any unexpected errors
+ error_result = {
+ "error": f"Error calling Meta API: {str(e)}"
+ }
+ return json.dumps(error_result, indent=2)
+
+ return wrapper
+
+async def test_debug_wrapper():
+ """Test function to demonstrate the debug wrapper"""
+ # Apply our debug wrapper to get_ad_accounts
+ debug_wrapped_get_ad_accounts = debug_meta_api_tool(get_ad_accounts.__wrapped__)
+
+ print("===== Testing Debug Meta API Tool Wrapper =====")
+
+ print("\n1. Calling without explicit token:")
+ try:
+ result = await debug_wrapped_get_ad_accounts()
+ print(f"Result type: {type(result)}")
+ if isinstance(result, str):
+ data = json.loads(result)
+ if "error" in data:
+ print(f"Error: {data['error']}")
+ elif isinstance(data, list):
+ print(f"Success! Found {len(data)} items.")
+ else:
+ print(f"Unexpected result format: {type(data)}")
+ except Exception as e:
+ print(f"Error in call: {e}")
+
+ # Get a token directly from pipeboard_auth_manager
+ print("\n2. Getting token directly from pipeboard_auth_manager:")
+ token = pipeboard_auth_manager.get_access_token()
+ if token:
+ print(f"Token: {token[:10]}...{token[-5:]}")
+
+ print("\n3. Calling with explicit token:")
+ try:
+ result = await debug_wrapped_get_ad_accounts(access_token=token)
+ print(f"Result type: {type(result)}")
+ if isinstance(result, str):
+ data = json.loads(result)
+ if "error" in data:
+ print(f"Error: {data['error']}")
+ elif isinstance(data, list):
+ print(f"Success! Found {len(data)} items.")
+ else:
+ print(f"Unexpected result format: {type(data)}")
+ except Exception as e:
+ print(f"Error in call with token: {e}")
+ else:
+ print("No token available")
+
+ print("\n4. Global state:")
+ print(f"needs_authentication: {needs_authentication}")
+
+if __name__ == "__main__":
+ asyncio.run(test_debug_wrapper())
\ No newline at end of file
diff --git a/debug_token_flow.py b/debug_token_flow.py
new file mode 100644
index 0000000..5d2a14a
--- /dev/null
+++ b/debug_token_flow.py
@@ -0,0 +1,156 @@
+#!/usr/bin/env python
+"""
+Debug script to verify token flow between pipeboard_auth_manager and the meta_api_tool wrapper.
+This script will help us understand how tokens are being passed and used throughout the system.
+"""
+
+import os
+import sys
+import json
+import asyncio
+import logging
+import inspect
+from pprint import pprint
+
+# Set up logging
+logging.basicConfig(
+ level=logging.DEBUG,
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
+)
+logger = logging.getLogger("token_flow_debug")
+
+# Import the auth modules and API functions
+from meta_ads_mcp.core.pipeboard_auth import pipeboard_auth_manager, PIPEBOARD_API_BASE
+from meta_ads_mcp.api import get_ad_accounts, auth_manager, get_current_access_token, meta_api_tool, needs_authentication
+
+# Get the original get_ad_accounts function before it's wrapped
+original_get_ad_accounts = None
+for attr_name in dir(get_ad_accounts):
+ if attr_name == "__wrapped__":
+ original_get_ad_accounts = getattr(get_ad_accounts, attr_name)
+ break
+
+async def debug_token_flow():
+ """Test and debug the token flow between different components"""
+ print("===== Token Flow Debugging =====")
+
+ # 1. Check if PIPEBOARD_API_TOKEN is set
+ api_token = os.environ.get("PIPEBOARD_API_TOKEN")
+ if not api_token:
+ print("No PIPEBOARD_API_TOKEN environment variable set. Please set it first.")
+ return
+
+ print(f"Using Pipeboard API token: {api_token[:5]}...")
+ print(f"Pipeboard API base URL: {PIPEBOARD_API_BASE}")
+
+ # 2. Get token from pipeboard_auth_manager
+ print("\n--- Step 1: Get token from pipeboard_auth_manager ---")
+ pipeboard_token = pipeboard_auth_manager.get_access_token()
+
+ if pipeboard_token:
+ print(f"Token from pipeboard_auth_manager: {pipeboard_token[:10]}...{pipeboard_token[-5:]}")
+ print(f"Token type: {type(pipeboard_token)}")
+ print(f"Token length: {len(pipeboard_token)}")
+
+ # Check token info object
+ if pipeboard_auth_manager.token_info:
+ print(f"Token expires_at: {pipeboard_auth_manager.token_info.expires_at}")
+ print(f"Token is_expired(): {pipeboard_auth_manager.token_info.is_expired()}")
+ else:
+ print("No token returned from pipeboard_auth_manager")
+
+ # 3. Check if the token is available through get_current_access_token
+ print("\n--- Step 2: Check token via get_current_access_token ---")
+ current_token = await get_current_access_token()
+
+ if current_token:
+ print(f"Token from get_current_access_token: {current_token[:10]}...{current_token[-5:]}")
+ if current_token == pipeboard_token:
+ print("✅ Tokens match: get_current_access_token returns the same token as pipeboard_auth_manager")
+ else:
+ print("❌ MISMATCH: get_current_access_token returns a different token!")
+ else:
+ print("No token returned from get_current_access_token")
+
+ # 4. Check auth_manager directly
+ print("\n--- Step 3: Check auth_manager directly ---")
+ print(f"auth_manager object type: {type(auth_manager)}")
+ print(f"auth_manager fields: {dir(auth_manager)}")
+
+ try:
+ auth_manager_token = auth_manager.get_access_token()
+ if auth_manager_token:
+ print(f"Token from auth_manager.get_access_token(): {auth_manager_token[:10]}...{auth_manager_token[-5:]}")
+ if auth_manager_token == pipeboard_token:
+ print("✅ Tokens match: auth_manager returns the same token as pipeboard_auth_manager")
+ else:
+ print("❌ MISMATCH: auth_manager returns a different token!")
+ else:
+ print("No token returned from auth_manager.get_access_token()")
+ except AttributeError:
+ print("auth_manager does not have get_access_token method")
+
+ # 5. Check directly from wrapper function
+ print("\n--- Step 4: Check token in wrapper function ---")
+
+ # Create a simple wrapped function to log the token
+ @meta_api_tool
+ async def debug_token_wrapper(access_token=None, **kwargs):
+ print(f"Inside wrapped function, access_token received: {access_token[:10]}...{access_token[-5:] if access_token else None}")
+ return {"success": True, "token_present": access_token is not None}
+
+ # Call the wrapped function directly without token
+ print("Calling wrapped function without token parameter...")
+ result = await debug_token_wrapper()
+ print(f"Result from wrapper: {result}")
+
+ # 6. Test get_ad_accounts with explicit token
+ print("\n--- Step 5: Call get_ad_accounts with explicit token ---")
+ try:
+ # Call get_ad_accounts with explicit token
+ ad_accounts_json = await get_ad_accounts(access_token=pipeboard_token)
+ data = json.loads(ad_accounts_json)
+ if isinstance(data, dict) and "error" in data:
+ print(f"Error: {data['error']}")
+ elif isinstance(data, list):
+ print(f"Success! Found {len(data)} ad accounts.")
+ else:
+ print(f"Unexpected response format: {type(data)}")
+ except Exception as e:
+ print(f"Error calling get_ad_accounts with explicit token: {e}")
+
+ # 7. Test get_ad_accounts without explicit token
+ print("\n--- Step 6: Call get_ad_accounts without explicit token ---")
+ try:
+ # Call get_ad_accounts without explicit token
+ ad_accounts_json = await get_ad_accounts()
+ data = json.loads(ad_accounts_json)
+ if isinstance(data, dict) and "error" in data:
+ print(f"Error: {data['error']}")
+ if "details" in data:
+ print(f"Error details: {data['details']}")
+ elif isinstance(data, list):
+ print(f"Success! Found {len(data)} ad accounts.")
+ else:
+ print(f"Unexpected response format: {type(data)}")
+ except Exception as e:
+ print(f"Error calling get_ad_accounts without explicit token: {e}")
+
+ # 8. Check global needs_authentication flag
+ print(f"\nGlobal needs_authentication flag: {needs_authentication}")
+
+ # 9. Check if original function is accessible
+ print("\n--- Step 7: Check original function ---")
+ if original_get_ad_accounts:
+ print(f"Original get_ad_accounts function: {original_get_ad_accounts}")
+ try:
+ # Try to call the original function
+ result = await original_get_ad_accounts(access_token=pipeboard_token)
+ print(f"Original function result available: {result is not None}")
+ except Exception as e:
+ print(f"Error calling original function: {e}")
+ else:
+ print("Could not access original get_ad_accounts function")
+
+if __name__ == "__main__":
+ asyncio.run(debug_token_flow())
\ No newline at end of file
diff --git a/meta_ads_mcp/api.py b/meta_ads_mcp/api.py
index 2e329a5..97e8910 100644
--- a/meta_ads_mcp/api.py
+++ b/meta_ads_mcp/api.py
@@ -30,7 +30,7 @@ USER_AGENT = "meta-ads-mcp/1.0"
META_APP_ID = os.environ.get("META_APP_ID", "") # Default to empty string
# Auth constants
-AUTH_SCOPE = "ads_management,ads_read,business_management"
+AUTH_SCOPE = "ads_management,ads_read,business_management,public_profile"
AUTH_REDIRECT_URI = "http://localhost:8888/callback"
AUTH_RESPONSE_TYPE = "token"
diff --git a/meta_ads_mcp/core/auth.py b/meta_ads_mcp/core/auth.py
index 1c7b66c..44799ee 100644
--- a/meta_ads_mcp/core/auth.py
+++ b/meta_ads_mcp/core/auth.py
@@ -22,7 +22,7 @@ from .callback_server import (
from .pipeboard_auth import pipeboard_auth_manager
# Auth constants
-AUTH_SCOPE = "ads_management,ads_read,business_management"
+AUTH_SCOPE = "ads_management,ads_read,business_management,public_profile"
AUTH_REDIRECT_URI = "http://localhost:8888/callback"
AUTH_RESPONSE_TYPE = "token"
diff --git a/meta_ads_mcp/core/pipeboard_auth.py b/meta_ads_mcp/core/pipeboard_auth.py
index 5dd77c8..1b06bcf 100644
--- a/meta_ads_mcp/core/pipeboard_auth.py
+++ b/meta_ads_mcp/core/pipeboard_auth.py
@@ -202,9 +202,9 @@ class PipeboardAuthManager:
logger.error("No PIPEBOARD_API_TOKEN environment variable set")
raise ValueError("No PIPEBOARD_API_TOKEN environment variable set")
- url = f"{PIPEBOARD_API_BASE}/meta/auth"
+ # Pass token as URL parameter instead of Authorization header
+ url = f"{PIPEBOARD_API_BASE}/meta/auth?api_token={self.api_token}"
headers = {
- "Authorization": f"Bearer {self.api_token}",
"Content-Type": "application/json"
}
@@ -262,10 +262,9 @@ class PipeboardAuthManager:
# If force refresh or no token/expired token, get a new one from Pipeboard
try:
- # Make a request to get the token
- url = f"{PIPEBOARD_API_BASE}/meta/token"
+ # Make a request to get the token, passing API token as URL parameter
+ url = f"{PIPEBOARD_API_BASE}/meta/token?api_token={self.api_token}"
headers = {
- "Authorization": f"Bearer {self.api_token}",
"Content-Type": "application/json"
}
diff --git a/meta_auth_test.sh b/meta_auth_test.sh
new file mode 100755
index 0000000..e4a6589
--- /dev/null
+++ b/meta_auth_test.sh
@@ -0,0 +1,4 @@
+#!/bin/bash
+echo "Initiating Meta OAuth authorization flow..."
+curl -X POST "http://localhost:3000/api/meta/auth?api_token=pk_8ee8c727644d4d32b646ddcf16f2385e" -H "Content-Type: application/json"
+read -p "Press enter after authorizing the app in the browser..."
diff --git a/test_meta_ads_auth.py b/test_meta_ads_auth.py
index e521f87..5791754 100644
--- a/test_meta_ads_auth.py
+++ b/test_meta_ads_auth.py
@@ -45,8 +45,13 @@ async def test_authentication(app_id=None, force_login=False):
# Test the token by getting ad accounts
print("\nFetching ad accounts to test token...")
- ad_accounts_json = await get_ad_accounts(token)
- ad_accounts = json.loads(ad_accounts_json)
+ ad_accounts_json = await get_ad_accounts(access_token=token)
+
+ # Check if ad_accounts_json is already a dictionary or a JSON string
+ if isinstance(ad_accounts_json, dict):
+ ad_accounts = ad_accounts_json
+ else:
+ ad_accounts = json.loads(ad_accounts_json)
if "error" in ad_accounts:
print(f"Error fetching ad accounts: {ad_accounts['error']}")
diff --git a/test_pipeboard_auth.py b/test_pipeboard_auth.py
index 2e7a097..236a200 100644
--- a/test_pipeboard_auth.py
+++ b/test_pipeboard_auth.py
@@ -12,6 +12,7 @@ import argparse
import requests
import logging
import inspect
+import socket
# Set up logging
logging.basicConfig(
@@ -28,6 +29,44 @@ from meta_ads_mcp.api import get_ad_accounts
META_GRAPH_API_VERSION = "v20.0"
META_GRAPH_API_BASE = f"https://graph.facebook.com/{META_GRAPH_API_VERSION}"
+def test_server_connectivity(server_url, port=3000):
+ """Test if the Pipeboard server is reachable and identify network issues"""
+ logger.debug(f"Testing server connectivity to {server_url}")
+
+ # Parse the URL
+ from urllib.parse import urlparse
+ parsed_url = urlparse(server_url)
+ hostname = parsed_url.netloc.split(':')[0]
+
+ # Test basic connectivity with socket
+ try:
+ logger.debug(f"Testing TCP connection to {hostname}:{port}")
+ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ s.settimeout(5)
+ s.connect((hostname, port))
+ logger.debug(f"TCP connection successful to {hostname}:{port}")
+ s.close()
+ except socket.error as e:
+ logger.error(f"Socket connection failed: {e}")
+ return False
+
+ # Test HTTP request to server root
+ try:
+ logger.debug(f"Testing HTTP request to {server_url}")
+ response = requests.get(server_url, timeout=5)
+ logger.debug(f"HTTP GET {server_url} response: {response.status_code}")
+
+ if response.status_code == 200:
+ logger.debug("Server is responding to HTTP requests")
+ return True
+ else:
+ logger.error(f"Server returned HTTP {response.status_code}")
+ logger.error(f"Response content: {response.text[:500]}")
+ return False
+ except requests.RequestException as e:
+ logger.error(f"HTTP request failed: {e}")
+ return False
+
async def test_token_manually(access_token):
"""Test the access token directly with Graph API to validate it"""
logger.debug(f"Testing token directly with Graph API...")
@@ -54,9 +93,9 @@ async def test_token_manually(access_token):
async def debug_pipeboard_token_endpoint(api_token):
"""Debug the Pipeboard token endpoint directly"""
logger.debug(f"Debugging Pipeboard token endpoint...")
- url = f"{PIPEBOARD_API_BASE}/meta/token"
+ # Pass token as URL parameter instead of Authorization header
+ url = f"{PIPEBOARD_API_BASE}/meta/token?api_token={api_token}"
headers = {
- "Authorization": f"Bearer {api_token}",
"Content-Type": "application/json"
}
@@ -93,13 +132,30 @@ async def inspect_api_call_params(token):
except Exception as e:
logger.error(f"Error getting function source: {e}")
-async def test_pipeboard_authentication(api_token=None, force_login=False, verbose=False):
+async def test_pipeboard_authentication(api_token=None, force_login=False, verbose=False, check_server=False):
"""Test the Pipeboard authentication flow and run a simple command"""
print("===== Meta Ads MCP Authentication Test via Pipeboard.co =====")
if verbose:
print(f"Debug mode is ENABLED. Check logs for detailed information.")
+ # Test server connectivity if requested
+ if check_server:
+ print("\nTesting server connectivity...")
+ server_url = PIPEBOARD_API_BASE.rsplit('/api', 1)[0] # Get base URL without /api
+ if test_server_connectivity(server_url):
+ print(f"✅ Pipeboard server at {server_url} is reachable")
+ else:
+ print(f"❌ CONNECTIVITY ERROR: Cannot reach Pipeboard server at {server_url}")
+ print("Please check if the server is running and reachable from your machine.")
+ print(f"Current PIPEBOARD_API_BASE is set to: {PIPEBOARD_API_BASE}")
+ print("\nPossible issues:")
+ print("1. Server is not running at the expected address")
+ print("2. Firewall is blocking the connection")
+ print("3. Network connectivity issues")
+ print("4. Incorrect server URL in environment variables")
+ return
+
# Set the Pipeboard API token if provided
if api_token:
os.environ["PIPEBOARD_API_TOKEN"] = api_token
@@ -182,7 +238,9 @@ async def test_pipeboard_authentication(api_token=None, force_login=False, verbo
print("\nFetching ad accounts to test token...")
logger.debug("Calling get_ad_accounts with token...")
try:
- ad_accounts_json = await get_ad_accounts(token)
+ # Directly call the function with the token, not relying on the wrapper
+ # to find it from auth manager
+ ad_accounts_json = await get_ad_accounts(access_token=token, user_id="me", limit=10)
logger.debug(f"API Response raw: {ad_accounts_json[:500]}...")
try:
@@ -190,22 +248,42 @@ async def test_pipeboard_authentication(api_token=None, force_login=False, verbo
# Check for error response
if isinstance(ad_accounts, dict) and ad_accounts.get("error"):
- error_info = ad_accounts.get("error", {})
- print(f"Error from Meta API: {error_info.get('message', 'Unknown error')}")
- logger.error(f"Detailed error info: {json.dumps(error_info, indent=2)}")
+ # Direct error message
+ if isinstance(ad_accounts["error"], str):
+ print(f"Error from Meta API: {ad_accounts['error']}")
+ logger.error(f"Error message: {ad_accounts['error']}")
+
+ # Check for details
+ if "details" in ad_accounts and isinstance(ad_accounts["details"], dict):
+ error_details = ad_accounts["details"]
+ logger.error(f"Error details: {json.dumps(error_details, indent=2)}")
+ print(f"Error details: {error_details.get('message', 'No additional details')}")
+ # Error object
+ elif isinstance(ad_accounts["error"], dict):
+ error_info = ad_accounts["error"]
+ print(f"Error from Meta API: {error_info.get('message', 'Unknown error')}")
+ logger.error(f"Detailed error info: {json.dumps(error_info, indent=2)}")
+
+ # Specific error handling for common issues
+ if "code" in error_info:
+ code = error_info.get("code")
+ if code == 190:
+ print("\n⚠️ Error 190: Invalid or expired access token")
+ print("This likely means your token has expired or been invalidated by Meta.")
+ elif code == 4:
+ print("\n⚠️ Error 4: Application request limit reached")
+ print("You have hit Meta's API rate limits.")
+ elif code == 200:
+ print("\n⚠️ Error 200: Permission error")
+ print("The token doesn't have permission for the requested operation.")
+
+ # If there's a login_url in the response, show it
+ if "login_url" in ad_accounts:
+ print(f"\nPlease re-authenticate using this URL: {ad_accounts['login_url']}")
- # Specific error handling for common issues
- if "code" in error_info:
- code = error_info.get("code")
- if code == 190:
- print("\n⚠️ Error 190: Invalid or expired access token")
- print("This likely means your token has expired or been invalidated by Meta.")
- elif code == 4:
- print("\n⚠️ Error 4: Application request limit reached")
- print("You have hit Meta's API rate limits.")
- elif code == 200:
- print("\n⚠️ Error 200: Permission error")
- print("The token doesn't have permission for the requested operation.")
+ # Look for markdown_link which may contain a clickable auth link
+ if "markdown_link" in ad_accounts:
+ print(f"\nAuthentication link: {ad_accounts['markdown_link']}")
return
@@ -233,7 +311,13 @@ if __name__ == "__main__":
parser.add_argument("--api-token", type=str, help="Pipeboard API token for authentication")
parser.add_argument("--force-login", action="store_true", help="Force new login even if cached token exists")
parser.add_argument("--verbose", "-v", action="store_true", help="Enable verbose debug logging")
+ parser.add_argument("--check-server", action="store_true", help="Test server connectivity before proceeding")
args = parser.parse_args()
- asyncio.run(test_pipeboard_authentication(api_token=args.api_token, force_login=args.force_login, verbose=args.verbose))
\ No newline at end of file
+ asyncio.run(test_pipeboard_authentication(
+ api_token=args.api_token,
+ force_login=args.force_login,
+ verbose=args.verbose,
+ check_server=args.check_server
+ ))
\ No newline at end of file