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 logging and configuration management in Meta Ads MCP

Yves Junqueira2906d346e879
diff --git a/README.md b/README.md
index 72f428d..f3d3a6b 100644
--- a/README.md
+++ b/README.md
@@ -199,42 +199,73 @@ The Meta Ads MCP uses the OAuth 2.0 flow designed for desktop apps. When authent
3. Ask you to authorize the app
4. Redirect back to the local server to extract and store the token securely
-### Authentication Methods
+## Troubleshooting and Logging
-There are two ways to authenticate with the Meta Ads API:
+The Meta Ads MCP includes a comprehensive logging system to help troubleshoot issues:
-1. **LLM/MCP Interface Authentication** (Recommended)
-
- When using the Meta Ads MCP through an LLM interface (like Claude), simply use any Meta Ads function. If you're not authenticated, the system will automatically provide a clickable Markdown link to complete the authentication flow.
+### Log Location
- ```
- [Click here to authenticate with Meta Ads API](https://www.facebook.com/dialog/oauth?...)
- ```
+Log files are stored in a platform-specific location:
- Just click the link, complete the authorization in your browser, and the token will be automatically captured and stored.
+- **macOS**: `~/Library/Application Support/meta-ads-mcp/meta_ads_debug.log`
+- **Windows**: `%APPDATA%\meta-ads-mcp\meta_ads_debug.log`
+- **Linux**: `~/.config/meta-ads-mcp/meta_ads_debug.log`
-2. **Command Line Authentication**
+### Common Issues
- You can authenticate directly from the command line:
+#### App ID Issues
- ```bash
- uvx meta-ads-mcp --login --app-id YOUR_APP_ID
- ```
+If you encounter errors like `(#200) Provide valid app ID`, check the following:
-### Token Caching
+1. Ensure you've set up a Meta Developer App correctly
+2. Verify that you're passing the correct App ID using one of these methods:
+ - Set the `META_APP_ID` environment variable: `export META_APP_ID=your_app_id`
+ - Pass it as a command-line argument: `meta-ads-mcp --app-id your_app_id`
-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`
+#### Authentication Errors
-You do not need to provide your access token for each command; it will be automatically retrieved from the cache.
+Authentication errors can be tracked in the log file. Check for:
+- Token expiration issues
+- App permission problems
+- Connection errors
-## Environment Variables
+### Debugging Command
-You can set the following environment variables instead of passing them as arguments:
+For specific image download issues, use the built-in diagnostic tool:
-- `META_APP_ID`: Your Meta App ID (Client ID)
+```python
+# Using direct tool call
+mcp_meta_ads_debug_image_download(ad_id="your_ad_id")
+```
+
+This will give you detailed information about the download process and potential issues.
+
+## Running with Different App IDs
+
+If you need to use different Meta App IDs for different purposes:
+
+```bash
+# Using environment variable
+export META_APP_ID=your_app_id
+uvx meta-ads-mcp
+
+# Or using command line argument
+uvx meta-ads-mcp --app-id=your_app_id
+```
+
+## Privacy and Security
+
+The 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`
+
+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)
## Testing
diff --git a/meta_ads_mcp/api.py b/meta_ads_mcp/api.py
index 082645a..eb8706a 100644
--- a/meta_ads_mcp/api.py
+++ b/meta_ads_mcp/api.py
@@ -26,15 +26,8 @@ META_GRAPH_API_VERSION = "v20.0"
META_GRAPH_API_BASE = f"https://graph.facebook.com/{META_GRAPH_API_VERSION}"
USER_AGENT = "meta-ads-mcp/1.0"
-# Meta App configuration - Using a placeholder app ID. This will be overridden by:
-# 1. Command line arguments
-# 2. Environment variables
-# 3. User input during runtime
-META_APP_ID = "YOUR_META_APP_ID" # Will be replaced at runtime
-
-# Try to load from environment variable
-if os.environ.get("META_APP_ID"):
- META_APP_ID = os.environ.get("META_APP_ID")
+# Meta App configuration
+META_APP_ID = os.environ.get("META_APP_ID", "") # Default to empty string
# Auth constants
AUTH_SCOPE = "ads_management,ads_read,business_management"
@@ -55,6 +48,35 @@ callback_server_port = None
# Global token container for communication between threads
token_container = {"token": None, "expires_in": None, "user_id": None}
+# Configuration class to store app ID and other config
+class MetaConfig:
+ _instance = None
+
+ def __new__(cls):
+ if cls._instance is None:
+ cls._instance = super(MetaConfig, cls).__new__(cls)
+ cls._instance.app_id = os.environ.get("META_APP_ID", "") # Default from env
+ cls._instance.initialized = False
+ return cls._instance
+
+ def set_app_id(self, app_id):
+ """Set app ID from CLI or other source"""
+ if app_id:
+ print(f"Setting Meta App ID: {app_id}")
+ self.app_id = app_id
+ self.initialized = True
+
+ def get_app_id(self):
+ """Get current app ID"""
+ return self.app_id
+
+ def is_configured(self):
+ """Check if app has been configured with valid app ID"""
+ return bool(self.app_id)
+
+# Create global config instance
+meta_config = MetaConfig()
+
# Callback Handler class definition
class CallbackHandler(BaseHTTPRequestHandler):
def do_GET(self):
@@ -302,8 +324,8 @@ class AuthManager:
"""Clear the current token and remove from cache"""
self.invalidate_token()
-# Initialize auth manager
-auth_manager = AuthManager(META_APP_ID)
+# Initialize auth manager with app_id from config
+auth_manager = AuthManager(meta_config.get_app_id())
# Function to get token without requiring it as a parameter
async def get_current_access_token() -> Optional[str]:
@@ -315,6 +337,24 @@ async def get_current_access_token() -> Optional[str]:
"""
return auth_manager.get_access_token()
+# Function to get current app ID from all possible sources
+def get_current_app_id():
+ """Get the current app ID from MetaConfig."""
+ # First try to get from our singleton config
+ app_id = meta_config.get_app_id()
+ if app_id:
+ return app_id
+
+ # If not in config yet, check environment as fallback
+ env_app_id = os.environ.get("META_APP_ID", "")
+ if env_app_id:
+ # Update config for future use
+ meta_config.set_app_id(env_app_id)
+ return env_app_id
+
+ # Last resort, return empty string
+ return ""
+
class GraphAPIError(Exception):
"""Exception raised for errors from the Graph API."""
def __init__(self, error_data: Dict[str, Any]):
@@ -345,6 +385,17 @@ async def make_api_request(
Returns:
API response as a dictionary
"""
+ # Validate access token before proceeding
+ if not access_token:
+ print("API request attempted with blank access token")
+ return {
+ "error": "Authentication Required",
+ "details": {
+ "message": "A valid access token is required to access the Meta API",
+ "action_required": "Please authenticate first"
+ }
+ }
+
url = f"{META_GRAPH_API_BASE}/{endpoint}"
headers = {
@@ -391,6 +442,19 @@ async def make_api_request(
# Check for specific FB API errors related to auth
if isinstance(error_obj, dict) and error_obj.get("code") in [190, 102, 4, 200, 10]:
print(f"Detected Facebook API auth error: {error_obj.get('code')}")
+ # For app ID errors, provide more useful error message
+ if error_obj.get("code") == 200 and "Provide valid app ID" in error_obj.get("message", ""):
+ print("Meta API authentication configuration issue")
+ app_id = auth_manager.app_id
+ print(f"Current app_id: {app_id}")
+ return {
+ "error": f"HTTP Error: {e.response.status_code}",
+ "details": {
+ "message": "Meta API authentication configuration issue. Please check your app credentials.",
+ "original_error": error_obj.get("message"),
+ "code": error_obj.get("code")
+ }
+ }
auth_manager.invalidate_token()
return {"error": f"HTTP Error: {e.response.status_code}", "details": error_info}
@@ -403,6 +467,7 @@ async def make_api_request(
def meta_api_tool(func):
"""Decorator to handle authentication for all Meta API tools"""
async def wrapper(*args, **kwargs):
+ global needs_authentication
# Handle various MCP invocation patterns
if len(args) == 1:
# MCP might pass a single string argument that contains JSON
@@ -449,39 +514,44 @@ def meta_api_tool(func):
# If not, try to get it from the auth manager
if not access_token:
access_token = await get_current_access_token()
+ if access_token:
+ kwargs['access_token'] = access_token
# If still no token, we need authentication
if not access_token:
- global needs_authentication
needs_authentication = True
# 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)
+
+ # 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()
- # Create a resource response that includes the markdown link format
- response = {
- "error": "Authentication required to use Meta Ads API",
- "login_url": login_url,
- "server_status": f"Callback server running on port {port}",
- "markdown_link": f"[Click here to authenticate with Meta Ads API]({login_url})",
- "message": "IMPORTANT: Please use the Markdown link format in your response to allow the user to click it.",
- "instructions_for_llm": "You must present this link as clickable Markdown to the user using the markdown_link format provided.",
- "note": "After authenticating, the token will be automatically saved."
- }
-
- # Wait a moment to ensure the server is fully started
- await asyncio.sleep(1)
-
- return json.dumps(response, indent=2)
-
- # Update kwargs with the token
- kwargs['access_token'] = access_token
+ # 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:
@@ -492,6 +562,17 @@ def meta_api_tool(func):
# 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"
@@ -514,6 +595,28 @@ def meta_api_tool(func):
return json.dumps(response, indent=2)
+ # If result is a string (JSON), check for app ID errors and improve them
+ if isinstance(result, str):
+ try:
+ result_obj = json.loads(result)
+ if "error" in result_obj and "details" in result_obj and "error" in result_obj["details"]:
+ error_obj = result_obj["details"].get("error", {})
+ if isinstance(error_obj, dict) and error_obj.get("code") == 200 and "Provide valid app ID" in error_obj.get("message", ""):
+ # Replace with more user-friendly message
+ app_id = auth_manager.app_id
+ return json.dumps({
+ "error": "Meta API Configuration Issue",
+ "details": {
+ "message": "Your Meta API app is not properly configured",
+ "action_required": "Check your META_APP_ID environment variable",
+ "current_app_id": app_id,
+ "original_error": error_obj.get("message")
+ }
+ }, indent=2)
+ except Exception:
+ # Not JSON or other parsing error, just continue
+ pass
+
return result
except Exception as e:
# Handle any unexpected errors
@@ -1171,10 +1274,35 @@ async def get_insights(
breakdown: Optional breakdown dimension (e.g., age, gender, country)
level: Level of aggregation (ad, adset, campaign, account)
"""
+ # Import logger
+ from meta_ads_mcp.core.utils import logger
+
+ # Log function call details
+ logger.info(f"get_insights called with object_id: {object_id}, time_range: {time_range}, level: {level}")
+
+ # Log authentication details
+ from meta_ads_mcp.core.auth import meta_config
+ app_id = meta_config.get_app_id()
+ logger.info(f"App ID from meta_config: {app_id}")
+
+ # Validate inputs
if not object_id:
- return json.dumps({"error": "No object ID provided"}, indent=2)
+ logger.error("No object ID provided for get_insights")
+ return json.dumps({"error": "Missing Required Parameter", "details": {"message": "No object ID provided"}}, indent=2)
+ # Check access token (masking for security)
+ token_status = "provided" if access_token else "not provided"
+ logger.info(f"Access token status: {token_status}")
+
+ # Log the specific object ID format for troubleshooting
+ if object_id.startswith("act_"):
+ logger.info(f"Object ID is an account ID: {object_id}")
+ else:
+ logger.info(f"Object ID format: {object_id}")
+
endpoint = f"{object_id}/insights"
+ logger.info(f"Using endpoint: {endpoint}")
+
params = {
"date_preset": time_range,
"fields": "account_id,account_name,campaign_id,campaign_name,adset_id,adset_name,ad_id,ad_name,impressions,clicks,spend,cpc,cpm,ctr,reach,frequency,actions,conversions,unique_clicks,cost_per_action_type",
@@ -1184,7 +1312,27 @@ async def get_insights(
if breakdown:
params["breakdowns"] = breakdown
- data = await make_api_request(endpoint, access_token, params)
+ logger.info("Making API request for insights")
+ try:
+ data = await make_api_request(endpoint, access_token, params)
+ logger.info(f"API response received: {'success' if 'error' not in data else 'error'}")
+
+ # Check for specific app ID errors and improve error message
+ if "error" in data:
+ error_details = data.get("details", {}).get("error", {})
+ if isinstance(error_details, dict) and error_details.get("code") == 200:
+ logger.error(f"Authentication configuration error in response: {error_details.get('message')}")
+ return json.dumps({
+ "error": "Meta API Configuration Issue",
+ "details": {
+ "message": "There is an issue with your Meta API configuration",
+ "action_required": "Check your META_APP_ID environment variable or re-authenticate",
+ "current_app_id": app_id
+ }
+ }, indent=2)
+ except Exception as e:
+ logger.error(f"Exception during get_insights API call: {str(e)}")
+ data = {"error": str(e)}
return json.dumps(data, indent=2)
@@ -1521,6 +1669,16 @@ def login():
"""
print("Starting Meta Ads authentication flow...")
+ # Ensure auth_manager has the current app ID from config
+ current_app_id = meta_config.get_app_id()
+ if not current_app_id:
+ print("Error: No Meta App ID available. Authentication will fail.")
+ print("Please provide an app ID using --app-id or via META_APP_ID environment variable.")
+ return
+
+ auth_manager.app_id = current_app_id
+ print(f"Using Meta App ID from config: {current_app_id}")
+
try:
# Start the callback server first
port = start_callback_server()
@@ -1672,6 +1830,12 @@ def start_callback_server():
# Update auth manager's redirect URI with new port
auth_manager.redirect_uri = f"http://localhost:{port}/callback"
+
+ # Always make sure auth_manager has the current app ID from config
+ current_app_id = meta_config.get_app_id()
+ if current_app_id:
+ auth_manager.app_id = current_app_id
+
callback_server_port = port
try:
@@ -1739,9 +1903,17 @@ def login_cli():
args = parser.parse_args()
- # Update app ID if provided
+ # Update app ID if provided via CLI
if args.app_id:
- auth_manager.app_id = args.app_id
+ meta_config.set_app_id(args.app_id)
+ else:
+ # Use existing config or environment variable
+ if not meta_config.is_configured():
+ print("Error: No Meta App ID provided. Please provide using --app-id or META_APP_ID environment variable.")
+ return 1
+
+ # Update auth_manager with app ID from config
+ auth_manager.app_id = meta_config.get_app_id()
if args.force_login:
# Clear existing token
@@ -1754,7 +1926,7 @@ def login_cli():
def main():
"""
- Main entry point for the Meta Ads MCP server.
+ Main entry point for the Meta Ads MCP Server.
This function handles command line arguments and runs the server.
"""
# Set up command line arguments
@@ -1764,12 +1936,22 @@ def main():
args = parser.parse_args()
- # Update app ID if provided
+ # Update app ID if provided via CLI (highest priority)
if args.app_id:
- auth_manager.app_id = args.app_id
+ meta_config.set_app_id(args.app_id)
+
+ # Ensure auth_manager has the current app ID
+ app_id = get_current_app_id()
+ if app_id:
+ auth_manager.app_id = app_id
+ else:
+ print("Warning: No Meta App ID provided. Authentication will fail.")
# Handle login command
if args.login:
+ if not meta_config.is_configured():
+ print("Error: Cannot login without a Meta App ID. Please provide using --app-id or META_APP_ID environment variable.")
+ return 1
login()
else:
# Initialize and run the server
diff --git a/meta_ads_mcp/core/api.py b/meta_ads_mcp/core/api.py
index a573d1d..819bf72 100644
--- a/meta_ads_mcp/core/api.py
+++ b/meta_ads_mcp/core/api.py
@@ -5,13 +5,19 @@ import json
import httpx
import asyncio
import functools
+import os
from .auth import needs_authentication, get_current_access_token, auth_manager, start_callback_server
+from .utils import logger
# Constants
META_GRAPH_API_VERSION = "v20.0"
META_GRAPH_API_BASE = f"https://graph.facebook.com/{META_GRAPH_API_VERSION}"
USER_AGENT = "meta-ads-mcp/1.0"
+# Log key environment and configuration at startup
+logger.info("Core API module initialized")
+logger.info(f"Graph API Version: {META_GRAPH_API_VERSION}")
+logger.info(f"META_APP_ID env var present: {'Yes' if os.environ.get('META_APP_ID') else 'No'}")
class GraphAPIError(Exception):
"""Exception raised for errors from the Graph API."""
@@ -20,9 +26,14 @@ class GraphAPIError(Exception):
self.message = error_data.get('message', 'Unknown Graph API error')
super().__init__(self.message)
+ # Log error details
+ logger.error(f"Graph API Error: {self.message}")
+ logger.debug(f"Error details: {error_data}")
+
# Check if this is an auth error
if "code" in error_data and error_data["code"] in [190, 102, 4]:
# Common auth error codes
+ logger.warning(f"Auth error detected (code: {error_data['code']}). Invalidating token.")
auth_manager.invalidate_token()
@@ -44,6 +55,17 @@ async def make_api_request(
Returns:
API response as a dictionary
"""
+ # Validate access token before proceeding
+ if not access_token:
+ logger.error("API request attempted with blank access token")
+ return {
+ "error": "Authentication Required",
+ "details": {
+ "message": "A valid access token is required to access the Meta API",
+ "action_required": "Please authenticate first"
+ }
+ }
+
url = f"{META_GRAPH_API_BASE}/{endpoint}"
headers = {
@@ -53,10 +75,14 @@ async def make_api_request(
request_params = params or {}
request_params["access_token"] = access_token
- # Print the request details (masking the token for security)
+ # Logging the request (masking token for security)
masked_params = {k: "***TOKEN***" if k == "access_token" else v for k, v in request_params.items()}
- print(f"Making {method} request to: {url}")
- print(f"Params: {masked_params}")
+ logger.debug(f"API Request: {method} {url}")
+ logger.debug(f"Request params: {masked_params}")
+
+ # Check for app_id in params
+ app_id = auth_manager.app_id
+ logger.debug(f"Current app_id from auth_manager: {app_id}")
async with httpx.AsyncClient() as client:
try:
@@ -70,6 +96,7 @@ async def make_api_request(
raise ValueError(f"Unsupported HTTP method: {method}")
response.raise_for_status()
+ logger.debug(f"API Response status: {response.status_code}")
return response.json()
except httpx.HTTPStatusError as e:
@@ -79,23 +106,36 @@ async def make_api_request(
except:
error_info = {"status_code": e.response.status_code, "text": e.response.text}
- print(f"HTTP Error: {e.response.status_code} - {error_info}")
+ logger.error(f"HTTP Error: {e.response.status_code} - {error_info}")
# Check for authentication errors
if e.response.status_code == 401 or e.response.status_code == 403:
- print("Detected authentication error")
+ logger.warning("Detected authentication error (401/403)")
auth_manager.invalidate_token()
elif "error" in error_info:
error_obj = error_info.get("error", {})
# Check for specific FB API errors related to auth
if isinstance(error_obj, dict) and error_obj.get("code") in [190, 102, 4, 200, 10]:
- print(f"Detected Facebook API auth error: {error_obj.get('code')}")
+ logger.warning(f"Detected Facebook API auth error: {error_obj.get('code')}")
+ # Log more details about app ID related errors
+ if error_obj.get("code") == 200 and "Provide valid app ID" in error_obj.get("message", ""):
+ logger.error("Meta API authentication configuration issue")
+ logger.error(f"Current app_id: {app_id}")
+ # Provide a clearer error message without the confusing "Provide valid app ID" message
+ return {
+ "error": f"HTTP Error: {e.response.status_code}",
+ "details": {
+ "message": "Meta API authentication configuration issue. Please check your app credentials.",
+ "original_error": error_obj.get("message"),
+ "code": error_obj.get("code")
+ }
+ }
auth_manager.invalidate_token()
return {"error": f"HTTP Error: {e.response.status_code}", "details": error_info}
except Exception as e:
- print(f"Request Error: {str(e)}")
+ logger.error(f"Request Error: {str(e)}")
return {"error": str(e)}
@@ -105,21 +145,76 @@ def meta_api_tool(func):
@functools.wraps(func)
async def wrapper(*args, **kwargs):
try:
+ # Log function call
+ logger.debug(f"Function call: {func.__name__}")
+ logger.debug(f"Args: {args}")
+ # Log kwargs without sensitive info
+ safe_kwargs = {k: ('***TOKEN***' if k == 'access_token' else v) for k, v in kwargs.items()}
+ logger.debug(f"Kwargs: {safe_kwargs}")
+
+ # Log app ID information
+ app_id = auth_manager.app_id
+ logger.debug(f"Current app_id: {app_id}")
+ logger.debug(f"META_APP_ID env var: {os.environ.get('META_APP_ID')}")
+
# If access_token is not in kwargs, try to get it from auth_manager
if 'access_token' not in kwargs or not kwargs['access_token']:
try:
- access_token = await auth_manager.get_current_access_token()
+ access_token = await get_current_access_token()
if access_token:
kwargs['access_token'] = access_token
+ logger.debug("Using access token from auth_manager")
+ else:
+ logger.warning("No access token available from auth_manager")
except Exception as e:
- pass
-
+ logger.error(f"Error getting access token: {str(e)}")
+
+ # Final validation - if we still don't have a valid token, return authentication required
if 'access_token' not in kwargs or not kwargs['access_token']:
- needs_authentication = True
+ logger.warning("No access token available, authentication needed")
+ auth_url = auth_manager.get_auth_url()
+ return json.dumps({
+ "error": "Authentication Required",
+ "details": {
+ "message": "You need to authenticate with the Meta API before using this tool",
+ "action_required": "Please authenticate first",
+ "auth_url": auth_url,
+ "markdown_link": f"[Click here to authenticate with Meta Ads API]({auth_url})"
+ }
+ }, indent=2)
# Call the original function
- return await func(*args, **kwargs)
+ result = await func(*args, **kwargs)
+
+ # If the result is a string (JSON), try to parse it to check for errors
+ if isinstance(result, str):
+ try:
+ result_dict = json.loads(result)
+ if "error" in result_dict:
+ logger.error(f"Error in API response: {result_dict['error']}")
+ # If this is an app ID error, log more details
+ if isinstance(result_dict.get("details", {}).get("error", {}), dict):
+ error_obj = result_dict["details"]["error"]
+ if error_obj.get("code") == 200 and "Provide valid app ID" in error_obj.get("message", ""):
+ logger.error("Meta API authentication configuration issue")
+ logger.error(f"Current app_id: {app_id}")
+ # Replace the confusing error with a more user-friendly one
+ return json.dumps({
+ "error": "Meta API Configuration Issue",
+ "details": {
+ "message": "Your Meta API app is not properly configured",
+ "action_required": "Check your META_APP_ID environment variable",
+ "current_app_id": app_id,
+ "original_error": error_obj.get("message")
+ }
+ }, indent=2)
+ except Exception:
+ # Not JSON or other parsing error, just continue
+ pass
+
+ return result
except Exception as e:
+ logger.error(f"Error in {func.__name__}: {str(e)}")
return {"error": str(e)}
return wrapper
\ No newline at end of file
diff --git a/meta_ads_mcp/core/auth.py b/meta_ads_mcp/core/auth.py
index 35cc365..56518c0 100644
--- a/meta_ads_mcp/core/auth.py
+++ b/meta_ads_mcp/core/auth.py
@@ -12,12 +12,18 @@ import asyncio
from urllib.parse import urlparse, parse_qs
from http.server import HTTPServer, BaseHTTPRequestHandler
import json
+from .utils import logger
# Auth constants
AUTH_SCOPE = "ads_management,ads_read,business_management"
AUTH_REDIRECT_URI = "http://localhost:8888/callback"
AUTH_RESPONSE_TYPE = "token"
+# Log important configuration information
+logger.info("Authentication module initialized")
+logger.info(f"Auth scope: {AUTH_SCOPE}")
+logger.info(f"Default redirect URI: {AUTH_REDIRECT_URI}")
+
# Global token container for communication between threads
token_container = {"token": None, "expires_in": None, "user_id": None}
@@ -33,6 +39,54 @@ callback_server_lock = threading.Lock()
callback_server_running = False
callback_server_port = None
+# Meta configuration singleton
+class MetaConfig:
+ _instance = None
+
+ def __new__(cls):
+ if cls._instance is None:
+ logger.debug("Creating new MetaConfig instance")
+ cls._instance = super(MetaConfig, cls).__new__(cls)
+ cls._instance.app_id = os.environ.get("META_APP_ID", "")
+ logger.info(f"MetaConfig initialized with app_id from env: {cls._instance.app_id}")
+ return cls._instance
+
+ def set_app_id(self, app_id):
+ """Set the Meta App ID for API calls"""
+ logger.info(f"Setting Meta App ID: {app_id}")
+ self.app_id = app_id
+ # Also update environment variable for modules that might read directly from it
+ os.environ["META_APP_ID"] = app_id
+ logger.debug(f"Updated META_APP_ID environment variable: {os.environ.get('META_APP_ID')}")
+
+ def get_app_id(self):
+ """Get the current Meta App ID"""
+ # Check if we have one set
+ if hasattr(self, 'app_id') and self.app_id:
+ logger.debug(f"Using app_id from instance: {self.app_id}")
+ return self.app_id
+
+ # If not, try environment variable
+ env_app_id = os.environ.get("META_APP_ID", "")
+ if env_app_id:
+ logger.debug(f"Using app_id from environment: {env_app_id}")
+ # Update our instance for future use
+ self.app_id = env_app_id
+ return env_app_id
+
+ logger.warning("No app_id found in instance or environment variables")
+ return ""
+
+ def is_configured(self):
+ """Check if the Meta configuration is complete"""
+ app_id = self.get_app_id()
+ configured = bool(app_id)
+ logger.debug(f"MetaConfig.is_configured() = {configured} (app_id: {app_id})")
+ return configured
+
+# Create singleton instance
+meta_config = MetaConfig()
+
class TokenInfo:
"""Stores token information including expiration"""
def __init__(self, access_token: str, expires_in: int = None, user_id: str = None):
@@ -40,6 +94,7 @@ class TokenInfo:
self.expires_in = expires_in
self.user_id = user_id
self.created_at = int(time.time())
+ logger.debug(f"TokenInfo created. Expires in: {expires_in if expires_in else 'Not specified'}")
def is_expired(self) -> bool:
"""Check if the token is expired"""
@@ -590,22 +645,30 @@ class CallbackHandler(BaseHTTPRequestHandler):
# Process the token (save it) immediately
if token_container["token"]:
# Create token info and save to cache
+ logger.info("Token received in callback handler, attempting to save to cache")
token_info = TokenInfo(
access_token=token_container["token"],
expires_in=token_container["expires_in"]
)
try:
+ # Set the token info in the auth_manager first
+ global auth_manager
+ auth_manager.token_info = token_info
+ logger.info(f"Token info set in auth_manager, expires in {token_info.expires_in} seconds")
+
# Save to cache
- self._save_token_to_cache()
+ auth_manager._save_token_to_cache()
+ logger.info(f"Token successfully saved to cache at {auth_manager._get_token_cache_path()}")
except Exception as e:
- pass
+ logger.error(f"Error saving token to cache: {e}")
# Reset auth needed flag
needs_authentication = False
return token_container["token"]
else:
+ logger.warning("Received empty token in callback")
needs_authentication = True
return None
@@ -701,44 +764,57 @@ def process_token_response(token_container):
global needs_authentication
if token_container and token_container.get('token'):
+ logger.info("Processing token response from Facebook OAuth")
token_info = TokenInfo(
access_token=token_container['token'],
expires_in=token_container.get('expires_in', 0)
)
try:
+ global auth_manager
auth_manager.token_info = token_info
+ logger.info(f"Token info set in auth_manager, expires in {token_info.expires_in} seconds")
except NameError:
- pass
+ logger.error("auth_manager not defined when trying to process token")
try:
+ logger.info("Attempting to save token to cache")
auth_manager._save_token_to_cache()
+ logger.info(f"Token successfully saved to cache at {auth_manager._get_token_cache_path()}")
except Exception as e:
- pass
+ logger.error(f"Error saving token to cache: {e}")
needs_authentication = False
return True
else:
+ logger.warning("Received empty token in process_token_response")
needs_authentication = True
return False
-async def get_current_access_token():
- """Get the current access token, either from auth_manager or token_container."""
+async def get_current_access_token() -> Optional[str]:
+ """Get the current access token from auth manager"""
+ # Use the singleton auth manager
+ global auth_manager
+
+ # Log the function call and current app ID
+ logger.debug("get_current_access_token() called")
+ app_id = meta_config.get_app_id()
+ logger.debug(f"Current app_id: {app_id}")
+
+ # Attempt to get access token
try:
token = auth_manager.get_access_token()
+
if token:
+ logger.debug("Access token found in auth_manager")
return token
- except Exception:
- if token_container.get('token'):
- auth_manager.token_info = TokenInfo(
- access_token=token_container['token'],
- expires_in=token_container.get('expires_in', 0)
- )
- return token_container['token']
- pass
-
- return None
+ else:
+ logger.warning("No valid access token available in auth_manager")
+ return None
+ except Exception as e:
+ logger.error(f"Error getting access token: {str(e)}")
+ return None
def login():
diff --git a/meta_ads_mcp/core/authentication.py b/meta_ads_mcp/core/authentication.py
index 843e17b..dd234ee 100644
--- a/meta_ads_mcp/core/authentication.py
+++ b/meta_ads_mcp/core/authentication.py
@@ -5,6 +5,7 @@ import asyncio
from .api import meta_api_tool
from .auth import start_callback_server, auth_manager, get_current_access_token
from .server import mcp_server
+from .utils import logger
@mcp_server.tool()
@@ -24,6 +25,7 @@ async def get_login_link(access_token: str = None) -> str:
# 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,
@@ -34,11 +36,15 @@ 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}")
# Return a special format that helps the LLM format the response properly
response = {
diff --git a/meta_ads_mcp/core/server.py b/meta_ads_mcp/core/server.py
index 60b664c..f012094 100644
--- a/meta_ads_mcp/core/server.py
+++ b/meta_ads_mcp/core/server.py
@@ -3,8 +3,10 @@
from mcp.server.fastmcp import FastMCP
import argparse
import os
+import sys
from .auth import login as login_auth
from .resources import list_resources, get_resource
+from .utils import logger
# Initialize FastMCP server
mcp_server = FastMCP("meta-ads", use_consistent_tool_format=True)
@@ -18,6 +20,7 @@ def login_cli():
"""
Command-line function to authenticate with Meta
"""
+ logger.info("Starting Meta Ads CLI authentication flow")
print("Starting Meta Ads CLI authentication flow...")
# Call the common login function
@@ -26,23 +29,49 @@ def login_cli():
def main():
"""Main entry point for the package"""
+ # Log startup information
+ logger.info("Meta Ads MCP server starting")
+ logger.info(f"Python version: {sys.version}")
+ logger.info(f"Args: {sys.argv}")
+
+ # Initialize argument parser
parser = argparse.ArgumentParser(description="Meta Ads MCP Server")
parser.add_argument("--login", action="store_true", help="Authenticate with Meta and store the token")
parser.add_argument("--app-id", type=str, help="Meta App ID (Client ID) for authentication")
parser.add_argument("--version", action="store_true", help="Show the version of the package")
args = parser.parse_args()
+ logger.info(f"Parsed args: login={args.login}, app_id={args.app_id}, version={args.version}")
# Update app ID if provided as environment variable or command line arg
- from .auth import auth_manager
+ from .auth import auth_manager, meta_config
+
+ # Check environment variable first (early init)
+ env_app_id = os.environ.get("META_APP_ID")
+ if env_app_id:
+ logger.info(f"Found META_APP_ID in environment: {env_app_id}")
+ else:
+ logger.warning("META_APP_ID not found in environment variables")
+
+ # Command line takes precedence
if args.app_id:
+ logger.info(f"Setting app_id from command line: {args.app_id}")
auth_manager.app_id = args.app_id
- elif os.environ.get("META_APP_ID"):
- auth_manager.app_id = os.environ.get("META_APP_ID")
+ meta_config.set_app_id(args.app_id)
+ elif env_app_id:
+ logger.info(f"Setting app_id from environment: {env_app_id}")
+ auth_manager.app_id = env_app_id
+ meta_config.set_app_id(env_app_id)
+
+ # Log the final app ID that will be used
+ logger.info(f"Final app_id from meta_config: {meta_config.get_app_id()}")
+ logger.info(f"Final app_id from auth_manager: {auth_manager.app_id}")
+ logger.info(f"ENV META_APP_ID: {os.environ.get('META_APP_ID')}")
# Show version if requested
if args.version:
from meta_ads_mcp import __version__
+ logger.info(f"Displaying version: {__version__}")
print(f"Meta Ads MCP v{__version__}")
return 0
@@ -51,4 +80,5 @@ def main():
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
diff --git a/meta_ads_mcp/core/utils.py b/meta_ads_mcp/core/utils.py
index e6300d4..da3f093 100644
--- a/meta_ads_mcp/core/utils.py
+++ b/meta_ads_mcp/core/utils.py
@@ -7,6 +7,49 @@ from PIL import Image as PILImage
import base64
import time
import asyncio
+import os
+import json
+import logging
+import pathlib
+import platform
+
+# Configure logging to file
+def setup_logging():
+ """Set up logging to file for troubleshooting."""
+ # Get platform-specific path for logs
+ if platform.system() == "Windows":
+ base_path = pathlib.Path(os.environ.get("APPDATA", ""))
+ elif platform.system() == "Darwin": # macOS
+ base_path = pathlib.Path.home() / "Library" / "Application Support"
+ else: # Assume Linux/Unix
+ base_path = pathlib.Path.home() / ".config"
+
+ # Create directory if it doesn't exist
+ log_dir = base_path / "meta-ads-mcp"
+ log_dir.mkdir(parents=True, exist_ok=True)
+
+ log_file = log_dir / "meta_ads_debug.log"
+
+ # Configure file logger
+ logging.basicConfig(
+ level=logging.DEBUG,
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
+ filename=str(log_file),
+ filemode='a' # Append mode
+ )
+
+ # Create a logger
+ logger = logging.getLogger("meta-ads-mcp")
+ logger.setLevel(logging.DEBUG)
+
+ # Log startup information
+ logger.info(f"Logging initialized. Log file: {log_file}")
+ logger.info(f"Platform: {platform.system()} {platform.release()}")
+
+ return logger
+
+# Create the logger instance to be imported by other modules
+logger = setup_logging()
# Global store for ad creative images
ad_creative_images = {}