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.

Enhance error handling for callback server initialization

Yves Junqueirafc5d2f5532cd
diff --git a/meta_ads_mcp/core/adsets.py b/meta_ads_mcp/core/adsets.py
index b92c076..2fdd1f3 100644
--- a/meta_ads_mcp/core/adsets.py
+++ b/meta_ads_mcp/core/adsets.py
@@ -270,12 +270,21 @@ async def update_adset(adset_id: str, frequency_control_specs: List[Dict[str, An
current_details = json.loads(current_details_json)
# Start the callback server if not already running
- port = start_callback_server()
-
- # Generate confirmation URL with properly encoded parameters
- changes_json = json.dumps(changes)
- encoded_changes = urllib.parse.quote(changes_json)
- confirmation_url = f"http://localhost:{port}/confirm-update?adset_id={adset_id}&token={access_token}&changes={encoded_changes}"
+ try:
+ port = start_callback_server()
+
+ # Generate confirmation URL with properly encoded parameters
+ changes_json = json.dumps(changes)
+ encoded_changes = urllib.parse.quote(changes_json)
+ confirmation_url = f"http://localhost:{port}/confirm-update?adset_id={adset_id}&token={access_token}&changes={encoded_changes}"
+ except Exception as e:
+ return json.dumps({
+ "error": "Callback server disabled",
+ "message": f"Cannot create confirmation URL: {str(e)}",
+ "suggestion": "Manual update confirmation not available when META_ADS_DISABLE_CALLBACK_SERVER is set",
+ "adset_id": adset_id,
+ "proposed_changes": changes
+ }, indent=2)
# Reset the update confirmation
update_confirmation.clear()
diff --git a/meta_ads_mcp/core/auth.py b/meta_ads_mcp/core/auth.py
index a8a08c9..06ea549 100644
--- a/meta_ads_mcp/core/auth.py
+++ b/meta_ads_mcp/core/auth.py
@@ -216,22 +216,27 @@ class AuthManager:
return self.token_info.access_token
# Start the callback server if not already running
- port = start_callback_server()
-
- # Update redirect URI with the actual port
- self.redirect_uri = f"http://localhost:{port}/callback"
-
- # Generate the auth URL
- auth_url = self.get_auth_url()
-
- # Open browser with auth URL
- logger.info(f"Opening browser with URL: {auth_url}")
- webbrowser.open(auth_url)
-
- # We don't wait for the token here anymore
- # The token will be processed by the callback server
- # Just return None to indicate we've started the flow
- return None
+ try:
+ port = start_callback_server()
+
+ # Update redirect URI with the actual port
+ self.redirect_uri = f"http://localhost:{port}/callback"
+
+ # Generate the auth URL
+ auth_url = self.get_auth_url()
+
+ # Open browser with auth URL
+ logger.info(f"Opening browser with URL: {auth_url}")
+ webbrowser.open(auth_url)
+
+ # We don't wait for the token here anymore
+ # The token will be processed by the callback server
+ # Just return None to indicate we've started the flow
+ return None
+ except Exception as e:
+ logger.error(f"Failed to start callback server: {e}")
+ logger.info("Callback server disabled. OAuth authentication flow cannot be used.")
+ return None
def get_access_token(self) -> Optional[str]:
"""
@@ -477,7 +482,14 @@ def login():
try:
# Start the callback server first
- port = start_callback_server()
+ try:
+ port = start_callback_server()
+ except Exception as callback_error:
+ print(f"Error: {callback_error}")
+ print("Callback server is disabled. Please use alternative authentication methods:")
+ print("- Set PIPEBOARD_API_TOKEN environment variable for Pipeboard authentication")
+ print("- Or provide a direct META_ACCESS_TOKEN environment variable")
+ return
# Get the auth URL and open the browser
auth_url = auth_manager.get_auth_url()
diff --git a/meta_ads_mcp/core/authentication.py b/meta_ads_mcp/core/authentication.py
index bd0c640..7a6487b 100644
--- a/meta_ads_mcp/core/authentication.py
+++ b/meta_ads_mcp/core/authentication.py
@@ -90,14 +90,23 @@ async def get_login_link(access_token: str = None) -> str:
# IMPORTANT: Start the callback server first by calling our helper function
# This ensures the server is ready before we provide the URL to the user
logger.info("Starting callback server for authentication")
- port = start_callback_server()
- logger.info(f"Callback server started on port {port}")
-
- # Generate direct login URL
- auth_manager.redirect_uri = f"http://localhost:{port}/callback" # Ensure port is set correctly
- logger.info(f"Setting redirect URI to {auth_manager.redirect_uri}")
- login_url = auth_manager.get_auth_url()
- logger.info(f"Generated login URL: {login_url}")
+ try:
+ port = start_callback_server()
+ logger.info(f"Callback server started on port {port}")
+
+ # Generate direct login URL
+ auth_manager.redirect_uri = f"http://localhost:{port}/callback" # Ensure port is set correctly
+ logger.info(f"Setting redirect URI to {auth_manager.redirect_uri}")
+ login_url = auth_manager.get_auth_url()
+ logger.info(f"Generated login URL: {login_url}")
+ except Exception as e:
+ logger.error(f"Failed to start callback server: {e}")
+ return json.dumps({
+ "error": "Callback server disabled",
+ "message": str(e),
+ "suggestion": "Use Pipeboard authentication (set PIPEBOARD_API_TOKEN) or provide a direct access token",
+ "authentication_method": "meta_oauth_disabled"
+ }, indent=2)
# Check if we can exchange for long-lived tokens
token_exchange_supported = bool(META_APP_SECRET)
diff --git a/meta_ads_mcp/core/callback_server.py b/meta_ads_mcp/core/callback_server.py
index 8b8949d..a5c8524 100644
--- a/meta_ads_mcp/core/callback_server.py
+++ b/meta_ads_mcp/core/callback_server.py
@@ -917,7 +917,16 @@ def start_callback_server() -> int:
Returns:
Port number the server is running on
+
+ Raises:
+ Exception: If callback server is disabled via META_ADS_DISABLE_CALLBACK_SERVER environment variable
"""
+ # Check if callback server is disabled via environment variable
+ if os.environ.get("META_ADS_DISABLE_CALLBACK_SERVER"):
+ logger.info("Callback server disabled via META_ADS_DISABLE_CALLBACK_SERVER environment variable")
+ print("Callback server is disabled. OAuth authentication flow cannot be used.")
+ raise Exception("Callback server disabled via META_ADS_DISABLE_CALLBACK_SERVER environment variable. Use alternative authentication methods.")
+
global callback_server_thread, callback_server_running, callback_server_port, callback_server_instance, server_shutdown_timer
with callback_server_lock: