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 Pipeboard authentication support and update README
Yves Junqueirad0f59dc9c01d
diff --git a/README.md b/README.mdindex ca88482..785a176 100644--- a/README.md+++ b/README.md@@ -223,13 +223,45 @@ Before using the MCP server, you'll need to set up a Meta Developer App:## Authentication-The Meta Ads MCP uses the OAuth 2.0 flow designed for desktop apps. When authenticating, it will:+The Meta Ads MCP supports two authentication methods:++### 1. Pipeboard Authentication (Recommended)++This method uses [Pipeboard.co](https://pipeboard.co) to manage Meta API authentication, providing longer-lived tokens and a simplified flow:++1. Set up your Pipeboard account and generate an API token from your dashboard+2. Set the `PIPEBOARD_API_TOKEN` environment variable with your token:+ ```bash+ export PIPEBOARD_API_TOKEN=your_pipeboard_token+ ```+3. Run the Meta Ads MCP normally - it will automatically detect and use Pipeboard authentication:+ ```bash+ uvx meta-ads-mcp+ ```+4. The first time you run a command, you'll be provided with a login URL to authorize with Meta++Benefits of Pipeboard authentication:+- Longer-lived tokens (60 days)+- No need to configure a Meta Developer App+- Simpler setup with just an API token+- Automatic token renewal++To test the Pipeboard authentication flow:+```bash+python test_pipeboard_auth.py --api-token YOUR_PIPEBOARD_TOKEN+```++### 2. Direct Meta OAuth (Legacy)++The traditional OAuth 2.0 flow designed for desktop apps. When authenticating, it will:1. Start a local callback server on your machine2. Open a browser window to authenticate with Meta3. Ask you to authorize the app4. Redirect back to the local server to extract and store the token securely+This method requires you to [create a Meta Developer App](#create-a-meta-developer-app) first.+## Troubleshooting and LoggingThe Meta Ads MCP includes a comprehensive logging system to help troubleshoot issues:@@ -289,14 +321,15 @@ uvx meta-ads-mcp --app-id=your_app_idThe Meta Ads MCP follows security best practices:1. Tokens are cached in a platform-specific secure location:- - Windows: `%APPDATA%\meta-ads-mcp\token_cache.json`- - macOS: `~/Library/Application Support/meta-ads-mcp/token_cache.json`- - Linux: `~/.config/meta-ads-mcp/token_cache.json`+ - Windows: `%APPDATA%\meta-ads-mcp\token_cache.json` or `%APPDATA%\meta-ads-mcp\pipeboard_token_cache.json`+ - macOS: `~/Library/Application Support/meta-ads-mcp/token_cache.json` or `~/Library/Application Support/meta-ads-mcp/pipeboard_token_cache.json`+ - Linux: `~/.config/meta-ads-mcp/token_cache.json` or `~/.config/meta-ads-mcp/pipeboard_token_cache.json`2. You do not need to provide your access token for each command; it will be automatically retrieved from the cache.3. You can set the following environment variables instead of passing them as arguments:- - `META_APP_ID`: Your Meta App ID (Client ID)+ - `META_APP_ID`: Your Meta App ID (Client ID) - for direct OAuth method+ - `PIPEBOARD_API_TOKEN`: Your Pipeboard API token - for Pipeboard authentication method## Testing@@ -335,16 +368,15 @@ If you encounter authentication issues:- Ensure you click the link and complete the authorization flow in your browser- Check that the callback server is running properly (the tool will report this)-2. When using the command line:+2. When using Pipeboard authentication:+ - Verify your `PIPEBOARD_API_TOKEN` is set correctly+ - Check if you need to complete the authorization process by visiting the provided login URL+ - Try forcing a new login: `python test_pipeboard_auth.py --force-login`++3. When using direct Meta OAuth:- Run with `--force-login` to get a fresh token: `uvx meta-ads-mcp --login --app-id YOUR_APP_ID --force-login`- Make sure the terminal has permissions to open a browser window-3. General authentication troubleshooting:- - Check that your app is properly configured in the Meta Developers portal- - Ensure your app has the necessary permissions (ads_management, ads_read, business_management)- - Verify the app's redirect URI includes `http://localhost:8888/callback`- - Try clearing the token cache (located in platform-specific directories listed in the Token Caching section)-### API ErrorsIf you receive errors from the Meta API:diff --git a/meta_ads_mcp/api.py b/meta_ads_mcp/api.pyindex eb8706a..2e329a5 100644--- a/meta_ads_mcp/api.py+++ b/meta_ads_mcp/api.py@@ -521,45 +521,40 @@ def meta_api_tool(func):if not access_token:needs_authentication = True- # Start the callback server- port = start_callback_server()+ # Check if we're using Pipeboard authentication+ using_pipeboard = bool(os.environ.get("PIPEBOARD_API_TOKEN", ""))- # Get current app ID from config- current_app_id = meta_config.get_app_id()- if not current_app_id:- return json.dumps({- "error": "No Meta App ID provided. Please provide a valid app ID via environment variable META_APP_ID or --app-id CLI argument.",- "help": "This is required for authentication with Meta Graph API."- }, indent=2)-- # Update auth manager with current app ID- auth_manager.app_id = current_app_id- print(f"Using Meta App ID from config: {current_app_id}")-- # 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()-- # Return a user-friendly authentication required response- return json.dumps({- "error": "Authentication Required",- "details": {- "message": "You need to authenticate with the Meta API before using this tool",- "action_required": "Please authenticate using the link below",- "login_url": login_url,- "markdown_link": f"[Click here to authenticate with Meta Ads API]({login_url})"- }- }, indent=2)-- # Call the original function- try:- result = await func(**kwargs)-- # If authentication is needed after the call (e.g., token was invalidated)- if needs_authentication:- # Start the callback server+ if using_pipeboard:+ # For Pipeboard, we use a different authentication flow+ try:+ # Here we'd import dynamically to avoid circular imports+ from .core.pipeboard_auth import pipeboard_auth_manager++ # Initiate the Pipeboard auth flow+ auth_data = pipeboard_auth_manager.initiate_auth_flow()+ login_url = auth_data.get("loginUrl")++ # Return a user-friendly authentication required response for Pipeboard+ return json.dumps({+ "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"+ }+ }, indent=2)+ except Exception as e:+ return json.dumps({+ "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"+ }+ }, indent=2)+ else:+ # For direct Meta auth, start the callback serverport = start_callback_server()# Get current app ID from config@@ -570,6 +565,7 @@ def meta_api_tool(func):"help": "This is required for authentication with Meta Graph API."}, indent=2)+ # Update auth manager with current app IDauth_manager.app_id = current_app_idprint(f"Using Meta App ID from config: {current_app_id}")@@ -579,21 +575,94 @@ def meta_api_tool(func):# Generate the authentication URLlogin_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)+ # Return a user-friendly authentication required response+ return json.dumps({+ "error": "Authentication Required",+ "details": {+ "message": "You need to authenticate with the Meta API before using this tool",+ "action_required": "Please authenticate using the link below",+ "login_url": login_url,+ "markdown_link": f"[Click here to authenticate with Meta Ads API]({login_url})",+ "authentication_method": "meta_oauth"+ }+ }, indent=2)++ # Call the original function+ try:+ result = await func(**kwargs)++ # If authentication is needed after the call (e.g., token was invalidated)+ if needs_authentication:+ # Check if we're using Pipeboard authentication+ using_pipeboard = bool(os.environ.get("PIPEBOARD_API_TOKEN", ""))- return json.dumps(response, indent=2)+ if using_pipeboard:+ # For Pipeboard, we use a different authentication flow+ try:+ # Here we'd import dynamically to avoid circular imports+ from .core.pipeboard_auth import pipeboard_auth_manager++ # Initiate the Pipeboard auth flow+ auth_data = pipeboard_auth_manager.initiate_auth_flow()+ login_url = auth_data.get("loginUrl")++ # 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,+ "markdown_link": f"[Click here to re-authenticate with Meta Ads API via Pipeboard]({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.",+ "authentication_method": "pipeboard",+ "note": "After authenticating, the token will be automatically saved."+ }++ return json.dumps(response, indent=2)+ except Exception as e:+ return json.dumps({+ "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"+ }+ }, indent=2)+ else:+ # For direct Meta auth, start the callback server+ port = start_callback_server()++ # Get current app ID from config+ current_app_id = meta_config.get_app_id()+ if not current_app_id:+ return json.dumps({+ "error": "No Meta App ID provided. Please provide a valid app ID via environment variable META_APP_ID or --app-id CLI argument.",+ "help": "This is required for authentication with Meta Graph API."+ }, indent=2)++ auth_manager.app_id = current_app_id+ print(f"Using Meta App ID from config: {current_app_id}")++ # 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.",+ "authentication_method": "meta_oauth",+ "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)# If result is a string (JSON), check for app ID errors and improve themif isinstance(result, str):diff --git a/meta_ads_mcp/core/auth.py b/meta_ads_mcp/core/auth.pyindex e66d7b2..1c7b66c 100644--- a/meta_ads_mcp/core/auth.py+++ b/meta_ads_mcp/core/auth.py@@ -18,6 +18,9 @@ from .callback_server import (update_confirmation)+# Import the new Pipeboard authentication+from .pipeboard_auth import pipeboard_auth_manager+# Auth constantsAUTH_SCOPE = "ads_management,ads_read,business_management"AUTH_REDIRECT_URI = "http://localhost:8888/callback"@@ -123,7 +126,10 @@ class AuthManager:self.app_id = app_idself.redirect_uri = redirect_uriself.token_info = None- self._load_cached_token()+ # Check for Pipeboard token first+ self.use_pipeboard = bool(os.environ.get("PIPEBOARD_API_TOKEN", ""))+ if not self.use_pipeboard:+ self._load_cached_token()def _get_token_cache_path(self) -> pathlib.Path:"""Get the platform-specific path for token cache file"""@@ -154,14 +160,14 @@ class AuthManager:# Check if token is expiredif self.token_info.is_expired():- print("Cached token is expired")+ logger.info("Cached token is expired")self.token_info = Nonereturn False- print(f"Loaded cached token (expires in {(self.token_info.created_at + self.token_info.expires_in) - int(time.time())} seconds)")+ logger.info(f"Loaded cached token (expires in {(self.token_info.created_at + self.token_info.expires_in) - int(time.time())} seconds)")return Trueexcept Exception as e:- print(f"Error loading cached token: {e}")+ logger.error(f"Error loading cached token: {e}")return Falsedef _save_token_to_cache(self) -> None:@@ -174,9 +180,9 @@ class AuthManager:try:with open(cache_path, "w") as f:json.dump(self.token_info.serialize(), f)- print(f"Token cached at: {cache_path}")+ logger.info(f"Token cached at: {cache_path}")except Exception as e:- print(f"Error saving token to cache: {e}")+ logger.error(f"Error saving token to cache: {e}")def get_auth_url(self) -> str:"""Generate the Facebook OAuth URL for desktop app flow"""@@ -198,6 +204,12 @@ class AuthManager:Returns:Access token if successful, None otherwise"""+ # If Pipeboard auth is available, use that instead+ if self.use_pipeboard:+ logger.info("Using Pipeboard authentication")+ return pipeboard_auth_manager.get_access_token(force_refresh=force_refresh)++ # Otherwise, use the original OAuth flow# Check if we already have a valid tokenif not force_refresh and self.token_info and not self.token_info.is_expired():return self.token_info.access_token@@ -212,7 +224,7 @@ class AuthManager:auth_url = self.get_auth_url()# Open browser with auth URL- print(f"Opening browser with URL: {auth_url}")+ logger.info(f"Opening browser with URL: {auth_url}")webbrowser.open(auth_url)# We don't wait for the token here anymore@@ -227,6 +239,10 @@ class AuthManager:Returns:Access token if available, None otherwise"""+ # If using Pipeboard, always delegate to the Pipeboard auth manager+ if self.use_pipeboard:+ return pipeboard_auth_manager.get_access_token()+if not self.token_info or self.token_info.is_expired():return None@@ -234,8 +250,13 @@ class AuthManager:def invalidate_token(self) -> None:"""Invalidate the current token, usually because it has expired or is invalid"""+ # If using Pipeboard, delegate to the Pipeboard auth manager+ if self.use_pipeboard:+ pipeboard_auth_manager.invalidate_token()+ return+if self.token_info:- print(f"Invalidating token: {self.token_info.access_token[:10]}...")+ logger.info(f"Invalidating token: {self.token_info.access_token[:10]}...")self.token_info = None# Signal that authentication is needed@@ -247,12 +268,12 @@ class AuthManager:cache_path = self._get_token_cache_path()if cache_path.exists():os.remove(cache_path)- print(f"Removed cached token file: {cache_path}")+ logger.info(f"Removed cached token file: {cache_path}")except Exception as e:- print(f"Error removing cached token: {e}")+ logger.error(f"Error removing cached token file: {e}")def clear_token(self) -> None:- """Clear the current token and remove from cache"""+ """Alias for invalidate_token for consistency with other APIs"""self.invalidate_token()@@ -443,4 +464,14 @@ def login():# Initialize auth manager with a placeholder - will be updated at runtimeMETA_APP_ID = os.environ.get("META_APP_ID", "YOUR_META_APP_ID")++# Only show warnings about missing META_APP_ID/META_APP_SECRET when not using Pipeboard+if not os.environ.get("PIPEBOARD_API_TOKEN"):+ # Log warnings about missing environment variables+ if META_APP_ID == "YOUR_META_APP_ID":+ logger.warning("META_APP_ID environment variable is not set. Authentication will not work properly.")++ if not os.environ.get("META_APP_SECRET"):+ logger.warning("META_APP_SECRET environment variable is not set. Long-lived token exchange will not work.")+auth_manager = AuthManager(META_APP_ID)\ No newline at end of filediff --git a/meta_ads_mcp/core/authentication.py b/meta_ads_mcp/core/authentication.pyindex 4574137..fb42acf 100644--- a/meta_ads_mcp/core/authentication.py+++ b/meta_ads_mcp/core/authentication.py@@ -2,10 +2,12 @@import jsonimport asyncio+import osfrom .api import meta_api_toolfrom .auth import start_callback_server, auth_manager, get_current_access_tokenfrom .server import mcp_serverfrom .utils import logger, META_APP_SECRET+from .pipeboard_auth import pipeboard_auth_manager@mcp_server.tool()@@ -19,54 +21,102 @@ async def get_login_link(access_token: str = None) -> str:Returns:A clickable resource link for Meta authentication"""- # Check if we have a cached token- cached_token = auth_manager.get_access_token()- token_status = "No token" if not cached_token else "Valid token"+ # Check if we're using pipeboard authentication+ using_pipeboard = bool(os.environ.get("PIPEBOARD_API_TOKEN", ""))- # If we already have a valid token and none was provided, just return success- if cached_token and not access_token:- logger.info("get_login_link called with existing valid token")- return json.dumps({- "message": "Already authenticated",+ if using_pipeboard:+ # Handle Pipeboard authentication+ # Check if we have a cached token+ cached_token = pipeboard_auth_manager.get_access_token()+ token_status = "No token" if not cached_token else "Valid token"++ # If we already have a valid token and none was provided, just return success+ if cached_token and not access_token:+ logger.info("get_login_link called with existing valid Pipeboard token")+ return json.dumps({+ "message": "Already authenticated with Pipeboard",+ "token_status": token_status,+ "token_preview": cached_token[:10] + "..." if cached_token else None,+ "authentication_method": "pipeboard"+ }, indent=2)++ # Initiate the auth flow via Pipeboard+ try:+ auth_data = pipeboard_auth_manager.initiate_auth_flow()+ login_url = auth_data.get("loginUrl")++ # Return a special format that helps the LLM format the response properly+ response = {+ "login_url": login_url,+ "token_status": token_status,+ "markdown_link": f"[Click here to authenticate with Meta Ads via Pipeboard]({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.",+ "authentication_method": "pipeboard",+ "token_duration": "Approximately 60 days",+ "note": "After authenticating, the token will be automatically saved."+ }++ return json.dumps(response, indent=2)+ except Exception as e:+ logger.error(f"Error initiating Pipeboard auth flow: {e}")+ return json.dumps({+ "error": f"Failed to initiate Pipeboard authentication: {str(e)}",+ "message": "Please check your PIPEBOARD_API_TOKEN environment variable.",+ "authentication_method": "pipeboard"+ }, indent=2)+ else:+ # Original Meta authentication flow+ # Check if we have a cached token+ cached_token = auth_manager.get_access_token()+ token_status = "No token" if not cached_token else "Valid token"++ # If we already have a valid token and none was provided, just return success+ if cached_token and not access_token:+ logger.info("get_login_link called with existing valid token")+ return json.dumps({+ "message": "Already authenticated",+ "token_status": token_status,+ "token_preview": cached_token[:10] + "...",+ "created_at": auth_manager.token_info.created_at if hasattr(auth_manager, "token_info") else None,+ "expires_in": auth_manager.token_info.expires_in if hasattr(auth_manager, "token_info") else None,+ "authentication_method": "meta_oauth"+ }, indent=2)++ # 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}")++ # Check if we can exchange for long-lived tokens+ token_exchange_supported = bool(META_APP_SECRET)+ token_duration = "60 days" if token_exchange_supported else "1-2 hours"++ # Return a special format that helps the LLM format the response properly+ response = {+ "login_url": login_url,"token_status": token_status,- "token_preview": cached_token[:10] + "...",- "created_at": auth_manager.token_info.created_at if hasattr(auth_manager, "token_info") else None,- "expires_in": auth_manager.token_info.expires_in if hasattr(auth_manager, "token_info") else None- }, indent=2)-- # 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}")-- # Check if we can exchange for long-lived tokens- token_exchange_supported = bool(META_APP_SECRET)- token_duration = "60 days" if token_exchange_supported else "1-2 hours"-- # Return a special format that helps the LLM format the response properly- response = {- "login_url": login_url,- "token_status": token_status,- "server_status": f"Callback server running on port {port}",- "markdown_link": f"[Click here to authenticate with Meta Ads]({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.",- "token_exchange": "enabled" if token_exchange_supported else "disabled",- "token_duration": token_duration,- "token_exchange_message": f"Your authentication token will be valid for approximately {token_duration}." +- (" Long-lived token exchange is enabled." if token_exchange_supported else- " To enable long-lived tokens (60 days), set the META_APP_SECRET environment variable."),- "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)\ No newline at end of file+ "server_status": f"Callback server running on port {port}",+ "markdown_link": f"[Click here to authenticate with Meta Ads]({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.",+ "token_exchange": "enabled" if token_exchange_supported else "disabled",+ "token_duration": token_duration,+ "authentication_method": "meta_oauth",+ "token_exchange_message": f"Your authentication token will be valid for approximately {token_duration}." ++ (" Long-lived token exchange is enabled." if token_exchange_supported else+ " To enable long-lived tokens (60 days), set the META_APP_SECRET environment variable."),+ "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)\ No newline at end of filediff --git a/meta_ads_mcp/core/pipeboard_auth.py b/meta_ads_mcp/core/pipeboard_auth.pynew file mode 100644index 0000000..5dd77c8--- /dev/null+++ b/meta_ads_mcp/core/pipeboard_auth.py@@ -0,0 +1,380 @@+"""Authentication with Meta Ads API via pipeboard.co."""++import os+import json+import time+import requests+from pathlib import Path+import platform+from typing import Optional, Dict, Any+from .utils import logger++# Enable more detailed logging+import logging+logger.setLevel(logging.DEBUG)++# Base URL for pipeboard API+#PIPEBOARD_API_BASE = "https://pipeboard.co/api"+PIPEBOARD_API_BASE = "http://localhost:3000/api"++class TokenInfo:+ """Stores token information including expiration"""+ def __init__(self, access_token: str, expires_at: str = None, token_type: str = None):+ self.access_token = access_token+ self.expires_at = expires_at+ self.token_type = token_type+ self.created_at = int(time.time())+ logger.debug(f"TokenInfo created. Expires at: {expires_at if expires_at else 'Not specified'}")++ def is_expired(self) -> bool:+ """Check if the token is expired"""+ if not self.expires_at:+ logger.debug("No expiration date set for token, assuming not expired")+ return False # If no expiration is set, assume it's not expired++ # Parse ISO 8601 date format to timestamp+ try:+ # Convert the expires_at string to a timestamp+ # Format is like "2023-12-31T23:59:59.999Z" or "2023-12-31T23:59:59.999+00:00"+ from datetime import datetime++ # Remove the Z suffix if present and handle +00:00 format+ expires_at_str = self.expires_at+ if expires_at_str.endswith('Z'):+ expires_at_str = expires_at_str[:-1] # Remove Z++ # Handle microseconds if present+ if '.' in expires_at_str:+ datetime_format = "%Y-%m-%dT%H:%M:%S.%f"+ else:+ datetime_format = "%Y-%m-%dT%H:%M:%S"++ # Handle timezone offset+ timezone_offset = "+00:00"+ if "+" in expires_at_str:+ expires_at_str, timezone_offset = expires_at_str.split("+")+ timezone_offset = "+" + timezone_offset++ # Parse the datetime without timezone info+ expires_datetime = datetime.strptime(expires_at_str, datetime_format)++ # Convert to timestamp (assume UTC)+ expires_timestamp = expires_datetime.timestamp()+ current_time = time.time()++ # Check if token is expired and log result+ is_expired = current_time > expires_timestamp+ time_diff = expires_timestamp - current_time+ if is_expired:+ logger.debug(f"Token is expired! Current time: {datetime.fromtimestamp(current_time)}, "+ f"Expires at: {datetime.fromtimestamp(expires_timestamp)}, "+ f"Expired {abs(time_diff):.0f} seconds ago")+ else:+ logger.debug(f"Token is still valid. Expires at: {datetime.fromtimestamp(expires_timestamp)}, "+ f"Time remaining: {time_diff:.0f} seconds")++ return is_expired+ except Exception as e:+ logger.error(f"Error parsing expiration date: {e}")+ # Log the actual value to help diagnose format issues+ logger.error(f"Invalid expires_at value: '{self.expires_at}'")+ # Log detailed error information+ import traceback+ logger.error(f"Traceback: {traceback.format_exc()}")+ return False # If we can't parse the date, assume it's not expired++ def serialize(self) -> Dict[str, Any]:+ """Convert to a dictionary for storage"""+ return {+ "access_token": self.access_token,+ "expires_at": self.expires_at,+ "token_type": self.token_type,+ "created_at": self.created_at+ }++ @classmethod+ def deserialize(cls, data: Dict[str, Any]) -> 'TokenInfo':+ """Create from a stored dictionary"""+ logger.debug(f"Deserializing token data with keys: {', '.join(data.keys())}")+ if 'expires_at' in data:+ logger.debug(f"Token expires_at from cache: {data['expires_at']}")++ token = cls(+ access_token=data.get("access_token", ""),+ expires_at=data.get("expires_at"),+ token_type=data.get("token_type")+ )+ token.created_at = data.get("created_at", int(time.time()))+ return token+++class PipeboardAuthManager:+ """Manages authentication with Meta APIs via pipeboard.co"""+ 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")+ self.token_info = None+ self._load_cached_token()++ def _get_token_cache_path(self) -> Path:+ """Get the platform-specific path for token cache file"""+ if platform.system() == "Windows":+ base_path = Path(os.environ.get("APPDATA", ""))+ elif platform.system() == "Darwin": # macOS+ base_path = Path.home() / "Library" / "Application Support"+ else: # Assume Linux/Unix+ base_path = Path.home() / ".config"++ # Create directory if it doesn't exist+ cache_dir = base_path / "meta-ads-mcp"+ cache_dir.mkdir(parents=True, exist_ok=True)++ cache_path = cache_dir / "pipeboard_token_cache.json"+ logger.debug(f"Token cache path: {cache_path}")+ return cache_path++ def _load_cached_token(self) -> bool:+ """Load token from cache if available"""+ cache_path = self._get_token_cache_path()++ if not cache_path.exists():+ logger.debug(f"Token cache file not found at {cache_path}")+ return False++ try:+ with open(cache_path, "r") as f:+ logger.debug(f"Reading token cache from {cache_path}")+ data = json.load(f)+ self.token_info = TokenInfo.deserialize(data)++ # Log token details (partial token for security)+ masked_token = self.token_info.access_token[:10] + "..." + self.token_info.access_token[-5:] if self.token_info.access_token else "None"+ logger.debug(f"Loaded token: {masked_token}")++ # Check if token is expired+ if self.token_info.is_expired():+ logger.info("Cached token is expired")+ self.token_info = None+ return False++ logger.info(f"Loaded cached token (expires at {self.token_info.expires_at})")+ return True+ except json.JSONDecodeError as e:+ logger.error(f"Error parsing token cache file: {e}")+ logger.debug("Token cache file might be corrupted, trying to read raw content")+ try:+ with open(cache_path, "r") as f:+ raw_content = f.read()+ logger.debug(f"Raw cache file content (first 100 chars): {raw_content[:100]}")+ except Exception as e2:+ logger.error(f"Could not read raw cache file: {e2}")+ return False+ except Exception as e:+ logger.error(f"Error loading cached token: {e}")+ return False++ def _save_token_to_cache(self) -> None:+ """Save token to cache file"""+ if not self.token_info:+ logger.debug("No token to save to cache")+ return++ cache_path = self._get_token_cache_path()++ try:+ token_data = self.token_info.serialize()+ logger.debug(f"Saving token to cache. Expires at: {token_data.get('expires_at')}")++ with open(cache_path, "w") as f:+ json.dump(token_data, f)+ logger.info(f"Token cached at: {cache_path}")+ except Exception as e:+ logger.error(f"Error saving token to cache: {e}")++ def initiate_auth_flow(self) -> Dict[str, str]:+ """+ Initiate the Meta OAuth flow via pipeboard.co++ Returns:+ Dict with loginUrl and status info+ """+ if not self.api_token:+ 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"+ headers = {+ "Authorization": f"Bearer {self.api_token}",+ "Content-Type": "application/json"+ }++ logger.debug(f"Initiating auth flow with POST request to {url}")++ try:+ response = requests.post(url, headers=headers)+ logger.debug(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()++ data = response.json()++ # Log auth flow response (without sensitive information)+ if 'loginUrl' in data:+ logger.debug(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())}")++ return data+ except requests.exceptions.ConnectionError as e:+ logger.error(f"Connection error to Pipeboard: {e}")+ logger.debug(f"Attempting to connect to: {PIPEBOARD_API_BASE}")+ raise+ except requests.exceptions.Timeout as e:+ logger.error(f"Timeout connecting to Pipeboard: {e}")+ raise+ except requests.exceptions.RequestException as e:+ logger.error(f"Error initiating auth flow: {e}")+ raise+ except Exception as e:+ logger.error(f"Unexpected error initiating auth flow: {e}")+ raise++ def get_access_token(self, force_refresh: bool = False) -> Optional[str]:+ """+ Get the current access token, refreshing if necessary or if forced++ Args:+ force_refresh: Force token refresh even if cached token exists++ Returns:+ Access token if available, None otherwise+ """+ # Check if we already have a valid token+ if not force_refresh and self.token_info and not self.token_info.is_expired():+ logger.debug("Using existing valid token")+ return self.token_info.access_token++ logger.debug(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+ url = f"{PIPEBOARD_API_BASE}/meta/token"+ headers = {+ "Authorization": f"Bearer {self.api_token}",+ "Content-Type": "application/json"+ }++ logger.debug(f"Requesting token from {url}")++ response = requests.get(url, headers=headers)+ logger.debug(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}")+ response.raise_for_status()++ data = response.json()++ # Validate response data+ if "access_token" not in data:+ logger.error(f"No access_token in response. Response keys: {', '.join(data.keys())}")+ if "error" in data:+ logger.error(f"Error in response: {data['error']}")+ return None++ # Create new token info+ self.token_info = TokenInfo(+ access_token=data.get("access_token"),+ expires_at=data.get("expires_at"),+ token_type=data.get("token_type", "bearer")+ )++ # Save to cache+ 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}")+ 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+ response_text = e.response.text if hasattr(e, 'response') and e.response else "No response"++ if status_code == 401:+ 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}")+ else:+ logger.error(f"Error getting access token (status {status_code}): {e}")+ logger.error(f"Response content: {response_text}")+ return None+ except Exception as e:+ logger.error(f"Unexpected error getting access token: {e}")+ return None++ def invalidate_token(self) -> None:+ """Invalidate the current token, usually because it has expired or is invalid"""+ if self.token_info:+ logger.info(f"Invalidating token: {self.token_info.access_token[:10]}...")+ self.token_info = None++ # Remove the cached token file+ try:+ cache_path = self._get_token_cache_path()+ if cache_path.exists():+ os.remove(cache_path)+ logger.info(f"Removed cached token file: {cache_path}")+ else:+ logger.debug(f"No token cache file to remove: {cache_path}")+ except Exception as e:+ logger.error(f"Error removing cached token file: {e}")+ else:+ logger.debug("No token to invalidate")++ def test_token_validity(self) -> bool:+ """+ Test if the current token is valid with the Meta Graph API++ Returns:+ True if valid, False otherwise+ """+ if not self.token_info or not self.token_info.access_token:+ logger.debug("No token to test")+ return False++ try:+ # Make a simple request to the /me endpoint to test the token+ META_GRAPH_API_VERSION = "v20.0"+ url = f"https://graph.facebook.com/{META_GRAPH_API_VERSION}/me"+ headers = {"Authorization": f"Bearer {self.token_info.access_token}"}++ logger.debug(f"Testing token validity with request to {url}")+ response = requests.get(url, headers=headers)++ if response.status_code == 200:+ data = response.json()+ logger.debug(f"Token is valid. User ID: {data.get('id')}")+ return True+ else:+ logger.error(f"Token validation failed with status {response.status_code}")+ logger.error(f"Response: {response.text}")+ return False+ except Exception as e:+ logger.error(f"Error testing token validity: {e}")+ return False+++# Create singleton instance+pipeboard_auth_manager = PipeboardAuthManager()\ No newline at end of filediff --git a/meta_ads_mcp/core/utils.py b/meta_ads_mcp/core/utils.pyindex 2dd325e..855f80a 100644--- a/meta_ads_mcp/core/utils.py+++ b/meta_ads_mcp/core/utils.py@@ -17,11 +17,16 @@ import platformMETA_APP_ID = os.environ.get("META_APP_ID", "")META_APP_SECRET = os.environ.get("META_APP_SECRET", "")-# Print warning if Meta app credentials are not configured-if not META_APP_ID:- print("WARNING: META_APP_ID environment variable is not set. Authentication will not work properly.")-if not META_APP_SECRET:- print("WARNING: META_APP_SECRET environment variable is not set. Long-lived token exchange will not work.")+# Only show warnings about Meta credentials if we're not using Pipeboard+# Check for Pipeboard token in environment+using_pipeboard = bool(os.environ.get("PIPEBOARD_API_TOKEN", ""))++# Print warning if Meta app credentials are not configured and not using Pipeboard+if not using_pipeboard:+ if not META_APP_ID:+ print("WARNING: META_APP_ID environment variable is not set. Authentication will not work properly.")+ if not META_APP_SECRET:+ print("WARNING: META_APP_SECRET environment variable is not set. Long-lived token exchange will not work.")# Configure logging to filedef setup_logging():@@ -55,6 +60,7 @@ def setup_logging():# Log startup informationlogger.info(f"Logging initialized. Log file: {log_file}")logger.info(f"Platform: {platform.system()} {platform.release()}")+ logger.info(f"Using Pipeboard authentication: {using_pipeboard}")return loggerdiff --git a/pyproject.toml b/pyproject.tomlindex 358e434..8132a11 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -25,6 +25,7 @@ dependencies = ["requests>=2.32.3","Pillow>=10.0.0","pathlib>=1.0.1",+ "python-dateutil>=2.8.2",][project.urls]diff --git a/test_pipeboard_auth.py b/test_pipeboard_auth.pynew file mode 100644index 0000000..2e7a097--- /dev/null+++ b/test_pipeboard_auth.py@@ -0,0 +1,239 @@+#!/usr/bin/env python+"""+Test script for Meta Ads MCP authentication flow via Pipeboard.co.+This script shows how to authenticate with the Meta Ads API via Pipeboard.co and run a simple command.+"""++import os+import sys+import json+import asyncio+import argparse+import requests+import logging+import inspect++# Set up logging+logging.basicConfig(+ level=logging.DEBUG,+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'+)+logger = logging.getLogger("meta_ads_debug")++# Import only pipeboard auth manager to avoid META_APP_ID/META_APP_SECRET warnings+from meta_ads_mcp.core.pipeboard_auth import pipeboard_auth_manager, PIPEBOARD_API_BASE+from meta_ads_mcp.api import get_ad_accounts++# Define Meta Graph API base URL for testing access token directly+META_GRAPH_API_VERSION = "v20.0"+META_GRAPH_API_BASE = f"https://graph.facebook.com/{META_GRAPH_API_VERSION}"++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...")++ # Make a direct request to /me endpoint to check token+ me_url = f"{META_GRAPH_API_BASE}/me"+ try:+ headers = {"Authorization": f"Bearer {access_token}"}+ response = requests.get(me_url, headers=headers)+ logger.debug(f"GET {me_url} response status: {response.status_code}")++ if response.status_code == 200:+ user_data = response.json()+ logger.debug(f"Token is valid. User ID: {user_data.get('id')}, Name: {user_data.get('name', 'N/A')}")+ return True+ else:+ logger.error(f"Token validation failed with status {response.status_code}")+ logger.error(f"Response: {response.text}")+ return False+ except Exception as e:+ logger.error(f"Error validating token directly: {e}")+ return False++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"+ headers = {+ "Authorization": f"Bearer {api_token}",+ "Content-Type": "application/json"+ }++ try:+ response = requests.get(url, headers=headers)+ logger.debug(f"GET {url} response status: {response.status_code}")++ if response.status_code == 200:+ data = response.json()+ # Mask token for logging+ if "access_token" in data:+ display_token = data["access_token"][:10] + "..." + data["access_token"][-5:]+ logger.debug(f"Token received: {display_token}")+ logger.debug(f"Token expires_at: {data.get('expires_at', 'Not provided')}")+ logger.debug(f"Token type: {data.get('token_type', 'Not provided')}")+ else:+ logger.error("No access_token in response")++ return data+ else:+ logger.error(f"Pipeboard token endpoint failed with status {response.status_code}")+ logger.error(f"Response: {response.text}")+ return None+ except Exception as e:+ logger.error(f"Error calling Pipeboard token endpoint: {e}")+ return None++async def inspect_api_call_params(token):+ """Inspect what parameters are being sent to the Meta API in get_ad_accounts"""+ # This is using reflection to get source code of the get_ad_accounts function+ try:+ source = inspect.getsource(get_ad_accounts)+ logger.debug(f"get_ad_accounts function source:\n{source}")+ 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):+ """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.")++ # Set the Pipeboard API token if provided+ if api_token:+ os.environ["PIPEBOARD_API_TOKEN"] = api_token+ logger.debug(f"Using provided Pipeboard API token: {api_token[:5]}...")+ else:+ # Check for token in environment+ api_token = os.environ.get("PIPEBOARD_API_TOKEN")+ if not api_token:+ logger.error("No Pipeboard API token provided. Please set PIPEBOARD_API_TOKEN environment variable or use --api-token")+ return+ logger.debug(f"Using Pipeboard API token from environment: {api_token[:5]}...")++ # Debug Pipeboard API URL+ logger.debug(f"Using Pipeboard API base URL: {PIPEBOARD_API_BASE}")++ # Force authentication if requested+ if force_login:+ logger.debug("Forcing new authentication...")+ try:+ # Invalidate any existing token first+ pipeboard_auth_manager.invalidate_token()+ logger.debug("Existing token invalidated")++ # Initiate the auth flow+ auth_data = pipeboard_auth_manager.initiate_auth_flow()+ login_url = auth_data.get("loginUrl")++ logger.debug(f"Auth flow initiated. Response: {auth_data}")+ print(f"\nPlease visit this URL to authorize with Meta: {login_url}")+ input("Press Enter after completing authorization in your browser...")+ except Exception as e:+ logger.error(f"Error initiating auth flow: {e}")+ return++ print("Getting access token (using cached token if available)...")++ # Debug the token endpoint directly+ pipeboard_token_data = await debug_pipeboard_token_endpoint(api_token)++ # Get token from auth manager+ token = pipeboard_auth_manager.get_access_token()++ if token:+ # Mask token for display+ masked_token = token[:10] + "..." + token[-5:]+ print(f"Access token obtained: {masked_token}")++ # Check token validity directly with Graph API+ logger.debug("Validating token directly with Meta Graph API...")+ token_valid = await test_token_manually(token)++ if not token_valid:+ print("\n⚠️ Token validation failed with Meta Graph API!")+ print("This may explain the 'Authentication Required' error.")++ # Check if token is from cache or fresh from API+ token_source = "cache" if pipeboard_auth_manager.token_info else "API"+ print(f"Token was obtained from: {token_source}")++ if token_source == "cache":+ print("\nTrying to force token refresh...")+ # Try to force refresh the token+ token = pipeboard_auth_manager.get_access_token(force_refresh=True)+ if token:+ masked_token = token[:10] + "..." + token[-5:]+ print(f"New access token obtained: {masked_token}")+ token_valid = await test_token_manually(token)+ if not token_valid:+ print("⚠️ New token also invalid!")++ # Log token info+ if pipeboard_auth_manager.token_info:+ logger.debug(f"Token info - expires_at: {pipeboard_auth_manager.token_info.expires_at}")+ logger.debug(f"Token is_expired(): {pipeboard_auth_manager.token_info.is_expired()}")++ # Inspect API call parameters+ await inspect_api_call_params(token)++ # Test the token by getting ad accounts+ print("\nFetching ad accounts to test token...")+ logger.debug("Calling get_ad_accounts with token...")+ try:+ ad_accounts_json = await get_ad_accounts(token)+ logger.debug(f"API Response raw: {ad_accounts_json[:500]}...")++ try:+ ad_accounts = json.loads(ad_accounts_json)++ # 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)}")++ # 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.")++ return++ if isinstance(ad_accounts, list):+ print(f"Success! Found {len(ad_accounts)} ad accounts.")+ for account in ad_accounts[:3]: # Show first 3 accounts only+ print(f" - {account.get('name')} (ID: {account.get('id')})")+ if len(ad_accounts) > 3:+ print(f" ... and {len(ad_accounts) - 3} more")+ except json.JSONDecodeError:+ print("Error parsing response from Meta API")+ print(f"Raw response: {ad_accounts_json[:100]}...")+ logger.error(f"JSON parse error on API response: {ad_accounts_json}")+ return+ except Exception as e:+ print(f"Exception when calling Meta API: {e}")+ logger.exception("Exception when calling Meta API")+ else:+ print("Failed to obtain access token. Authentication failed.")+ print("Please ensure you've completed the authorization process in your browser.")+++if __name__ == "__main__":+ parser = argparse.ArgumentParser(description="Test Meta Ads MCP authentication via Pipeboard.co")+ 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")++ 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