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
feat(auth)!: drop PIPEBOARD_API_TOKEN auth from the self-hosted package (#157)
Yves Junqueiracbe4c6351ec3
diff --git a/STREAMABLE_HTTP_SETUP.md b/STREAMABLE_HTTP_SETUP.mdindex 157d71b..f04d6e8 100644--- a/STREAMABLE_HTTP_SETUP.md+++ b/STREAMABLE_HTTP_SETUP.md@@ -18,12 +18,25 @@ python -m meta_ads_mcp --transport streamable-http --host 0.0.0.0 --port 9000### 2. Set Authentication-Set your Pipeboard token as an environment variable. This is optional for HTTP transport if you provide the token in the header, but it can be useful for command-line use.+When you run this server yourself, the credential is a **Meta access token** from+your own Meta app — create one at+[developers.facebook.com](https://developers.facebook.com/apps/). A Pipeboard API+token will not work here: the server passes whatever you give it straight to the+Meta Graph API.```bash-export PIPEBOARD_API_TOKEN=your_pipeboard_token+export META_ACCESS_TOKEN=your_meta_access_token```+Setting this is optional for the HTTP transport if you pass the token per request+in a header (see [Security Model](#security-model-read-before-exposing-the-port)),+but it is convenient for command-line use.++> Want to authenticate with a Pipeboard API token instead, and never handle a Meta+> token? Use the hosted MCP at `https://meta-ads.mcp.pipeboard.co/` rather than+> running this server. (`PIPEBOARD_API_TOKEN` is no longer supported by this+> package — see [Migration](#migration-from-stdio).)+### 3. Make HTTP RequestsThe server accepts JSON-RPC 2.0 requests at the `/mcp` endpoint. Use the `Authorization` header to provide your token.@@ -32,7 +45,7 @@ The server accepts JSON-RPC 2.0 requests at the `/mcp` endpoint. Use the `Authorcurl -X POST http://localhost:8080/mcp \-H "Content-Type: application/json" \-H "Accept: application/json, text/event-stream" \- -H "Authorization: Bearer your_pipeboard_token" \+ -H "Authorization: Bearer your_meta_access_token" \-d '{"jsonrpc": "2.0","method": "tools/call",@@ -75,7 +88,7 @@ deliberately different from stdio. Understanding it is the difference between asafe deployment and leaking your Meta account to the internet.- **stdio (local):** the server acts as whatever credential is configured in its- environment — `META_ACCESS_TOKEN`, `PIPEBOARD_API_TOKEN`, or a stored login.+ environment — `META_ACCESS_TOKEN` or a stored login from the local OAuth flow.Only the local process that launched it can talk to it, so this is expectedand safe. *If all you want is to use the MCP locally, prefer stdio.*@@ -106,33 +119,23 @@ safe deployment and leaking your Meta account to the internet.## Authentication-### Primary Method: Bearer Token (Recommended)+Which credential you use depends on **who runs the server**.-1. Sign up at [Pipeboard.co](https://pipeboard.co)-2. Generate an API token at [pipeboard.co/api-tokens](https://pipeboard.co/api-tokens)-3. Include the token in the `Authorization` HTTP header:+### Self-hosted: Meta access token++When you run this package yourself, supply a Meta access token from your own Meta+app. Create one at [developers.facebook.com](https://developers.facebook.com/apps/),+then pass it in the `Authorization` header:```bash-curl -H "Authorization: Bearer your_pipeboard_token" \+curl -H "Authorization: Bearer your_meta_access_token" \-X POST http://localhost:8080/mcp \-H "Content-Type: application/json" \-H "Accept: application/json, text/event-stream" \-d '{"jsonrpc":"2.0","method":"tools/list","id":1}'```-#### Remote MCP: Token in URL--When using the hosted Remote MCP at `https://mcp.pipeboard.co/meta-ads-mcp`, you can alternatively authenticate by including the token as a URL parameter:--```-https://mcp.pipeboard.co/meta-ads-mcp?token=YOUR_PIPEBOARD_TOKEN-```--This is particularly useful for MCP clients that don't support interactive authentication flows.--### Alternative Method: Direct Meta Token--If you have a Meta Developer App, you can use a direct access token via the `X-META-ACCESS-TOKEN` header. This is less common.+The `X-META-ACCESS-TOKEN` header is equivalent:```bashcurl -H "X-META-ACCESS-TOKEN: your_meta_access_token" \@@ -142,6 +145,28 @@ curl -H "X-META-ACCESS-TOKEN: your_meta_access_token" \-d '{"jsonrpc":"2.0","method":"tools/list","id":1}'```+### Hosted: Pipeboard API token++The hosted Remote MCP at `https://meta-ads.mcp.pipeboard.co/` accepts a **Pipeboard+API token** instead, so you never handle a Meta token yourself. Pipeboard resolves+the Meta credential server-side and enforces the API token's account and permission+scoping on every call.++1. Sign up at [Pipeboard.co](https://pipeboard.co)+2. Generate an API token at [pipeboard.co/api-tokens](https://pipeboard.co/api-tokens)+3. Point your MCP client at `https://meta-ads.mcp.pipeboard.co/` with+ `Authorization: Bearer <your_pipeboard_token>`++For clients that cannot send headers, the token may be passed as a URL parameter:++```+https://meta-ads.mcp.pipeboard.co/?token=YOUR_PIPEBOARD_TOKEN+```++> A Pipeboard API token only works against the hosted endpoint. Passing one to a+> server you run yourself will fail, because that server forwards the token+> directly to the Meta Graph API.+## Available Endpoints### Server URL Structure@@ -279,7 +304,7 @@ class MetaAdsMCPClient:return response.json()# Usage-client = MetaAdsMCPClient(token="your_pipeboard_token")+client = MetaAdsMCPClient(token="your_meta_access_token")result = client.call_tool("get_ad_accounts", {"limit": 5})print(json.dumps(result, indent=2))```@@ -323,7 +348,7 @@ class MetaAdsMCPClient {}// Usage-const client = new MetaAdsMCPClient('http://localhost:8080', 'your_pipeboard_token');+const client = new MetaAdsMCPClient('http://localhost:8080', 'your_meta_access_token');client.callTool('get_ad_accounts', { limit: 5 }).then(result => console.log(JSON.stringify(result, null, 2)));```@@ -362,11 +387,11 @@ CMD ["python", "-m", "meta_ads_mcp", "--transport", "streamable-http", "--host",### Environment Variables```bash-# For Pipeboard-based authentication. The token will be used for stdio,-# but for HTTP it should be passed in the Authorization header.-export PIPEBOARD_API_TOKEN=your_pipeboard_token+# Meta access token from your own Meta app. Used for stdio; for HTTP it can+# also be passed per request in the Authorization header.+export META_ACCESS_TOKEN=your_meta_access_token-# Optional (for custom Meta apps)+# Optional (for the local OAuth flow instead of a direct token)export META_APP_ID=your_app_idexport META_APP_SECRET=your_app_secret@@ -410,7 +435,13 @@ If you're currently using stdio transport with MCP clients, you can support both1. **Keep existing MCP client setup** (Claude Desktop, Cursor, etc.) using stdio.2. **Add HTTP transport** for web applications and custom integrations by running a separate server instance with the `--transport streamable-http` flag.3. **Use the same authentication method**:- - For stdio, the `PIPEBOARD_API_TOKEN` environment variable is used.+ - For stdio, the `META_ACCESS_TOKEN` environment variable is used.- For HTTP, pass the token in the `Authorization: Bearer <token>` header.+> **Removed:** `PIPEBOARD_API_TOKEN` used to exchange a Pipeboard API token for the+> underlying Meta access token. That exchange has been removed, because the Meta+> token it returned ignored the scoping on the API token that requested it. Either+> set `META_ACCESS_TOKEN` from your own Meta app, or use the hosted MCP at+> `https://meta-ads.mcp.pipeboard.co/`.+Both transports access the same Meta Ads functionality and use the same underlying authentication system.\ No newline at end of filediff --git a/examples/README.md b/examples/README.mdindex f0171cc..8e84e02 100644--- a/examples/README.md+++ b/examples/README.md@@ -8,7 +8,7 @@ This directory contains example scripts and usage demonstrations for the Meta AdA complete example HTTP client that demonstrates how to interact with the Meta Ads MCP server using the HTTP transport.**Features:**-- Shows how to authenticate with Pipeboard tokens or Meta access tokens+- Shows how to authenticate with a Meta access token- Demonstrates all basic MCP operations (initialize, list tools, call tools)- Includes error handling and response formatting- Ready-to-use client class for integration@@ -24,8 +24,8 @@ python http_client.py```**Authentication:**-- Set `PIPEBOARD_API_TOKEN` environment variable for Pipeboard auth-- Or pass `meta_access_token` parameter for direct Meta API auth+- Set the `META_ACCESS_TOKEN` environment variable, or pass the+ `meta_access_token` parameter, using a token from your own Meta app## Adding New Examplesdiff --git a/examples/example_http_client.py b/examples/example_http_client.pyindex 81c8f07..1c32b7a 100644--- a/examples/example_http_client.py+++ b/examples/example_http_client.py@@ -19,14 +19,12 @@ class MetaAdsMCPClient:"""Simple HTTP client for Meta Ads MCP server"""def __init__(self, base_url: str = "http://localhost:8080",- pipeboard_token: Optional[str] = None,meta_access_token: Optional[str] = None):"""Initialize the clientArgs:base_url: Base URL of the MCP server- pipeboard_token: Pipeboard API token (recommended)- meta_access_token: Direct Meta access token (fallback)+ meta_access_token: Meta access token from your own Meta app"""self.base_url = base_url.rstrip('/')self.endpoint = f"{self.base_url}/mcp/"@@ -40,12 +38,9 @@ class MetaAdsMCPClient:}# Add authentication- if pipeboard_token:- self.headers["Authorization"] = f"Bearer {pipeboard_token}"- print(f"✅ Using Pipeboard authentication")- elif meta_access_token:- self.headers["X-META-ACCESS-TOKEN"] = meta_access_token- print(f"✅ Using direct Meta token authentication")+ if meta_access_token:+ self.headers["Authorization"] = f"Bearer {meta_access_token}"+ print(f"✅ Using Meta access token authentication")else:print(f"⚠️ No authentication provided - tools will require auth")@@ -123,20 +118,16 @@ def main():print("="*60)# Check for authentication- pipeboard_token = os.environ.get("PIPEBOARD_API_TOKEN")meta_token = os.environ.get("META_ACCESS_TOKEN")-- if not pipeboard_token and not meta_token:- print("⚠️ No authentication tokens found in environment")- print(" Set PIPEBOARD_API_TOKEN or META_ACCESS_TOKEN for full functionality")++ if not meta_token:+ print("⚠️ No authentication token found in environment")+ print(" Set META_ACCESS_TOKEN for full functionality")print(" Using test token for demonstration...")- pipeboard_token = "demo_token_12345"-+ meta_token = "demo_token_12345"+# Create client- client = MetaAdsMCPClient(- pipeboard_token=pipeboard_token,- meta_access_token=meta_token- )+ client = MetaAdsMCPClient(meta_access_token=meta_token)# Test the MCP protocol flowprint("\n🔄 Testing MCP Protocol Flow")@@ -212,7 +203,7 @@ def main():print(" Tool Call: ✅ SUCCESS")print("\n🎉 Meta Ads MCP HTTP transport is fully functional!")print("\n💡 Next steps:")- print(" 1. Set PIPEBOARD_API_TOKEN environment variable")+ print(" 1. Set META_ACCESS_TOKEN environment variable")print(" 2. Call any of the 26 available Meta Ads tools")print(" 3. Build your web application or automation scripts")diff --git a/meta_ads_auth.sh b/meta_ads_auth.shdeleted file mode 100755index 4e93256..0000000--- a/meta_ads_auth.sh+++ /dev/null@@ -1,54 +0,0 @@-#!/bin/bash-echo "Starting Meta Ads MCP with Pipeboard authentication..."--# Set the Pipeboard API token as an environment variable-export PIPEBOARD_API_TOKEN="pk_8ee8c727644d4d32b646ddcf16f2385e"--# Check if the Pipeboard server is running and can handle meta auth-echo "Checking if Pipeboard meta auth endpoint is available..."-curl -s -o /dev/null -w "%{http_code}" "http://localhost:3000/api/meta" > /dev/null-if [ $? -ne 0 ]; then- echo "Warning: Could not connect to Pipeboard meta endpoint"- echo "Please make sure the Pipeboard server is running before proceeding."- echo "You can start it with: cd /path/to/pipeboard && npm run dev"- echo ""- echo "As a test, you can try running this command separately:"- echo "curl -X POST \"http://localhost:3000/api/meta/auth?api_token=pk_8ee8c727644d4d32b646ddcf16f2385e\" -H \"Content-Type: application/json\""- echo ""- read -p "Press Enter to continue anyway or Ctrl+C to abort..."-fi--# Try direct auth to test the endpoint-echo "Testing direct authentication with Pipeboard..."-AUTH_RESPONSE=$(curl -s -X POST "http://localhost:3000/api/meta/auth?api_token=pk_8ee8c727644d4d32b646ddcf16f2385e" -H "Content-Type: application/json")-if [[ $AUTH_RESPONSE == *"loginUrl"* ]]; then- echo "Authentication endpoint working correctly!"- LOGIN_URL=$(echo $AUTH_RESPONSE | grep -o 'https://[^"]*')- echo "Login URL: $LOGIN_URL"-- # Open the browser directly as a fallback- echo "Opening browser to login URL (as a fallback)..."- if [ "$(uname)" == "Darwin" ]; then- # macOS- open "$LOGIN_URL"- elif [ "$(expr substr $(uname -s) 1 5)" == "Linux" ]; then- # Linux- xdg-open "$LOGIN_URL" || firefox "$LOGIN_URL" || google-chrome "$LOGIN_URL" || echo "Could not open browser automatically"- else- # Windows or others- echo "Please open this URL in your browser manually: $LOGIN_URL"- fi-- echo "After authorizing in your browser, the MCP script will retrieve the token."-else- echo "Warning: Authentication endpoint test failed!"- echo "Response: $AUTH_RESPONSE"- read -p "Press Enter to continue anyway or Ctrl+C to abort..."-fi--# Run the meta-ads-mcp package-echo "Running Meta Ads MCP..."-python -m meta_ads_mcp--echo "Meta Ads MCP server is now running."-echo "If you had to manually authenticate, the token should be cached now."diff --git a/meta_ads_mcp/__init__.py b/meta_ads_mcp/__init__.pyindex ec27f1e..c66cb0d 100644--- a/meta_ads_mcp/__init__.py+++ b/meta_ads_mcp/__init__.py@@ -6,7 +6,7 @@ This package provides a Meta Ads MCP integrationfrom meta_ads_mcp.core.server import main-__version__ = "1.0.119"+__version__ = "1.0.120"__all__ = ['get_ad_accounts',diff --git a/meta_ads_mcp/core/api.py b/meta_ads_mcp/core/api.pyindex 5a9c00b..15b3484 100644--- a/meta_ads_mcp/core/api.py+++ b/meta_ads_mcp/core/api.py@@ -402,12 +402,9 @@ def meta_api_tool(func):else:logger.warning("No access token available from auth_manager")# Add more details about why token might be missing- if (auth_manager.app_id == "YOUR_META_APP_ID" or not auth_manager.app_id) and not auth_manager.use_pipeboard:+ if auth_manager.app_id == "YOUR_META_APP_ID" or not auth_manager.app_id:logger.error("TOKEN VALIDATION FAILED: No valid app_id configured")logger.error("Please set META_APP_ID environment variable or configure in your code")- elif auth_manager.use_pipeboard:- logger.error("TOKEN VALIDATION FAILED: Pipeboard authentication enabled but no valid token available")- logger.error("Complete authentication via Pipeboard service or check PIPEBOARD_API_TOKEN")else:logger.error("Check logs above for detailed token validation failures")except Exception as e:@@ -423,59 +420,51 @@ def meta_api_tool(func):# Add more specific troubleshooting informationauth_url = auth_manager.get_auth_url()app_id = auth_manager.app_id- using_pipeboard = auth_manager.use_pipeboard-+logger.error("TOKEN VALIDATION SUMMARY:")logger.error(f"- Current app_id: '{app_id}'")logger.error(f"- Environment META_APP_ID: '{os.environ.get('META_APP_ID', 'Not set')}'")- logger.error(f"- Pipeboard API token configured: {'Yes' if os.environ.get('PIPEBOARD_API_TOKEN') else 'No'}")- logger.error(f"- Using Pipeboard authentication: {'Yes' if using_pipeboard else 'No'}")-- # Check for common configuration issues - but only if not using Pipeboard- if not using_pipeboard and (app_id == "YOUR_META_APP_ID" or not app_id):+ logger.error(f"- META_ACCESS_TOKEN set: {'Yes' if os.environ.get('META_ACCESS_TOKEN') else 'No'}")++ if app_id == "YOUR_META_APP_ID" or not app_id:logger.error("ISSUE DETECTED: No valid Meta App ID configured")logger.error("ACTION REQUIRED: Set META_APP_ID environment variable with a valid App ID")- elif using_pipeboard:- logger.error("ISSUE DETECTED: Pipeboard authentication configured but no valid token available")- logger.error("ACTION REQUIRED: Complete authentication via Pipeboard service")-- # Provide different guidance based on authentication method- if using_pipeboard:- return json.dumps({- "error": {- "message": "Pipeboard Authentication Required",- "details": {- "description": "Your Pipeboard API token is invalid or has expired",- "action_required": "Update your Pipeboard token",- "setup_url": "https://pipeboard.co/setup",- "token_url": "https://pipeboard.co/api-tokens",- "configuration_status": {- "app_id_configured": bool(app_id) and app_id != "YOUR_META_APP_ID",- "pipeboard_enabled": True,- },- "troubleshooting": "Go to https://pipeboard.co/setup to verify your account setup, then visit https://pipeboard.co/api-tokens to obtain a new API token",- "setup_link": "[Verify your Pipeboard account setup](https://pipeboard.co/setup)",- "token_link": "[Get a new Pipeboard API token](https://pipeboard.co/api-tokens)"- }- }- }, indent=2)- else:- return json.dumps({- "error": {- "message": "Authentication Required",- "details": {- "description": "You need to authenticate with the Meta API before using this tool",- "action_required": "Please authenticate first",- "auth_url": auth_url,- "configuration_status": {- "app_id_configured": bool(app_id) and app_id != "YOUR_META_APP_ID",- "pipeboard_enabled": False,++ if os.environ.get("PIPEBOARD_API_TOKEN"):+ logger.error(+ "NOTE: PIPEBOARD_API_TOKEN is set but is ignored by this package. "+ "Use META_ACCESS_TOKEN, or the hosted MCP at "+ "https://meta-ads.mcp.pipeboard.co/ which does accept it. "+ "The Pipeboard CLI also still uses it, so leave it set if you use that."+ )++ return json.dumps({+ "error": {+ "message": "Authentication Required",+ "details": {+ "description": "You need to authenticate with the Meta API before using this tool",+ "action_required": "Please authenticate first",+ "auth_url": auth_url,+ "configuration_status": {+ "app_id_configured": bool(app_id) and app_id != "YOUR_META_APP_ID",+ },+ "options": [+ {+ "option": "Use the hosted Meta Ads MCP (no Meta app needed)",+ "url": "https://meta-ads.mcp.pipeboard.co/",+ "how": "Point your MCP client at this URL and authenticate with your Pipeboard API token."},- "troubleshooting": "Check logs for TOKEN VALIDATION FAILED messages",- "markdown_link": f"[Click here to authenticate with Meta Ads API]({auth_url})"- }+ {+ "option": "Bring your own Meta access token",+ "url": "https://developers.facebook.com/apps/",+ "how": "Create your own Meta app, generate an access token, and set META_ACCESS_TOKEN."+ }+ ],+ "troubleshooting": "Check logs for TOKEN VALIDATION FAILED messages",+ "markdown_link": f"[Click here to authenticate with Meta Ads API]({auth_url})"}- }, indent=2)+ }+ }, indent=2)# Call the original functionresult = await func(*args, **kwargs)diff --git a/meta_ads_mcp/core/auth.py b/meta_ads_mcp/core/auth.pyindex b8a8eb4..75bca3b 100644--- a/meta_ads_mcp/core/auth.py+++ b/meta_ads_mcp/core/auth.py@@ -19,9 +19,6 @@ from .callback_server import (callback_server_port)-# Import the new Pipeboard authentication-from .pipeboard_auth import pipeboard_auth_manager-# Auth constants# Scope includes pages_show_list and pages_read_engagement to fix issue #16# where get_account_pages failed for regular users due to missing page permissions@@ -129,10 +126,7 @@ class AuthManager:self.app_id = app_idself.redirect_uri = redirect_uriself.token_info = None- # Check for Pipeboard token first- self.use_pipeboard = bool(os.environ.get("PIPEBOARD_API_TOKEN", ""))- if not self.use_pipeboard:- self._load_cached_token()+ self._load_cached_token()def _get_token_cache_path(self) -> pathlib.Path:"""Get the platform-specific path for token cache file"""@@ -243,12 +237,6 @@ 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@@ -283,10 +271,6 @@ 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@@ -294,11 +278,6 @@ 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:logger.info(f"Invalidating token: {self.token_info.access_token[:10]}...")self.token_info = None@@ -460,11 +439,8 @@ async def get_current_access_token() -> Optional[str]:app_id = meta_config.get_app_id()logger.debug(f"Current app_id: {app_id}")- # Check if using Pipeboard authentication- using_pipeboard = auth_manager.use_pipeboard-- # Check if app_id is valid - but only if not using Pipeboard authentication- if not app_id and not using_pipeboard:+ # Check if app_id is valid+ if not app_id:logger.error("TOKEN VALIDATION FAILED: No valid app_id configured")logger.error("Please set META_APP_ID environment variable or configure via meta_config.set_app_id()")return None@@ -524,9 +500,9 @@ def login():port = start_callback_server()except Exception as callback_error:print(f"Error: {callback_error}")- print("Callback server is disabled. Please use alternative authentication methods:")- print("- Set PIPEBOARD_API_TOKEN environment variable for Pipeboard authentication")- print("- Or provide a direct META_ACCESS_TOKEN environment variable")+ print("Callback server is disabled. Please use an alternative authentication method:")+ print("- Set META_ACCESS_TOKEN to an access token from your own Meta app")+ print("- Or use the hosted Pipeboard MCP at https://meta-ads.mcp.pipeboard.co/")return# Get the auth URL and open the browserdiff --git a/meta_ads_mcp/core/authentication.py b/meta_ads_mcp/core/authentication.pyindex 9cdbcdd..98f6570 100644--- a/meta_ads_mcp/core/authentication.py+++ b/meta_ads_mcp/core/authentication.py@@ -1,26 +1,30 @@"""Authentication-specific functionality for Meta Ads API.-The Meta Ads MCP server supports three authentication modes:+Running this package yourself requires a Meta access token of your own. There are+two ways to get one:-1. **Development/Local Mode** (default)- - Uses local callback server on localhost:8080+ for OAuth redirect- - Requires META_ADS_DISABLE_CALLBACK_SERVER to NOT be set- - Best for local development and testing+1. **Direct token** (simplest)+ - Set META_ACCESS_TOKEN to a token generated from your own Meta app+ - Takes precedence over every other mechanism-2. **Production with API Token**- - Uses PIPEBOARD_API_TOKEN for server-to-server authentication- - Bypasses OAuth flow entirely- - Best for server deployments with pre-configured tokens+2. **Local OAuth flow** (default when META_ACCESS_TOKEN is unset)+ - Requires META_APP_ID for your own Meta app+ - Uses a local callback server on localhost:8080+ for the OAuth redirect+ - Disabled when META_ADS_DISABLE_CALLBACK_SERVER is set-3. **Production OAuth Flow** (NEW)- - Uses Pipeboard OAuth endpoints for dynamic client registration- - Triggered when META_ADS_DISABLE_CALLBACK_SERVER is set but no PIPEBOARD_API_TOKEN- - Supports MCP clients that implement OAuth 2.0 discovery+If you would rather not run a Meta app at all, use the hosted MCP at+https://meta-ads.mcp.pipeboard.co/ and authenticate with a Pipeboard API token.+Pipeboard then calls the Meta API on your behalf and the Meta token is never+exposed to the client.++Note: PIPEBOARD_API_TOKEN is no longer supported. It used to exchange a Pipeboard+API token for the underlying Meta access token, which defeated the scoping on that+API token; the endpoint behind it has been removed.Environment Variables:-- PIPEBOARD_API_TOKEN: Enables mode 2 (token-based auth)-- META_ADS_DISABLE_CALLBACK_SERVER: Disables local server, enables mode 3-- META_ACCESS_TOKEN: Direct Meta token (fallback)+- META_ACCESS_TOKEN: Direct Meta token (highest precedence)+- META_APP_ID / META_APP_SECRET: Your own Meta app, for the local OAuth flow+- META_ADS_DISABLE_CALLBACK_SERVER: Disables the local callback server- META_ADS_DISABLE_LOGIN_LINK: Hard-disables the get_login_link tool; returns a disabled message"""@@ -33,7 +37,6 @@ from . import authfrom .auth import start_callback_server, shutdown_callback_server, auth_managerfrom .server import mcp_serverfrom .utils import logger, META_APP_SECRET-from .pipeboard_auth import pipeboard_auth_manager# Only register the login link tool if not explicitly disabledENABLE_LOGIN_LINK = not bool(os.environ.get("META_ADS_DISABLE_LOGIN_LINK", ""))@@ -43,97 +46,39 @@ async def get_login_link(access_token: Optional[str] = None) -> str:"""Get a clickable login link for Meta Ads authentication.- NOTE: This method should only be used if you're using your own Facebook app.- If using Pipeboard authentication (recommended), set the PIPEBOARD_API_TOKEN- environment variable instead (token obtainable via https://pipeboard.co).-+ NOTE: This method requires your own Facebook app (META_APP_ID). If you would+ rather not run one, use the hosted MCP at https://meta-ads.mcp.pipeboard.co/+ instead, which authenticates with a Pipeboard API token.+Args:access_token: Meta API access token (optional - will use cached token if not provided)Returns:A clickable resource link for Meta authentication"""- # Check if we're using pipeboard authentication- using_pipeboard = bool(os.environ.get("PIPEBOARD_API_TOKEN", ""))callback_server_disabled = bool(os.environ.get("META_ADS_DISABLE_CALLBACK_SERVER", ""))-- if using_pipeboard:- # Pipeboard token-based authentication- try:- logger.info("Using Pipeboard token-based authentication")-- # If an access token was provided, this is likely a test - return success- if access_token:- return json.dumps({- "message": "✅ Authentication Token Provided",- "status": "Using provided access token for authentication",- "token_info": f"Token preview: {access_token[:10]}...",- "authentication_method": "manual_token",- "ready_to_use": "You can now use all Meta Ads MCP tools and commands."- }, indent=2)-- # Check if Pipeboard token is working- token = pipeboard_auth_manager.get_access_token()- if token:- return json.dumps({- "message": "✅ Already Authenticated",- "status": "You're successfully authenticated with Meta Ads via Pipeboard!",- "token_info": f"Token preview: {token[:10]}...",- "authentication_method": "pipeboard_token",- "ready_to_use": "You can now use all Meta Ads MCP tools and commands."- }, indent=2)-- # Start Pipeboard auth flow- auth_data = pipeboard_auth_manager.initiate_auth_flow()- login_url = auth_data.get('loginUrl')-- if login_url:- return json.dumps({- "message": "🔗 Click to Authenticate",- "login_url": login_url,- "markdown_link": f"[🚀 Authenticate with Meta Ads]({login_url})",- "instructions": "Click the link above to complete authentication with Meta Ads.",- "authentication_method": "pipeboard_oauth",- "what_happens_next": "After clicking, you'll be redirected to Meta's authentication page. Once completed, your token will be automatically saved.",- "token_duration": "Your token will be valid for approximately 60 days."- }, indent=2)- else:- return json.dumps({- "message": "❌ Authentication Error",- "error": "Could not generate authentication URL from Pipeboard",- "troubleshooting": [- "Check that your PIPEBOARD_API_TOKEN is valid",- "Ensure the Pipeboard service is accessible",- "Try again in a few moments"- ],- "authentication_method": "pipeboard_oauth_failed"- }, indent=2)-- except Exception as e:- logger.error(f"Error initiating Pipeboard auth flow: {e}")- return json.dumps({- "message": "❌ Pipeboard Authentication Error",- "error": f"Failed to initiate Pipeboard authentication: {str(e)}",- "troubleshooting": [- "✅ Check that PIPEBOARD_API_TOKEN environment variable is set correctly",- "🌐 Verify that pipeboard.co is accessible from your network",- "🔄 Try refreshing your Pipeboard API token",- "⏰ Wait a moment and try again"- ],- "get_help": "Contact support if the issue persists",- "authentication_method": "pipeboard_error"- }, indent=2)- elif callback_server_disabled:- # Production OAuth flow - use Pipeboard OAuth endpoints directly- logger.info("Production OAuth flow - using Pipeboard OAuth endpoints")-++ if callback_server_disabled:+ # No local callback server, so the browser-based OAuth flow is unavailable.+ # Point at the two remaining ways to supply a token.+ logger.info("Callback server disabled - cannot run the local OAuth flow")+return json.dumps({"message": "🔐 Authentication Required",- "instructions": "Please sign in to your Pipeboard account to authenticate with Meta Ads.",- "sign_in_url": "https://pipeboard.co/auth/signin",- "markdown_link": "[🚀 Sign in to Pipeboard](https://pipeboard.co/auth/signin)",- "what_to_do": "Click the link above to sign in to your Pipeboard account and complete authentication.",- "authentication_method": "production_oauth"+ "reason": "The local callback server is disabled (META_ADS_DISABLE_CALLBACK_SERVER), so the browser OAuth flow cannot run.",+ "options": [+ {+ "option": "Use the hosted Meta Ads MCP (recommended)",+ "url": "https://meta-ads.mcp.pipeboard.co/",+ "how": "Point your MCP client at this URL and authenticate with your Pipeboard API token. Pipeboard calls the Meta API for you, so no Meta token is needed locally."+ },+ {+ "option": "Bring your own Meta access token",+ "url": "https://developers.facebook.com/apps/",+ "how": "Create your own Meta app, generate an access token, and set META_ACCESS_TOKEN before starting the server."+ }+ ],+ "authentication_method": "callback_server_disabled"}, indent=2)else:# Original Meta authentication flow (development/local)@@ -173,8 +118,8 @@ async def get_login_link(access_token: Optional[str] = None) -> str:"error": "Cannot start local callback server for authentication","reason": str(e),"solutions": [- "🌐 Use Pipeboard authentication: Set PIPEBOARD_API_TOKEN environment variable",- "🔑 Use direct token: Set META_ACCESS_TOKEN environment variable",+ "🔑 Use direct token: Set META_ACCESS_TOKEN environment variable",+ "🌐 Use the hosted MCP at https://meta-ads.mcp.pipeboard.co/ with your Pipeboard API token","🔧 Check if another service is using the required ports"],"authentication_method": "meta_oauth_disabled"diff --git a/meta_ads_mcp/core/pipeboard_auth.py b/meta_ads_mcp/core/pipeboard_auth.pydeleted file mode 100644index fd1e26e..0000000--- a/meta_ads_mcp/core/pipeboard_auth.py+++ /dev/null@@ -1,514 +0,0 @@-"""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"--# Debug message about API base URL-logger.info(f"Pipeboard API base URL: {PIPEBOARD_API_BASE}")--class TokenInfo:- """Stores token information including expiration"""- def __init__(self, access_token: str, expires_at: Optional[str] = None, token_type: Optional[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")- if self.api_token:- logger.info("Pipeboard authentication enabled. Will use pipeboard.co for Meta authentication.")- else:- logger.info("Pipeboard authentication not enabled. Set PIPEBOARD_API_TOKEN environment variable to enable.")- self.token_info = None- # Note: Token caching is disabled to always fetch fresh tokens from Pipeboard-- 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)-- # Validate the cached data structure- required_fields = ["access_token"]- if not all(field in data for field in required_fields):- logger.warning("Cached token data is missing required fields")- return False-- # Check if the token looks valid (basic format check)- if not data.get("access_token") or len(data["access_token"]) < 20:- logger.warning("Cached token appears malformed")- return False-- 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, removing cache file")- # Remove the expired cache file- try:- cache_path.unlink()- logger.info(f"Removed expired token cache: {cache_path}")- except Exception as e:- logger.warning(f"Could not remove expired cache file: {e}")- self.token_info = None- return False-- # Additional validation: check if token is too old (more than 60 days)- current_time = int(time.time())- if self.token_info.created_at and (current_time - self.token_info.created_at) > (60 * 24 * 3600):- logger.warning("Cached token is too old (more than 60 days), removing cache file")- try:- cache_path.unlink()- logger.info(f"Removed old token cache: {cache_path}")- except Exception as e:- logger.warning(f"Could not remove old cache file: {e}")- 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}")- # If there's any error reading the cache, try to remove the corrupted file- try:- cache_path.unlink()- logger.info(f"Removed corrupted token cache: {cache_path}")- except Exception as cleanup_error:- logger.warning(f"Could not remove corrupted cache file: {cleanup_error}")- return False- except Exception as e:- logger.error(f"Error loading cached token: {e}")- # If there's any error reading the cache, try to remove the corrupted file- try:- cache_path.unlink()- logger.info(f"Removed corrupted token cache: {cache_path}")- except Exception as cleanup_error:- logger.warning(f"Could not remove corrupted cache file: {cleanup_error}")- 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")-- # Exactly match the format used in meta_auth_test.sh- url = f"{PIPEBOARD_API_BASE}/meta/auth?api_token={self.api_token}"- headers = {- "Content-Type": "application/json"- }-- logger.info(f"Initiating auth flow with POST request to {url}")-- try:- # Make the POST request exactly as in the working meta_auth_test.sh script- response = requests.post(url, headers=headers)- logger.info(f"Auth flow response status: {response.status_code}")-- # Better error handling- if response.status_code != 200:- logger.error(f"Auth flow error: HTTP {response.status_code}")- error_text = response.text if response.text else "No response content"- logger.error(f"Response content: {error_text}")- if response.status_code == 404:- raise ValueError(f"Pipeboard API endpoint not found. Check if the server is running at {PIPEBOARD_API_BASE}")- elif response.status_code == 401:- raise ValueError(f"Unauthorized: Invalid API token. Check your PIPEBOARD_API_TOKEN.")-- response.raise_for_status()-- # Parse the response- try:- data = response.json()- logger.info(f"Received response keys: {', '.join(data.keys())}")- except json.JSONDecodeError:- logger.error(f"Could not parse JSON response: {response.text}")- raise ValueError(f"Invalid JSON response from auth endpoint: {response.text[:100]}")-- # Log auth flow response (without sensitive information)- if 'loginUrl' in data:- logger.info(f"Auth flow initiated successfully with login URL: {data['loginUrl'][:30]}...")- else:- logger.warning(f"Auth flow response missing loginUrl field. Response keys: {', '.join(data.keys())}")-- 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- """- # First check if API token is configured- if not self.api_token:- logger.error("TOKEN VALIDATION FAILED: No Pipeboard API token configured")- logger.error("Please set PIPEBOARD_API_TOKEN environment variable")- return None-- logger.info("Getting fresh token from Pipeboard (caching disabled)")-- # If force refresh or no token/expired token, get a new one from Pipeboard- try:- # Make a request to get the token, using the same URL format as initiate_auth_flow- url = f"{PIPEBOARD_API_BASE}/meta/token?api_token={self.api_token}"- headers = {- "Content-Type": "application/json"- }-- logger.info(f"Requesting token from {url}")-- # Add timeout for better error messages- try:- response = requests.get(url, headers=headers, timeout=10)- except requests.exceptions.Timeout:- logger.error("TOKEN VALIDATION FAILED: Timeout while connecting to Pipeboard API")- logger.error(f"Could not connect to {PIPEBOARD_API_BASE} within 10 seconds")- return None- except requests.exceptions.ConnectionError:- logger.error("TOKEN VALIDATION FAILED: Connection error with Pipeboard API")- logger.error(f"Could not connect to {PIPEBOARD_API_BASE} - check if service is running")- return None-- logger.info(f"Token request response status: {response.status_code}")-- # Better error handling with response content- if response.status_code != 200:- logger.error(f"TOKEN VALIDATION FAILED: HTTP error {response.status_code}")- error_text = response.text if response.text else "No response content"- logger.error(f"Response content: {error_text}")-- # Add more specific error messages for common status codes- if response.status_code == 401:- logger.error("Authentication failed: Invalid Pipeboard API token")- elif response.status_code == 404:- logger.error("Endpoint not found: Check if Pipeboard API service is running correctly")- elif response.status_code == 400:- logger.error("Bad request: The request to Pipeboard API was malformed")-- response.raise_for_status()-- try:- data = response.json()- logger.info(f"Received token response with keys: {', '.join(data.keys())}")- except json.JSONDecodeError:- logger.error("TOKEN VALIDATION FAILED: Invalid JSON response from Pipeboard API")- logger.error(f"Response content (first 100 chars): {response.text[:100]}")- return None-- # Validate response data- if "access_token" not in data:- logger.error("TOKEN VALIDATION FAILED: No access_token in Pipeboard API response")- logger.error(f"Response keys: {', '.join(data.keys())}")- if "error" in data:- logger.error(f"Error details: {data['error']}")- else:- logger.error("No error information available in response")- 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")- )-- # Note: Token caching is disabled-- 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: {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}")- # Return None so caller can handle the auth flow- return None- else:- logger.error(f"Error getting access token (status {status_code}): {e}")- logger.error(f"Response content: {response_text}")- 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")- logger.error("TOKEN VALIDATION FAILED: Missing token to test")- return False-- # Log token details for debugging (partial token for security)- masked_token = self.token_info.access_token[:5] + "..." + self.token_info.access_token[-5:] if self.token_info.access_token else "None"- token_type = self.token_info.token_type if hasattr(self.token_info, 'token_type') and self.token_info.token_type else "bearer"- logger.debug(f"Testing token validity (token: {masked_token}, type: {token_type})")-- try:- # Make a simple request to the /me endpoint to test the token- META_GRAPH_API_VERSION = "v24.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}")-- # Add timeout and better error handling- try:- response = requests.get(url, headers=headers, timeout=10)- except requests.exceptions.Timeout:- logger.error("TOKEN VALIDATION FAILED: Timeout while connecting to Meta API")- logger.error("The Graph API did not respond within 10 seconds")- return False- except requests.exceptions.ConnectionError:- logger.error("TOKEN VALIDATION FAILED: Connection error with Meta API")- logger.error("Could not establish connection to Graph API - check network connectivity")- return False-- if response.status_code == 200:- data = response.json()- logger.debug(f"Token is valid. User ID: {data.get('id')}")- # Add more useful user information for debugging- user_info = f"User ID: {data.get('id')}"- if 'name' in data:- user_info += f", Name: {data.get('name')}"- logger.info(f"Meta API token validated successfully ({user_info})")- return True- else:- logger.error(f"TOKEN VALIDATION FAILED: API returned status {response.status_code}")-- # Try to parse the error response for more detailed information- try:- error_data = response.json()- if 'error' in error_data:- error_obj = error_data.get('error', {})- error_code = error_obj.get('code', 'unknown')- error_message = error_obj.get('message', 'Unknown error')- logger.error(f"Meta API error: Code {error_code} - {error_message}")-- # Add specific guidance for common error codes- if error_code == 190:- logger.error("Error indicates the token is invalid or has expired")- elif error_code == 4:- logger.error("Error indicates rate limiting - too many requests")- elif error_code == 200:- logger.error("Error indicates API permissions or configuration issue")- else:- logger.error(f"No error object in response: {error_data}")- except json.JSONDecodeError:- logger.error(f"Could not parse error response: {response.text[:200]}")-- return False- except Exception as e:- logger.error(f"TOKEN VALIDATION FAILED: Unexpected error: {str(e)}")-- # Add stack trace for debugging complex issues- import traceback- logger.error(f"Stack trace: {traceback.format_exc()}")-- return False---# Create singleton instance-pipeboard_auth_manager = PipeboardAuthManager()\ No newline at end of filediff --git a/meta_ads_mcp/core/server.py b/meta_ads_mcp/core/server.pyindex 5a4e629..2229b5b 100644--- a/meta_ads_mcp/core/server.py+++ b/meta_ads_mcp/core/server.py@@ -4,14 +4,11 @@ from mcp.server.fastmcp import FastMCPimport argparseimport osimport sys-import webbrowserimport jsonfrom typing import Dict, Any, Optionalfrom .auth import login as login_authfrom .resources import list_resources, get_resourcefrom .utils import logger-from .pipeboard_auth import pipeboard_auth_manager-import time# Initialize FastMCP servermcp_server = FastMCP("meta-ads")@@ -74,12 +71,12 @@ class StreamableHTTPHandler:"""# Security validation - only allow safe headersALLOWED_VIA_HEADERS = {- 'pipeboard_api_token': True, # ✅ Primary method - simple and secure+ 'bearer_token': True, # ✅ Primary method - Meta access token'meta_app_id': True, # ✅ Fallback only - triggers OAuth complexity'meta_app_secret': False, # ❌ Server environment only- 'meta_access_token': False, # ❌ Use proper auth flows instead+ 'meta_access_token': False, # ❌ Use the Authorization header instead}-+# PRIMARY: Check for Bearer token in Authorization header (handles 90%+ of cases)auth_header = request_headers.get('Authorization') or request_headers.get('authorization')if auth_header and auth_header.lower().startswith('bearer '):@@ -272,52 +269,29 @@ def main():login_cli()return 0- # Check for Pipeboard authentication and token- pipeboard_api_token = os.environ.get("PIPEBOARD_API_TOKEN")- if pipeboard_api_token:- logger.info("Using Pipeboard authentication")- print("✅ Pipeboard authentication enabled")- print(f" API token: {pipeboard_api_token[:8]}...{pipeboard_api_token[-4:]}")- # Check for existing token- token = pipeboard_auth_manager.get_access_token()- if not token:- logger.info("No valid Pipeboard token found. Initiating browser-based authentication flow.")- print("No valid Meta token found. Opening browser for authentication...")- try:- # Initialize the auth flow and get the login URL- auth_data = pipeboard_auth_manager.initiate_auth_flow()- login_url = auth_data.get('loginUrl')- if login_url:- logger.info(f"Opening browser with login URL: {login_url}")- webbrowser.open(login_url)- print("Please authorize the application in your browser.")- print("After authorization, the token will be automatically retrieved.")- print("Waiting for authentication to complete...")-- # Poll for token completion- max_attempts = 30 # Try for 30 * 2 = 60 seconds- for attempt in range(max_attempts):- print(f"Waiting for authentication... ({attempt+1}/{max_attempts})")- # Try to get the token again- token = pipeboard_auth_manager.get_access_token(force_refresh=True)- if token:- print("Authentication successful!")- break- time.sleep(2) # Wait 2 seconds between attempts-- if not token:- print("Authentication timed out. Starting server anyway.")- print("You may need to restart the server after completing authentication.")- else:- logger.error("No login URL received from Pipeboard API")- print("Error: Could not get authentication URL. Check your API token.")- except Exception as e:- logger.error(f"Error initiating browser-based authentication: {e}")- print(f"Error: Could not start authentication: {e}")- else:- print(f"✅ Valid Pipeboard access token found")- print(f" Token preview: {token[:10]}...{token[-5:]}")-+ # PIPEBOARD_API_TOKEN used to exchange a Pipeboard API token for the underlying+ # Meta access token via pipeboard.co. That endpoint has been removed, because the+ # token it returned ignored the API token's account/permission scoping. Warn+ # anyone still setting it so the failure is self-explanatory.+ if os.environ.get("PIPEBOARD_API_TOKEN"):+ logger.warning("PIPEBOARD_API_TOKEN is set but is ignored by meta-ads-mcp.")+ print(+ "⚠️ PIPEBOARD_API_TOKEN is set but is ignored by meta-ads-mcp.",+ file=sys.stderr,+ )+ print(+ " Pipeboard no longer hands out the underlying Meta access token. To authenticate\n"+ " this server, either:\n"+ " - create your own app at https://developers.facebook.com/apps/ and set "+ "META_ACCESS_TOKEN, or\n"+ " - skip running this server and use the hosted MCP at "+ "https://meta-ads.mcp.pipeboard.co/\n"+ " (which does authenticate with your Pipeboard API token).\n"+ " Keep the variable set if you use the Pipeboard CLI or the hosted MCP - they\n"+ " still use it. Only this package ignores it.",+ file=sys.stderr,+ )+# Transport-specific server initialization and startupif args.transport == "streamable-http":logger.info(f"Starting MCP server with Streamable HTTP transport on {args.host}:{args.port}")diff --git a/meta_ads_mcp/core/utils.py b/meta_ads_mcp/core/utils.pyindex 84d8d6a..874382e 100644--- a/meta_ads_mcp/core/utils.py+++ b/meta_ads_mcp/core/utils.py@@ -14,26 +14,27 @@ import pathlibimport platformimport ipaddressimport socket+import sysfrom urllib.parse import urlparse# Check for Meta app credentials in environmentMETA_APP_ID = os.environ.get("META_APP_ID", "")META_APP_SECRET = os.environ.get("META_APP_SECRET", "")-# 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", ""))+# A direct META_ACCESS_TOKEN needs neither an app id nor an app secret, so these+# warnings only apply when we might have to run the local OAuth flow.+using_direct_token = bool(os.environ.get("META_ACCESS_TOKEN", ""))-# Print warning if Meta app credentials are not configured and not using Pipeboard-if not using_pipeboard:+# Written to stderr on purpose: stdout is the JSON-RPC channel on the stdio+# transport, so printing there corrupts the protocol stream.+if not using_direct_token:if not META_APP_ID:- print("WARNING: META_APP_ID environment variable is not set.")- print("RECOMMENDED: Use Pipeboard authentication by setting PIPEBOARD_API_TOKEN instead.")- print("ALTERNATIVE: For direct Meta authentication, set META_APP_ID to your Meta App ID.")+ print("WARNING: META_APP_ID environment variable is not set.", file=sys.stderr)+ print("RECOMMENDED: Set META_ACCESS_TOKEN to a token from your own Meta app.", file=sys.stderr)+ print("ALTERNATIVE: Set META_APP_ID to your Meta App ID to use the local OAuth flow.", file=sys.stderr)if not META_APP_SECRET:- print("WARNING: META_APP_SECRET environment variable is not set.")- print("NOTE: This is only needed for direct Meta authentication. Pipeboard authentication doesn't require this.")- print("RECOMMENDED: Use Pipeboard authentication by setting PIPEBOARD_API_TOKEN instead.")+ print("WARNING: META_APP_SECRET environment variable is not set.", file=sys.stderr)+ print("NOTE: This is only needed to exchange a short-lived token for a long-lived one.", file=sys.stderr)# Configure logging to filedef setup_logging():@@ -67,7 +68,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}")+ logger.info(f"Using META_ACCESS_TOKEN from environment: {using_direct_token}")return loggerdiff --git a/pyproject.toml b/pyproject.tomlindex a034611..ca14900 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -4,7 +4,7 @@ build-backend = "hatchling.build"[project]name = "meta-ads-mcp"-version = "1.0.119"+version = "1.0.120"description = "Model Context Protocol (MCP) server for Meta Ads - Use Remote MCP at pipeboard.co for easiest setup"readme = "README.md"requires-python = ">=3.10"diff --git a/server.json b/server.jsonindex f345959..3cb3f2a 100644--- a/server.json+++ b/server.json@@ -2,7 +2,7 @@"$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json","name": "co.pipeboard/meta-ads-mcp","description": "Facebook / Meta Ads automation with AI: analyze performance, test creatives, optimize spend.",- "version": "1.0.119",+ "version": "1.0.120","remotes": [{"type": "streamable-http",diff --git a/smithery.yaml b/smithery.yamlindex 8b74c76..a545150 100644--- a/smithery.yaml+++ b/smithery.yaml@@ -3,28 +3,28 @@ startCommand:configSchema:type: objectproperties:- pipeboardApiToken:+ metaAccessToken:type: string- description: "Pipeboard API token for Meta authentication (recommended). Get your free token at https://pipeboard.co"+ description: "Meta access token from your own Meta app (recommended). Create an app at https://developers.facebook.com/apps/"metaAppId:type: string- description: "Meta App ID (Client ID) for direct OAuth method (only needed if not using Pipeboard authentication)"+ description: "Meta App ID (Client ID), for the local OAuth flow when no metaAccessToken is supplied"required: []commandFunction: |(config) => {const env = {};const args = ["-m", "meta_ads_mcp"];-- // Add Pipeboard API token to environment if provided (recommended auth method)- if (config.pipeboardApiToken) {- env.PIPEBOARD_API_TOKEN = config.pipeboardApiToken;++ // Add Meta access token to environment if provided (recommended auth method)+ if (config.metaAccessToken) {+ env.META_ACCESS_TOKEN = config.metaAccessToken;}-- // Add Meta App ID as command-line argument if provided (alternative auth method)++ // Add Meta App ID as command-line argument if provided (local OAuth flow)if (config.metaAppId) {args.push("--app-id", config.metaAppId);}-+return {command: 'python',args: args,diff --git a/tests/README.md b/tests/README.mdindex c02a37e..d86319a 100644--- a/tests/README.md+++ b/tests/README.md@@ -61,9 +61,9 @@ python -m tests.test_http_transport### ✅ Authentication Integration- **No Authentication** - Proper rejection of unauthenticated requests-- **Pipeboard Token** - Primary authentication method (`X-PIPEBOARD-API-TOKEN`)+- **Bearer Token** - Primary authentication method (`Authorization: Bearer <meta token>`)- **Meta App ID** - Fallback authentication method (`X-META-APP-ID`)-- **Multiple Auth Methods** - Priority handling (Pipeboard takes precedence)+- **Multiple Auth Methods** - Priority handling (bearer token takes precedence)### ✅ Tool Execution- All 26 Meta Ads tools accessible via HTTP@@ -75,9 +75,9 @@ python -m tests.test_http_transportThe test suite runs multiple authentication scenarios:1. **No Authentication**: Tests that tools properly require authentication-2. **Pipeboard Token**: Tests the primary authentication path+2. **Bearer Token**: Tests the primary authentication path3. **Custom Meta App**: Tests the fallback authentication path-4. **Both Methods**: Tests authentication priority (Pipeboard preferred)+4. **Both Methods**: Tests authentication priority (bearer token preferred)## Expected Resultsdiff --git a/tests/conftest.py b/tests/conftest.pyindex 2f0c823..8fc4e32 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -47,10 +47,10 @@ def test_headers():@pytest.fixture-def pipeboard_auth_headers(test_headers):- """Headers with Pipeboard authentication token"""+def bearer_auth_headers(test_headers):+ """Headers with a Meta access token in the Authorization header"""headers = test_headers.copy()- headers["Authorization"] = "Bearer test_pipeboard_token_12345"+ headers["Authorization"] = "Bearer test_meta_access_token_12345"return headersdiff --git a/tests/test_event_id_e2e.py b/tests/test_event_id_e2e.pyindex 6d5dc92..7b1fbb8 100644--- a/tests/test_event_id_e2e.py+++ b/tests/test_event_id_e2e.py@@ -1,7 +1,7 @@"""End-to-end test for event_id parameter in create_ad_creative.-Run manually with PIPEBOARD_API_TOKEN set:- PIPEBOARD_API_TOKEN=pk_xxx python tests/test_event_id_e2e.py+Run manually with META_ACCESS_TOKEN set:+ META_ACCESS_TOKEN=EAAxxx python tests/test_event_id_e2e.py"""import asyncio@@ -23,8 +23,8 @@ EVENT_URL = f"https://www.facebook.com/events/{EVENT_ID}"async def main():- if not os.environ.get("PIPEBOARD_API_TOKEN"):- print("ERROR: PIPEBOARD_API_TOKEN not set")+ if not os.environ.get("META_ACCESS_TOKEN"):+ print("ERROR: META_ACCESS_TOKEN not set")sys.exit(1)create_fn = ads_module.create_ad_creative