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 Pipeboard authentication script and enhance server integration

Yves Junqueira4b0fe5cc4f6c
diff --git a/meta-ads-mcp b/meta-ads-mcp
index 0b11a42..ebc9ba7 100755
--- a/meta-ads-mcp
+++ b/meta-ads-mcp
@@ -7,7 +7,44 @@ Meta Ads MCP - Command Line Entry Point
This script provides the command-line entry point for the Meta Ads MCP package.
"""
+import sys
+import os
+import webbrowser
from meta_ads_mcp import main
+from meta_ads_mcp.core.pipeboard_auth import pipeboard_auth_manager
if __name__ == "__main__":
+ # Check if we have a Pipeboard token environment variable
+ pipeboard_api_token = os.environ.get("PIPEBOARD_API_TOKEN")
+ if pipeboard_api_token:
+ print("Using Pipeboard authentication...")
+ # Check for existing token
+ token = pipeboard_auth_manager.get_access_token()
+ if not token:
+ print("No valid token found. Initiating browser-based authentication...")
+ try:
+ # Initialize the auth flow and get the login URL
+ auth_data = pipeboard_auth_manager.initiate_auth_flow()
+ login_url = auth_data.get('loginUrl')
+ if login_url:
+ print(f"Opening browser with login URL: {login_url}")
+ webbrowser.open(login_url)
+ print("Please complete authorization in your browser.")
+ print("Then wait while the token is retrieved...")
+
+ # Poll for token
+ import time
+ for i in range(30): # Try for 60 seconds
+ print(f"Waiting for authentication... ({i+1}/30)")
+ token = pipeboard_auth_manager.get_access_token(force_refresh=True)
+ if token:
+ print("Authentication successful!")
+ break
+ time.sleep(2)
+ else:
+ print("Error: Could not get login URL")
+ except Exception as e:
+ print(f"Error during authentication: {e}")
+
+ # Start the main application
main()
\ No newline at end of file
diff --git a/meta_ads_auth.sh b/meta_ads_auth.sh
new file mode 100755
index 0000000..4e93256
--- /dev/null
+++ b/meta_ads_auth.sh
@@ -0,0 +1,54 @@
+#!/bin/bash
+echo "Starting Meta Ads MCP with Pipeboard authentication..."
+
+# Set the Pipeboard API token as an environment variable
+export PIPEBOARD_API_TOKEN="pk_8ee8c727644d4d32b646ddcf16f2385e"
+
+# Check if the Pipeboard server is running and can handle meta auth
+echo "Checking if Pipeboard meta auth endpoint is available..."
+curl -s -o /dev/null -w "%{http_code}" "http://localhost:3000/api/meta" > /dev/null
+if [ $? -ne 0 ]; then
+ echo "Warning: Could not connect to Pipeboard meta endpoint"
+ echo "Please make sure the Pipeboard server is running before proceeding."
+ echo "You can start it with: cd /path/to/pipeboard && npm run dev"
+ echo ""
+ echo "As a test, you can try running this command separately:"
+ echo "curl -X POST \"http://localhost:3000/api/meta/auth?api_token=pk_8ee8c727644d4d32b646ddcf16f2385e\" -H \"Content-Type: application/json\""
+ echo ""
+ read -p "Press Enter to continue anyway or Ctrl+C to abort..."
+fi
+
+# Try direct auth to test the endpoint
+echo "Testing direct authentication with Pipeboard..."
+AUTH_RESPONSE=$(curl -s -X POST "http://localhost:3000/api/meta/auth?api_token=pk_8ee8c727644d4d32b646ddcf16f2385e" -H "Content-Type: application/json")
+if [[ $AUTH_RESPONSE == *"loginUrl"* ]]; then
+ echo "Authentication endpoint working correctly!"
+ LOGIN_URL=$(echo $AUTH_RESPONSE | grep -o 'https://[^"]*')
+ echo "Login URL: $LOGIN_URL"
+
+ # Open the browser directly as a fallback
+ echo "Opening browser to login URL (as a fallback)..."
+ if [ "$(uname)" == "Darwin" ]; then
+ # macOS
+ open "$LOGIN_URL"
+ elif [ "$(expr substr $(uname -s) 1 5)" == "Linux" ]; then
+ # Linux
+ xdg-open "$LOGIN_URL" || firefox "$LOGIN_URL" || google-chrome "$LOGIN_URL" || echo "Could not open browser automatically"
+ else
+ # Windows or others
+ echo "Please open this URL in your browser manually: $LOGIN_URL"
+ fi
+
+ echo "After authorizing in your browser, the MCP script will retrieve the token."
+else
+ echo "Warning: Authentication endpoint test failed!"
+ echo "Response: $AUTH_RESPONSE"
+ read -p "Press Enter to continue anyway or Ctrl+C to abort..."
+fi
+
+# Run the meta-ads-mcp package
+echo "Running Meta Ads MCP..."
+python -m meta_ads_mcp
+
+echo "Meta Ads MCP server is now running."
+echo "If you had to manually authenticate, the token should be cached now."
diff --git a/meta_ads_mcp/core/pipeboard_auth.py b/meta_ads_mcp/core/pipeboard_auth.py
index 1b06bcf..84f5488 100644
--- a/meta_ads_mcp/core/pipeboard_auth.py
+++ b/meta_ads_mcp/core/pipeboard_auth.py
@@ -14,9 +14,12 @@ import logging
logger.setLevel(logging.DEBUG)
# Base URL for pipeboard API
-#PIPEBOARD_API_BASE = "https://pipeboard.co/api"
+# Using localhost:3000/api as specified in meta_auth_test.sh
PIPEBOARD_API_BASE = "http://localhost:3000/api"
+# Debug message about API base URL
+logger.info(f"Pipeboard API base URL: {PIPEBOARD_API_BASE}")
+
class TokenInfo:
"""Stores token information including expiration"""
def __init__(self, access_token: str, expires_at: str = None, token_type: str = None):
@@ -113,6 +116,10 @@ class PipeboardAuthManager:
def __init__(self):
self.api_token = os.environ.get("PIPEBOARD_API_TOKEN", "")
logger.debug(f"PipeboardAuthManager initialized with API token: {self.api_token[:5]}..." if self.api_token else "No API token")
+ if self.api_token:
+ logger.info("Pipeboard authentication enabled. Will use pipeboard.co for Meta authentication.")
+ else:
+ logger.info("Pipeboard authentication not enabled. Set PIPEBOARD_API_TOKEN environment variable to enable.")
self.token_info = None
self._load_cached_token()
@@ -202,29 +209,42 @@ class PipeboardAuthManager:
logger.error("No PIPEBOARD_API_TOKEN environment variable set")
raise ValueError("No PIPEBOARD_API_TOKEN environment variable set")
- # Pass token as URL parameter instead of Authorization header
+ # Exactly match the format used in meta_auth_test.sh
url = f"{PIPEBOARD_API_BASE}/meta/auth?api_token={self.api_token}"
headers = {
"Content-Type": "application/json"
}
- logger.debug(f"Initiating auth flow with POST request to {url}")
+ logger.info(f"Initiating auth flow with POST request to {url}")
try:
+ # Make the POST request exactly as in the working meta_auth_test.sh script
response = requests.post(url, headers=headers)
- logger.debug(f"Auth flow response status: {response.status_code}")
+ logger.info(f"Auth flow response status: {response.status_code}")
# Better error handling
if response.status_code != 200:
logger.error(f"Auth flow error: HTTP {response.status_code}")
- logger.error(f"Response content: {response.text}")
- response.raise_for_status()
+ error_text = response.text if response.text else "No response content"
+ logger.error(f"Response content: {error_text}")
+ if response.status_code == 404:
+ raise ValueError(f"Pipeboard API endpoint not found. Check if the server is running at {PIPEBOARD_API_BASE}")
+ elif response.status_code == 401:
+ raise ValueError(f"Unauthorized: Invalid API token. Check your PIPEBOARD_API_TOKEN.")
- data = response.json()
+ response.raise_for_status()
+
+ # Parse the response
+ try:
+ data = response.json()
+ logger.info(f"Received response keys: {', '.join(data.keys())}")
+ except json.JSONDecodeError:
+ logger.error(f"Could not parse JSON response: {response.text}")
+ raise ValueError(f"Invalid JSON response from auth endpoint: {response.text[:100]}")
# Log auth flow response (without sensitive information)
if 'loginUrl' in data:
- logger.debug(f"Auth flow initiated successfully with login URL: {data['loginUrl'][:30]}...")
+ logger.info(f"Auth flow initiated successfully with login URL: {data['loginUrl'][:30]}...")
else:
logger.warning(f"Auth flow response missing loginUrl field. Response keys: {', '.join(data.keys())}")
@@ -258,28 +278,34 @@ class PipeboardAuthManager:
logger.debug("Using existing valid token")
return self.token_info.access_token
- logger.debug(f"Getting new token (force_refresh={force_refresh})")
+ logger.info(f"Getting new token (force_refresh={force_refresh})")
# If force refresh or no token/expired token, get a new one from Pipeboard
try:
- # Make a request to get the token, passing API token as URL parameter
+ # Make a request to get the token, using the same URL format as initiate_auth_flow
url = f"{PIPEBOARD_API_BASE}/meta/token?api_token={self.api_token}"
headers = {
"Content-Type": "application/json"
}
- logger.debug(f"Requesting token from {url}")
+ logger.info(f"Requesting token from {url}")
response = requests.get(url, headers=headers)
- logger.debug(f"Token request response status: {response.status_code}")
+ logger.info(f"Token request response status: {response.status_code}")
# Better error handling with response content
if response.status_code != 200:
logger.error(f"Token request error: HTTP {response.status_code}")
- logger.error(f"Response content: {response.text}")
+ error_text = response.text if response.text else "No response content"
+ logger.error(f"Response content: {error_text}")
response.raise_for_status()
- data = response.json()
+ try:
+ data = response.json()
+ logger.info(f"Received token response with keys: {', '.join(data.keys())}")
+ except json.JSONDecodeError:
+ logger.error(f"Invalid JSON in token response: {response.text[:100]}")
+ return None
# Validate response data
if "access_token" not in data:
@@ -299,7 +325,7 @@ class PipeboardAuthManager:
self._save_token_to_cache()
masked_token = self.token_info.access_token[:10] + "..." + self.token_info.access_token[-5:] if self.token_info.access_token else "None"
- logger.info(f"Successfully retrieved access token from pipeboard.co: {masked_token}")
+ logger.info(f"Successfully retrieved access token: {masked_token}")
return self.token_info.access_token
except requests.RequestException as e:
status_code = e.response.status_code if hasattr(e, 'response') and e.response else None
@@ -309,12 +335,8 @@ class PipeboardAuthManager:
logger.error(f"Unauthorized: Check your PIPEBOARD_API_TOKEN. Response: {response_text}")
elif status_code == 404:
logger.error(f"No token available: You might need to complete authorization first. Response: {response_text}")
- # Provide the login URL
- try:
- auth_data = self.initiate_auth_flow()
- logger.info(f"Please visit this URL to authorize: {auth_data.get('loginUrl', 'No URL available')}")
- except Exception as auth_error:
- logger.error(f"Error initiating auth flow after 404: {auth_error}")
+ # Return None so caller can handle the auth flow
+ return None
else:
logger.error(f"Error getting access token (status {status_code}): {e}")
logger.error(f"Response content: {response_text}")
diff --git a/meta_ads_mcp/core/server.py b/meta_ads_mcp/core/server.py
index f012094..32594bb 100644
--- a/meta_ads_mcp/core/server.py
+++ b/meta_ads_mcp/core/server.py
@@ -4,9 +4,12 @@ from mcp.server.fastmcp import FastMCP
import argparse
import os
import sys
+import webbrowser
from .auth import login as login_auth
from .resources import list_resources, get_resource
from .utils import logger
+from .pipeboard_auth import pipeboard_auth_manager
+import time
# Initialize FastMCP server
mcp_server = FastMCP("meta-ads", use_consistent_tool_format=True)
@@ -78,7 +81,49 @@ def main():
# Handle login command
if args.login:
login_cli()
- else:
- # Initialize and run the server
- logger.info("Starting MCP server with stdio transport")
- mcp_server.run(transport='stdio')
\ No newline at end of file
+ return 0
+
+ # Check for Pipeboard authentication and token
+ pipeboard_api_token = os.environ.get("PIPEBOARD_API_TOKEN")
+ if pipeboard_api_token:
+ logger.info("Using Pipeboard authentication")
+ # Check for existing token
+ token = pipeboard_auth_manager.get_access_token()
+ if not token:
+ logger.info("No valid Pipeboard token found. Initiating browser-based authentication flow.")
+ print("No valid Meta token found. Opening browser for authentication...")
+ try:
+ # Initialize the auth flow and get the login URL
+ auth_data = pipeboard_auth_manager.initiate_auth_flow()
+ login_url = auth_data.get('loginUrl')
+ if login_url:
+ logger.info(f"Opening browser with login URL: {login_url}")
+ webbrowser.open(login_url)
+ print("Please authorize the application in your browser.")
+ print("After authorization, the token will be automatically retrieved.")
+ print("Waiting for authentication to complete...")
+
+ # Poll for token completion
+ max_attempts = 30 # Try for 30 * 2 = 60 seconds
+ for attempt in range(max_attempts):
+ print(f"Waiting for authentication... ({attempt+1}/{max_attempts})")
+ # Try to get the token again
+ token = pipeboard_auth_manager.get_access_token(force_refresh=True)
+ if token:
+ print("Authentication successful!")
+ break
+ time.sleep(2) # Wait 2 seconds between attempts
+
+ if not token:
+ print("Authentication timed out. Starting server anyway.")
+ print("You may need to restart the server after completing authentication.")
+ else:
+ logger.error("No login URL received from Pipeboard API")
+ print("Error: Could not get authentication URL. Check your API token.")
+ except Exception as e:
+ logger.error(f"Error initiating browser-based authentication: {e}")
+ print(f"Error: Could not start authentication: {e}")
+
+ # Initialize and run the server
+ logger.info("Starting MCP server with stdio transport")
+ mcp_server.run(transport='stdio')
\ No newline at end of file