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 login scripts and enhance authentication flow

Yves Junqueiraccbf7cca64be
diff --git a/README.md b/README.md
index bfa5d0c..7d16e82 100644
--- a/README.md
+++ b/README.md
@@ -1,150 +1,156 @@
-# Meta Ads MCP Server
+# Meta Ads MCP
-A Model Context Protocol (MCP) server that provides tools for querying the Meta Ads API.
+A [Model Calling Protocol (MCP)](https://github.com/anthropics/anthropic-tools) plugin for interacting with Meta Ads API.
+
+## Features
+
+- Seamless authentication with Meta's Graph API for desktop applications
+- Automatic token caching across sessions
+- Cross-platform support (Windows, macOS, Linux)
+- Access to ad accounts, campaigns, ad sets, and ads
+- Image download and analysis capabilities
+- Performance insights
## Setup
-1. Install dependencies:
-```bash
-# Using pip
-pip install mcp>=1.2.0 httpx>=0.26.0
+### 1. Create a Meta Developer App
-# Or using Poetry
-poetry add mcp httpx
+1. Go to [Meta for Developers](https://developers.facebook.com/) and create a new app
+2. Choose the "Consumer" app type
+3. In your app settings, add the "Marketing API" product
+4. Configure your app's OAuth redirect URI to include `http://localhost:8888/callback`
+5. Note your App ID (Client ID) for use with the MCP
-# Or using uv (recommended)
-uv pip install mcp>=1.2.0 httpx>=0.26.0
-```
+### 2. Install Dependencies
-2. Run the server:
```bash
-# Direct execution (for development only)
-python meta_ads.py
+pip install -r requirements.txt
+```
+
+## Authentication
+
+The Meta Ads MCP uses the OAuth 2.0 flow designed for desktop apps. The first time you use it, it will:
-# Using uv (recommended)
-uv run python meta_ads.py
+1. Open a browser window to authenticate with Meta
+2. Ask you to authorize the app
+3. Redirect back to a local server running on your machine
+4. Extract and store the token securely
+
+### Initial Authentication
+
+You can trigger the authentication process in two ways:
+
+1. Using the dedicated login command:
+
+```bash
+python meta_ads_generated.py --login --app-id YOUR_APP_ID
```
-Note: The server uses stdio transport, so it won't output anything when run directly. It's meant to be used with an MCP client like Claude for Desktop or Cursor.
+2. Or by running any command which will automatically prompt for authentication if needed:
-## Tools
+```bash
+python test_meta_ads_auth.py --app-id YOUR_APP_ID
+```
-This MCP server provides the following tools:
+### Token Caching
-1. `get_ads` - Retrieves ads from a Meta Ads account
-2. `get_campaigns` - Retrieves campaigns from a Meta Ads account
-3. `get_adsets` - Retrieves ad sets from a Meta Ads account
+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`
-## Configuration with Claude for Desktop
+You do not need to provide your access token for each command; it will be automatically retrieved from the cache.
-To use this MCP server with Claude for Desktop, add the following to your Claude configuration file:
+## Usage Examples
-1. Open your Claude for Desktop configuration:
- - macOS: `~/Library/Application Support/Claude/claude_desktop_config.json`
- - Windows: `%AppData%\Claude\claude_desktop_config.json`
+### Test Authentication
-2. Add the server configuration:
-```json
-{
- "mcpServers": {
- "meta-ads": {
- "command": "uv",
- "args": [
- "--directory",
- "/ABSOLUTE/PATH/TO/PARENT/FOLDER",
- "run",
- "python",
- "meta_ads.py"
- ]
- }
- }
-}
+```bash
+python test_meta_ads_auth.py --app-id YOUR_APP_ID
```
-3. Replace `/ABSOLUTE/PATH/TO/PARENT/FOLDER` with the absolute path to the directory containing your `meta_ads.py` file. For example: `/Users/username/projects/meta-ads-mcp`
-
-4. Restart Claude for Desktop.
-
-## Configuration with Cursor
-
-To use this MCP server with Cursor:
-
-1. Edit the Cursor MCP configuration file:
- - macOS: `~/.cursor/mcp.json`
- - Windows: `%AppData%\Cursor\User\mcp.json`
-
-2. Add the server configuration:
-```json
-{
- "mcpServers": {
- "meta-ads": {
- "command": "uv",
- "args": [
- "--directory",
- "/ABSOLUTE/PATH/TO/PARENT/FOLDER",
- "run",
- "python",
- "meta_ads.py"
- ],
- "description": "Meta Ads API MCP server",
- "autoconnect": true
- }
- }
-}
+### Get Ad Accounts
+
+```python
+import asyncio
+from meta_ads_generated import get_ad_accounts
+
+async def main():
+ # Token will be automatically retrieved from cache
+ accounts_json = await get_ad_accounts()
+ print(accounts_json)
+
+asyncio.run(main())
```
-3. Replace `/ABSOLUTE/PATH/TO/PARENT/FOLDER` with the absolute path to the directory containing your `meta_ads.py` file.
+### Get Campaign Details
-4. Restart Cursor or reconnect to the MCP server.
+```python
+import asyncio
+from meta_ads_generated import get_campaign_details
-## Usage with Claude or Cursor
+async def main():
+ # Provide a campaign ID
+ campaign_details = await get_campaign_details(campaign_id="123456789")
+ print(campaign_details)
-You can now ask about your Meta Ads account. Example prompts:
-- "Show me the ads in my Meta Ads account with ID act_123456789"
-- "What campaigns do I have running in my Meta Ads account?"
-- "List the ad sets for my Meta account"
+asyncio.run(main())
+```
-The assistant will use the provided access token and account ID to fetch the requested information.
+### Create a Campaign
-## Important Notes
+```python
+import asyncio
+from meta_ads_generated import create_campaign
-- You need a valid Meta Ads API access token to use these tools
-- Your account ID should be in the format `act_XXXXXXXXX`
-- The server will fetch a maximum of 10 items by default (configurable with the `limit` parameter)
-- Using UV is recommended for better dependency management
+async def main():
+ result = await create_campaign(
+ account_id="act_123456789",
+ name="Test Campaign via MCP",
+ objective="AWARENESS",
+ status="PAUSED",
+ daily_budget=1000 # $10.00
+ )
+ print(result)
-## Generated Meta Ads API Implementation
+asyncio.run(main())
+```
-This project now includes an alternative implementation (`meta_ads_generated.py`) that provides a more complete interface to the Meta Ads API using Facebook's Graph API. This implementation:
+## Environment Variables
-1. Offers more detailed parameters and fields for each endpoint
-2. Provides additional functionality like filtering campaigns by status
-3. Adds support for creating new campaigns
-4. Includes enhanced error handling and debugging
+You can set the following environment variables instead of passing them as arguments:
-### Additional Tools in Generated Implementation
+- `META_APP_ID`: Your Meta App ID (Client ID)
-The generated implementation includes all the tools from the original implementation, plus:
+## Testing
-1. `get_ad_accounts` - Get ad accounts accessible by a user
-2. `get_account_info` - Get detailed information about a specific ad account
-3. `get_campaign_details` - Get detailed information about a specific campaign
-4. `get_adset_details` - Get detailed information about a specific ad set
-5. `get_ad_details` - Get detailed information about a specific ad
-6. `create_campaign` - Create a new campaign in a Meta Ads account
-7. `get_insights` - Get performance insights with optional breakdowns
+Run the test script to verify authentication and basic functionality:
-### Using the Generated Implementation
+```bash
+python test_meta_ads_auth.py --app-id YOUR_APP_ID
+```
-To use the generated implementation with Cursor:
+Use the `--force-login` flag to force a new authentication even if a cached token exists:
-1. The configuration is already included in your Cursor MCP configuration
-2. Run the server using the provided script:
```bash
-./run_mcp_generated.sh
+python test_meta_ads_auth.py --app-id YOUR_APP_ID --force-login
```
-3. When talking to Claude in Cursor, you can access the new tools with queries like:
- - "Show me detailed performance insights for my campaign"
- - "Get all my ad accounts"
- - "Create a new campaign for my Meta Ads account"
\ No newline at end of file
+## Troubleshooting
+
+### Authentication Issues
+
+If you encounter authentication issues:
+
+1. Run with `--force-login` to get a fresh token
+2. Check that your app is properly configured in the Meta Developers portal
+3. Ensure your app has the necessary permissions (ads_management, ads_read)
+4. Check the app's redirect URI includes http://localhost:8888/callback
+
+### API Errors
+
+If you receive errors from the Meta API:
+
+1. Verify your app has the Marketing API product added
+2. Ensure the user has appropriate permissions on the ad accounts
+3. Check if there are rate limits or other restrictions on your app
\ No newline at end of file
diff --git a/login.bat b/login.bat
new file mode 100644
index 0000000..5b6175b
--- /dev/null
+++ b/login.bat
@@ -0,0 +1,18 @@
+@echo off
+REM Simple script to log in to Meta Ads MCP on Windows
+
+SET APP_ID=%1
+
+IF "%APP_ID%"=="" (
+ IF NOT "%META_APP_ID%"=="" (
+ SET APP_ID=%META_APP_ID%
+ ) ELSE (
+ echo Error: No Meta App ID provided.
+ echo Usage: login.bat YOUR_APP_ID
+ echo or set the META_APP_ID environment variable.
+ exit /b 1
+ )
+)
+
+echo Starting Meta Ads authentication with App ID: %APP_ID%
+python meta_ads_generated.py --login --app-id "%APP_ID%"
\ No newline at end of file
diff --git a/login.sh b/login.sh
new file mode 100755
index 0000000..a8a6b08
--- /dev/null
+++ b/login.sh
@@ -0,0 +1,17 @@
+#!/bin/bash
+# Simple script to log in to Meta Ads MCP
+
+# Check for app ID in argument or environment variable
+if [ "$1" != "" ]; then
+ APP_ID="$1"
+elif [ "$META_APP_ID" != "" ]; then
+ APP_ID="$META_APP_ID"
+else
+ echo "Error: No Meta App ID provided."
+ echo "Usage: ./login.sh YOUR_APP_ID"
+ echo " or set the META_APP_ID environment variable."
+ exit 1
+fi
+
+echo "Starting Meta Ads authentication with App ID: $APP_ID"
+python meta_ads_generated.py --login --app-id "$APP_ID"
\ No newline at end of file
diff --git a/meta_ads_generated.py b/meta_ads_generated.py
index 67affc3..72cbaf5 100644
--- a/meta_ads_generated.py
+++ b/meta_ads_generated.py
@@ -5,9 +5,14 @@ import os
import base64
from mcp.server.fastmcp import FastMCP, Image
import datetime
-from urllib.parse import urlparse
+from urllib.parse import urlparse, parse_qs
from PIL import Image as PILImage
import io
+import webbrowser
+import time
+import platform
+import pathlib
+import argparse
# Initialize FastMCP server
mcp_server = FastMCP("meta-ads-generated")
@@ -17,9 +22,306 @@ 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
+
+# Auth constants
+AUTH_SCOPE = "ads_management,ads_read,business_management"
+AUTH_REDIRECT_URI = "http://localhost:8888/callback"
+AUTH_RESPONSE_TYPE = "token"
+
# Global store for ad creative images
ad_creative_images = {}
+# Authentication related classes
+class TokenInfo:
+ """Stores token information including expiration"""
+ def __init__(self, access_token: str, expires_in: int = None, user_id: str = None):
+ self.access_token = access_token
+ self.expires_in = expires_in
+ self.user_id = user_id
+ self.created_at = int(time.time())
+
+ def is_expired(self) -> bool:
+ """Check if the token is expired"""
+ if not self.expires_in:
+ return False # If no expiration is set, assume it's not expired
+
+ current_time = int(time.time())
+ return current_time > (self.created_at + self.expires_in)
+
+ def serialize(self) -> Dict[str, Any]:
+ """Convert to a dictionary for storage"""
+ return {
+ "access_token": self.access_token,
+ "expires_in": self.expires_in,
+ "user_id": self.user_id,
+ "created_at": self.created_at
+ }
+
+ @classmethod
+ def deserialize(cls, data: Dict[str, Any]) -> 'TokenInfo':
+ """Create from a stored dictionary"""
+ token = cls(
+ access_token=data.get("access_token", ""),
+ expires_in=data.get("expires_in"),
+ user_id=data.get("user_id")
+ )
+ token.created_at = data.get("created_at", int(time.time()))
+ return token
+
+
+class AuthManager:
+ """Manages authentication with Meta APIs"""
+ def __init__(self, app_id: str, redirect_uri: str = AUTH_REDIRECT_URI):
+ self.app_id = app_id
+ self.redirect_uri = redirect_uri
+ self.token_info = None
+ self._load_cached_token()
+
+ def _get_token_cache_path(self) -> pathlib.Path:
+ """Get the platform-specific path for token cache file"""
+ 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
+ cache_dir = base_path / "meta-ads-mcp"
+ cache_dir.mkdir(parents=True, exist_ok=True)
+
+ return cache_dir / "token_cache.json"
+
+ def _load_cached_token(self) -> bool:
+ """Load token from cache if available"""
+ cache_path = self._get_token_cache_path()
+
+ if not cache_path.exists():
+ return False
+
+ try:
+ with open(cache_path, "r") as f:
+ data = json.load(f)
+ self.token_info = TokenInfo.deserialize(data)
+
+ # Check if token is expired
+ if self.token_info.is_expired():
+ print("Cached token is expired")
+ self.token_info = None
+ return False
+
+ print(f"Loaded cached token (expires in {(self.token_info.created_at + self.token_info.expires_in) - int(time.time())} seconds)")
+ return True
+ except Exception as e:
+ print(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:
+ return
+
+ cache_path = self._get_token_cache_path()
+
+ try:
+ with open(cache_path, "w") as f:
+ json.dump(self.token_info.serialize(), f)
+ print(f"Token cached at: {cache_path}")
+ except Exception as e:
+ print(f"Error saving token to cache: {e}")
+
+ def get_auth_url(self) -> str:
+ """Generate the Facebook OAuth URL for desktop app flow"""
+ return (
+ f"https://www.facebook.com/v18.0/dialog/oauth?"
+ f"client_id={self.app_id}&"
+ f"redirect_uri={self.redirect_uri}&"
+ f"scope={AUTH_SCOPE}&"
+ f"response_type={AUTH_RESPONSE_TYPE}"
+ )
+
+ def start_local_server(self) -> str:
+ """
+ Start a local server to handle the OAuth callback.
+ Since we're using implicit flow with client-side token delivery,
+ we'll create a simple server that displays the token for the user to copy.
+
+ Returns:
+ The access token from the callback
+ """
+ import socket
+ from http.server import HTTPServer, BaseHTTPRequestHandler
+ import threading
+
+ token_container = {"token": None, "expires_in": None, "user_id": None}
+
+ class CallbackHandler(BaseHTTPRequestHandler):
+ def do_GET(self):
+ if self.path.startswith("/callback"):
+ # Return a page that extracts token from URL hash fragment
+ self.send_response(200)
+ self.send_header("Content-type", "text/html")
+ self.end_headers()
+
+ html = """
+ <html>
+ <head><title>Authentication Successful</title></head>
+ <body>
+ <h1>Authentication Successful!</h1>
+ <p>You can close this window and return to the application.</p>
+ <script>
+ // Extract token from URL hash
+ const hash = window.location.hash.substring(1);
+ const params = new URLSearchParams(hash);
+ const token = params.get('access_token');
+ const expires_in = params.get('expires_in');
+
+ // Send token back to server using fetch
+ fetch('/token?' + new URLSearchParams({
+ token: token,
+ expires_in: expires_in
+ }))
+ .then(response => console.log('Token sent to app'));
+ </script>
+ </body>
+ </html>
+ """
+ self.wfile.write(html.encode())
+ return
+
+ if self.path.startswith("/token"):
+ # Extract token from query params
+ query = parse_qs(urlparse(self.path).query)
+ token_container["token"] = query.get("token", [""])[0]
+
+ if "expires_in" in query:
+ try:
+ token_container["expires_in"] = int(query.get("expires_in", ["0"])[0])
+ except ValueError:
+ token_container["expires_in"] = None
+
+ # Send success response
+ self.send_response(200)
+ self.send_header("Content-type", "text/plain")
+ self.end_headers()
+ self.wfile.write(b"Token received")
+
+ # Signal the server to shut down
+ threading.Thread(target=server.shutdown).start()
+ return
+
+ # Silence server logs
+ def log_message(self, format, *args):
+ return
+
+ # Find an available port starting with 8888
+ port = 8888
+ max_attempts = 10
+ for attempt in range(max_attempts):
+ try:
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
+ s.bind(('localhost', port))
+ break
+ except OSError:
+ port += 1
+ if attempt == max_attempts - 1:
+ raise Exception(f"Could not find an available port after {max_attempts} attempts")
+
+ # Update redirect URI with actual port
+ self.redirect_uri = f"http://localhost:{port}/callback"
+
+ # Start HTTP server
+ server = HTTPServer(('localhost', port), CallbackHandler)
+ print(f"Callback server started on port {port}")
+
+ # Open browser with auth URL
+ auth_url = self.get_auth_url()
+ print(f"Opening browser with URL: {auth_url}")
+ webbrowser.open(auth_url)
+
+ # Run server until we get the token
+ server.serve_forever()
+
+ # Return the token
+ return token_container.get("token"), token_container.get("expires_in")
+
+ def authenticate(self, force_refresh: bool = False) -> Optional[str]:
+ """
+ Authenticate with Meta APIs
+
+ Args:
+ force_refresh: Force token refresh even if cached token exists
+
+ Returns:
+ Access token if successful, 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():
+ return self.token_info.access_token
+
+ # Start the OAuth flow
+ try:
+ token, expires_in = self.start_local_server()
+
+ if not token:
+ print("Authentication failed: No token received")
+ return None
+
+ self.token_info = TokenInfo(
+ access_token=token,
+ expires_in=expires_in
+ )
+
+ # Save token to cache
+ self._save_token_to_cache()
+
+ return self.token_info.access_token
+
+ except Exception as e:
+ print(f"Authentication error: {e}")
+ return None
+
+ def get_access_token(self) -> Optional[str]:
+ """
+ Get the current access token, refreshing if necessary
+
+ Returns:
+ Access token if available, None otherwise
+ """
+ if not self.token_info or self.token_info.is_expired():
+ return self.authenticate()
+
+ return self.token_info.access_token
+
+
+# Initialize auth manager
+auth_manager = AuthManager(META_APP_ID)
+
+# Function to get token without requiring it as a parameter
+async def get_current_access_token() -> str:
+ """
+ Get the current access token, triggering authentication if needed
+
+ Returns:
+ Current access token
+
+ Raises:
+ ValueError: If no token is available
+ """
+ token = auth_manager.get_access_token()
+ if not token:
+ token = auth_manager.authenticate(force_refresh=True)
+
+ if not token:
+ raise ValueError("Could not obtain a valid access token. Please try again.")
+
+ return token
+
class GraphAPIError(Exception):
"""Exception raised for errors from the Graph API."""
def __init__(self, error_data: Dict[str, Any]):
@@ -185,15 +487,19 @@ async def try_multiple_download_methods(url: str) -> Optional[bytes]:
#
@mcp_server.tool()
-async def get_ad_accounts(access_token: str, user_id: str = "me", limit: int = 10) -> str:
+async def get_ad_accounts(access_token: str = None, user_id: str = "me", limit: int = 10) -> str:
"""
Get ad accounts accessible by a user.
Args:
- access_token: Meta API access token
+ access_token: Meta API access token (optional - will use cached token if not provided)
user_id: Meta user ID or "me" for the current user
limit: Maximum number of accounts to return (default: 10)
"""
+ # Use provided token or get from auth manager
+ if not access_token:
+ access_token = await get_current_access_token()
+
endpoint = f"{user_id}/adaccounts"
params = {
"fields": "id,name,account_id,account_status,amount_spent,balance,currency,age,business_city,business_country_code",
@@ -205,14 +511,28 @@ async def get_ad_accounts(access_token: str, user_id: str = "me", limit: int = 1
return json.dumps(data, indent=2)
@mcp_server.tool()
-async def get_account_info(access_token: str, account_id: str) -> str:
+async def get_account_info(access_token: str = None, account_id: str = None) -> str:
"""
Get detailed information about a specific ad account.
Args:
- access_token: Meta API access token
+ access_token: Meta API access token (optional - will use cached token if not provided)
account_id: Meta Ads account ID (format: act_XXXXXXXXX)
"""
+ # Use provided token or get from auth manager
+ if not access_token:
+ access_token = await get_current_access_token()
+
+ # If no account ID is specified, try to get the first one for the user
+ if not account_id:
+ accounts_json = await get_ad_accounts(access_token, limit=1)
+ accounts_data = json.loads(accounts_json)
+
+ if "data" in accounts_data and accounts_data["data"]:
+ account_id = accounts_data["data"][0]["id"]
+ else:
+ return json.dumps({"error": "No account ID specified and no accounts found for user"}, indent=2)
+
# Ensure account_id has the 'act_' prefix for API compatibility
if not account_id.startswith("act_"):
account_id = f"act_{account_id}"
@@ -1130,6 +1450,41 @@ async def save_ad_image_via_api(access_token: str, ad_id: str) -> str:
return json.dumps(result, indent=2)
+# Helper function to start the login flow
+def login():
+ """
+ Start the login flow to authenticate with Meta
+ """
+ print("Starting Meta Ads authentication flow...")
+ token = auth_manager.authenticate(force_refresh=True)
+
+ if token:
+ print("Authentication successful!")
+ # Verify token works by getting basic user info
+ try:
+ import asyncio
+ result = asyncio.run(make_api_request("me", token, {}))
+ print(f"Authenticated as: {result.get('name', 'Unknown')} (ID: {result.get('id', 'Unknown')})")
+ except Exception as e:
+ print(f"Warning: Could not verify token: {e}")
+ else:
+ print("Authentication failed. Please try again.")
+
if __name__ == "__main__":
- # Initialize and run the server
- mcp_server.run(transport='stdio')
\ No newline at end of file
+ # Set up command line arguments
+ 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")
+
+ args = parser.parse_args()
+
+ # Update app ID if provided
+ if args.app_id:
+ auth_manager.app_id = args.app_id
+
+ # Handle login command
+ if args.login:
+ login()
+ else:
+ # Initialize and run the server
+ mcp_server.run(transport='stdio')
\ No newline at end of file
diff --git a/requirements.txt b/requirements.txt
index 6fc2df0..2e519d2 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -1,4 +1,4 @@
-mcp>=1.2.0
httpx>=0.26.0
-anyio>=4.0.0
-pydantic>=2.0.0
+mcp>=1.2.0
+Pillow>=10.0.0
+pathlib>=1.0.1
diff --git a/test_meta_ads_auth.py b/test_meta_ads_auth.py
new file mode 100644
index 0000000..2653565
--- /dev/null
+++ b/test_meta_ads_auth.py
@@ -0,0 +1,72 @@
+#!/usr/bin/env python3
+"""
+Test script for Meta Ads MCP authentication flow.
+This script shows how to authenticate with the Meta Ads API and run a simple command.
+"""
+
+import asyncio
+import argparse
+import json
+import os
+
+# Import the auth manager from our Meta Ads MCP module
+from meta_ads_generated import auth_manager, get_ad_accounts
+
+async def test_authentication(app_id=None, force_login=False):
+ """Test the authentication flow and run a simple command"""
+ print("===== Meta Ads MCP Authentication Test =====")
+
+ # Update app ID if provided
+ if app_id:
+ auth_manager.app_id = app_id
+ else:
+ # If no app ID is provided and META_APP_ID is the default, look for it in environment
+ if auth_manager.app_id == "YOUR_CLIENT_ID":
+ env_app_id = os.environ.get("META_APP_ID")
+ if env_app_id:
+ print(f"Using Meta App ID from environment: {env_app_id}")
+ auth_manager.app_id = env_app_id
+ else:
+ print("Warning: No Meta App ID provided. Please set META_APP_ID environment variable or use --app-id")
+
+ # Force authentication if requested
+ if force_login:
+ print("Forcing new authentication...")
+ token = auth_manager.authenticate(force_refresh=True)
+ else:
+ print("Getting access token (using cached token if available)...")
+ token = auth_manager.get_access_token()
+
+ if token:
+ # Mask token for display
+ masked_token = token[:10] + "..." + token[-5:]
+ print(f"Access token obtained: {masked_token}")
+
+ # Test the token by getting ad accounts
+ print("\nFetching ad accounts to test token...")
+ ad_accounts_json = await get_ad_accounts(token)
+ ad_accounts = json.loads(ad_accounts_json)
+
+ if "error" in ad_accounts:
+ print(f"Error fetching ad accounts: {ad_accounts['error']}")
+ else:
+ # Display accounts in a nice format
+ print("\nAd Accounts:")
+ if "data" in ad_accounts and ad_accounts["data"]:
+ for i, account in enumerate(ad_accounts["data"], 1):
+ print(f" {i}. {account.get('name', 'Unnamed')} (ID: {account.get('id', 'Unknown')})")
+ else:
+ print(" No ad accounts found.")
+ else:
+ print("Failed to obtain access token. Authentication failed.")
+
+ print("\n===== Test Complete =====")
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser(description="Test Meta Ads MCP authentication")
+ parser.add_argument("--app-id", type=str, help="Meta App ID (Client ID) for authentication")
+ parser.add_argument("--force-login", action="store_true", help="Force new login even if cached token exists")
+
+ args = parser.parse_args()
+
+ asyncio.run(test_authentication(app_id=args.app_id, force_login=args.force_login))
\ No newline at end of file