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
Update authentication method to use Bearer tokens across the application
Yves Junqueiraf02411246e48
diff --git a/STREAMABLE_HTTP_SETUP.md b/STREAMABLE_HTTP_SETUP.mdindex 53f311a..15051c1 100644--- a/STREAMABLE_HTTP_SETUP.md+++ b/STREAMABLE_HTTP_SETUP.md@@ -18,27 +18,21 @@ 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:+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.```bashexport PIPEBOARD_API_TOKEN=your_pipeboard_token```-Or alternatively, use a direct Meta access token:--```bash-export META_ACCESS_TOKEN=your_meta_access_token-```-### 3. Make HTTP Requests-The server accepts JSON-RPC 2.0 requests at the `/mcp/` endpoint:+The server accepts JSON-RPC 2.0 requests at the `/mcp/` endpoint. Use the `Authorization` header to provide your token.```bashcurl -X POST http://localhost:8080/mcp/ \-H "Content-Type: application/json" \-H "Accept: application/json, text/event-stream" \- -H "X-PIPEBOARD-API-TOKEN: your_pipeboard_token" \+ -H "Authorization: Bearer your_pipeboard_token" \-d '{"jsonrpc": "2.0","method": "tools/call",@@ -75,14 +69,14 @@ python -m meta_ads_mcp --transport streamable-http --port 9000## Authentication-### Primary Method: Pipeboard Token (Recommended)+### Primary Method: Bearer Token (Recommended)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 HTTP headers:+3. Include the token in the `Authorization` HTTP header:```bash-curl -H "X-PIPEBOARD-API-TOKEN: your_pipeboard_token" \+curl -H "Authorization: Bearer your_pipeboard_token" \-X POST http://localhost:8080/mcp/ \-H "Content-Type: application/json" \-d '{"jsonrpc":"2.0","method":"tools/list","id":1}'@@ -90,7 +84,7 @@ curl -H "X-PIPEBOARD-API-TOKEN: your_pipeboard_token" \### Alternative Method: Direct Meta Token-If you have a Meta Developer App, you can use a direct access 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.```bashcurl -H "X-META-ACCESS-TOKEN: your_meta_access_token" \@@ -111,7 +105,7 @@ curl -H "X-META-ACCESS-TOKEN: your_meta_access_token" \| Method | Description ||--------|-------------|| `initialize` | Initialize MCP session and exchange capabilities |-| `tools/list` | Get list of all available Meta Ads tools (26 tools) |+| `tools/list` | Get list of all available Meta Ads tools || `tools/call` | Execute a specific tool with parameters |### Response Format@@ -135,7 +129,7 @@ All responses follow JSON-RPC 2.0 format:```bashcurl -X POST http://localhost:8080/mcp/ \-H "Content-Type: application/json" \- -H "X-PIPEBOARD-API-TOKEN: your_token" \+ -H "Authorization: Bearer your_token" \-d '{"jsonrpc": "2.0","method": "initialize",@@ -153,7 +147,7 @@ curl -X POST http://localhost:8080/mcp/ \```bashcurl -X POST http://localhost:8080/mcp/ \-H "Content-Type: application/json" \- -H "X-PIPEBOARD-API-TOKEN: your_token" \+ -H "Authorization: Bearer your_token" \-d '{"jsonrpc": "2.0","method": "tools/list",@@ -166,7 +160,7 @@ curl -X POST http://localhost:8080/mcp/ \```bashcurl -X POST http://localhost:8080/mcp/ \-H "Content-Type: application/json" \- -H "X-PIPEBOARD-API-TOKEN: your_token" \+ -H "Authorization: Bearer your_token" \-d '{"jsonrpc": "2.0","method": "tools/call",@@ -183,7 +177,7 @@ curl -X POST http://localhost:8080/mcp/ \```bashcurl -X POST http://localhost:8080/mcp/ \-H "Content-Type: application/json" \- -H "X-PIPEBOARD-API-TOKEN: your_token" \+ -H "Authorization: Bearer your_token" \-d '{"jsonrpc": "2.0","method": "tools/call",@@ -216,7 +210,7 @@ class MetaAdsMCPClient:"Accept": "application/json, text/event-stream"}if token:- self.headers["X-PIPEBOARD-API-TOKEN"] = token+ self.headers["Authorization"] = f"Bearer {token}"def call_tool(self, tool_name, arguments=None):payload = {@@ -251,7 +245,7 @@ class MetaAdsMCPClient {'Accept': 'application/json, text/event-stream'};if (token) {- this.headers['X-PIPEBOARD-API-TOKEN'] = token;+ this.headers['Authorization'] = `Bearer ${token}`;}}@@ -286,7 +280,7 @@ client.callTool('get_ad_accounts', { limit: 5 })### Security Considerations1. **Use HTTPS**: In production, run behind a reverse proxy with SSL/TLS-2. **Authentication**: Always use valid Pipeboard or Meta access tokens+2. **Authentication**: Always use valid Bearer tokens.3. **Network Security**: Configure firewalls and access controls appropriately4. **Rate Limiting**: Consider implementing rate limiting for public APIs@@ -307,48 +301,50 @@ CMD ["python", "-m", "meta_ads_mcp", "--transport", "streamable-http", "--host",### Environment Variables```bash-# Required-PIPEBOARD_API_TOKEN=your_pipeboard_token+# 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# Optional (for custom Meta apps)-META_APP_ID=your_app_id-META_APP_SECRET=your_app_secret-META_ACCESS_TOKEN=your_access_token+export META_APP_ID=your_app_id+export META_APP_SECRET=your_app_secret++# Optional (for direct Meta token)+export META_ACCESS_TOKEN=your_access_token```## Troubleshooting### Common Issues-1. **Connection Refused**: Ensure the server is running and accessible on the specified port-2. **Authentication Failed**: Verify your Pipeboard token is valid and included in headers-3. **404 Not Found**: Make sure you're using the correct endpoint (`/mcp/`)-4. **JSON-RPC Errors**: Check that your request follows the JSON-RPC 2.0 format+1. **Connection Refused**: Ensure the server is running and accessible on the specified port.+2. **Authentication Failed**: Verify your Bearer token is valid and included in the `Authorization` header.+3. **404 Not Found**: Make sure you're using the correct endpoint (`/mcp/`).+4. **JSON-RPC Errors**: Check that your request follows the JSON-RPC 2.0 format.### Debug Mode-Enable verbose logging:--```bash-python -m meta_ads_mcp --transport streamable-http --port 8080 --verbose-```+Enable verbose logging by setting the log level in your environment if the application supports it, or check the application's logging configuration. The current implementation logs to a file.### Health Check-Test if the server is running:+Test if the server is running by sending a `tools/list` request:```bashcurl -X POST http://localhost:8080/mcp/ \-H "Content-Type: application/json" \+ -H "Authorization: Bearer your_token" \-d '{"jsonrpc":"2.0","method":"tools/list","id":1}'```## Migration from stdio-If you're currently using stdio transport with MCP clients, you can run both modes simultaneously:+If you're currently using stdio transport with MCP clients, you can support both stdio for local clients and HTTP for web applications. The application can only run in one mode at a time, so you may need to run two separate instances if you need both simultaneously.-1. **Keep existing MCP client setup** (Claude Desktop, Cursor, etc.) using stdio-2. **Add HTTP transport** for web applications and custom integrations-3. **Use the same authentication** (Pipeboard token works for both)+1. **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 HTTP, pass the token in the `Authorization: Bearer <token>` header.-Both transports access the same Meta Ads functionality and use the same authentication system.\ No newline at end of file+Both transports access the same Meta Ads functionality and use the same underlying authentication system.\ No newline at end of filediff --git a/examples/example_http_client.py b/examples/example_http_client.pyindex b56294d..81c8f07 100644--- a/examples/example_http_client.py+++ b/examples/example_http_client.py@@ -41,7 +41,7 @@ class MetaAdsMCPClient:# Add authenticationif pipeboard_token:- self.headers["Authentication"] = f"Bearer {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_tokendiff --git a/meta_ads_mcp/core/http_auth_integration.py b/meta_ads_mcp/core/http_auth_integration.pyindex c64f0bd..3a3d4bf 100644--- a/meta_ads_mcp/core/http_auth_integration.py+++ b/meta_ads_mcp/core/http_auth_integration.py@@ -50,10 +50,11 @@ class FastMCPAuthIntegration:Returns:Token if found, None otherwise"""- # Check for Bearer token in Authentication header (primary method)- auth_header = headers.get('Authentication') or headers.get('authentication') or headers.get('authorization')+ # Check for Bearer token in Authorization header (primary method)+ auth_header = headers.get('Authorization') or headers.get('authorization')if auth_header and auth_header.lower().startswith('bearer '):token = auth_header[7:].strip()+ logger.debug("Found Bearer token in Authorization header")return token# Check for direct Meta access token@@ -64,6 +65,7 @@ class FastMCPAuthIntegration:# Check for Pipeboard token (legacy support, to be removed)pipeboard_token = headers.get('X-PIPEBOARD-API-TOKEN') or headers.get('x-pipeboard-api-token')if pipeboard_token:+ logger.debug("Found Pipeboard token in legacy headers")return pipeboard_tokenreturn Nonediff --git a/meta_ads_mcp/core/server.py b/meta_ads_mcp/core/server.pyindex 1198a26..318e851 100644--- a/meta_ads_mcp/core/server.py+++ b/meta_ads_mcp/core/server.py@@ -80,11 +80,11 @@ class StreamableHTTPHandler:'meta_access_token': False, # ❌ Use proper auth flows instead}- # PRIMARY: Check for Bearer token in Authentication header (handles 90%+ of cases)- auth_header = request_headers.get('Authentication') or request_headers.get('authentication')+ # 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 '):token = auth_header[7:].strip()- logger.debug("Bearer authentication detected (primary path)")+ logger.info("Bearer authentication detected (primary path)")return {'auth_method': 'bearer','bearer_token': token,@@ -178,7 +178,7 @@ class StreamableHTTPHandler:'message': 'Authentication required','data': {'supported_methods': [- 'Authentication: Bearer <token> (recommended)',+ 'Authorization: Bearer <token> (recommended)','X-META-APP-ID: Custom Meta app OAuth (advanced users)'],'documentation': 'https://github.com/pipeboard-co/meta-ads-mcp'@@ -324,7 +324,7 @@ def main():print(f"Starting Meta Ads MCP server with Streamable HTTP transport")print(f"Server will listen on {args.host}:{args.port}")print(f"Response format: {'SSE' if args.sse_response else 'JSON'}")- print("Primary authentication: Bearer Token (via Authentication: Bearer <token> header)")+ print("Primary authentication: Bearer Token (via Authorization: Bearer <token> header)")print("Fallback authentication: Custom Meta App OAuth (via X-META-APP-ID header)")# Configure the existing server with streamable HTTP settings@@ -347,8 +347,8 @@ def main():setup_fastmcp_http_auth(mcp_server)logger.info("FastMCP HTTP authentication integration setup successful")print("✅ FastMCP HTTP authentication integration enabled")+ print(" - Bearer tokens via Authorization: Bearer <token> header")print(" - Direct Meta tokens via X-META-ACCESS-TOKEN header")- print(" - Context-aware authentication for all tools")except Exception as e:logger.error(f"Failed to setup FastMCP HTTP authentication integration: {e}")diff --git a/tests/conftest.py b/tests/conftest.pyindex fe51ce9..2f0c823 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -50,7 +50,7 @@ def test_headers():def pipeboard_auth_headers(test_headers):"""Headers with Pipeboard authentication token"""headers = test_headers.copy()- headers["Authentication"] = "Bearer test_pipeboard_token_12345"+ headers["Authorization"] = "Bearer test_pipeboard_token_12345"return headersdiff --git a/tests/test_http_transport.py b/tests/test_http_transport.pyindex 9ba8df7..04913b0 100644--- a/tests/test_http_transport.py+++ b/tests/test_http_transport.py@@ -208,7 +208,7 @@ class HTTPTransportTester:},{"name": "Bearer Token (Primary Path)",- "headers": {"Authentication": "Bearer test_pipeboard_token_12345"}+ "headers": {"Authorization": "Bearer test_pipeboard_token_12345"}},{"name": "Custom Meta App ID (Fallback Path)",@@ -217,7 +217,7 @@ class HTTPTransportTester:{"name": "Both Auth Methods","headers": {- "Authentication": "Bearer test_pipeboard_token_12345",+ "Authorization": "Bearer test_pipeboard_token_12345","X-META-APP-ID": "123456789012345"}}