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.

Bump version to 0.4.2

Yves Junqueira2abd232847df
diff --git a/meta_ads_mcp/__init__.py b/meta_ads_mcp/__init__.py
index 658bea4..7647915 100644
--- a/meta_ads_mcp/__init__.py
+++ b/meta_ads_mcp/__init__.py
@@ -7,7 +7,7 @@ with the Claude LLM.
from meta_ads_mcp.core.server import main
-__version__ = "0.4.1"
+__version__ = "0.4.2"
__all__ = [
'get_ad_accounts',
diff --git a/meta_ads_mcp/core/duplication.py b/meta_ads_mcp/core/duplication.py
index d1c5956..e6b18ec 100644
--- a/meta_ads_mcp/core/duplication.py
+++ b/meta_ads_mcp/core/duplication.py
@@ -6,6 +6,8 @@ import httpx
from typing import Optional, Dict, Any, List, Union
from .server import mcp_server
from .api import meta_api_tool
+from .auth import get_current_access_token
+from .http_auth_integration import FastMCPAuthIntegration
# Only register the duplication functions if the environment variable is set
@@ -178,21 +180,50 @@ if ENABLE_DUPLICATION:
async def _forward_duplication_request(resource_type: str, resource_id: str, access_token: str, options: Dict[str, Any]) -> str:
"""
- Forward duplication request to the cloud-hosted MCP API.
+ Forward duplication request to the cloud-hosted MCP API using dual-header authentication.
+
+ This implements the dual-header authentication pattern for MCP server callbacks:
+ - Authorization: Bearer <facebook_token> - Facebook access token for Meta API calls
+ - X-Pipeboard-Token: <pipeboard_token> - Pipeboard API token for authentication
Args:
resource_type: Type of resource to duplicate (campaign, adset, ad, creative)
resource_id: ID of the resource to duplicate
- access_token: Meta API access token from the request
+ access_token: Meta API access token (optional, will use context if not provided)
options: Duplication options
"""
try:
- if not access_token:
+ # Get tokens from the request context that were set by the HTTP auth middleware
+ # In the dual-header authentication pattern:
+ # - Pipeboard token comes from X-Pipeboard-Token header (for authentication)
+ # - Facebook token comes from Authorization header (for Meta API calls)
+
+ # Get tokens from context set by AuthInjectionMiddleware
+ pipeboard_token = FastMCPAuthIntegration.get_pipeboard_token()
+ facebook_token = FastMCPAuthIntegration.get_auth_token()
+
+ # Use provided access_token parameter if no Facebook token found in context
+ if not facebook_token:
+ facebook_token = access_token if access_token else await get_current_access_token()
+
+ # Validate we have both required tokens
+ if not pipeboard_token:
+ return json.dumps({
+ "error": "authentication_required",
+ "message": "Pipeboard API token not found",
+ "details": {
+ "required": "Valid Pipeboard token via X-Pipeboard-Token header",
+ "received_headers": "Check that the MCP server is forwarding the X-Pipeboard-Token header"
+ }
+ }, indent=2)
+
+ if not facebook_token:
return json.dumps({
"error": "authentication_required",
"message": "Meta Ads access token not found",
"details": {
- "required": "Valid access token from authenticated session"
+ "required": "Valid Meta access token from authenticated session",
+ "check": "Ensure Facebook account is connected and token is valid"
}
}, indent=2)
@@ -200,9 +231,10 @@ async def _forward_duplication_request(resource_type: str, resource_id: str, acc
base_url = "https://mcp.pipeboard.co"
endpoint = f"{base_url}/api/meta/duplicate/{resource_type}/{resource_id}"
- # Prepare the request
+ # Prepare the dual-header authentication as per API documentation
headers = {
- "Authorization": f"Bearer {access_token}",
+ "Authorization": f"Bearer {facebook_token}", # Facebook token for Meta API
+ "X-Pipeboard-Token": pipeboard_token, # Pipeboard token for auth
"Content-Type": "application/json",
"User-Agent": "meta-ads-mcp/1.0"
}
diff --git a/meta_ads_mcp/core/http_auth_integration.py b/meta_ads_mcp/core/http_auth_integration.py
index 3a3d4bf..3d64a55 100644
--- a/meta_ads_mcp/core/http_auth_integration.py
+++ b/meta_ads_mcp/core/http_auth_integration.py
@@ -13,6 +13,7 @@ import json
# Use context variables instead of thread-local storage for better async support
_auth_token: contextvars.ContextVar[Optional[str]] = contextvars.ContextVar('auth_token', default=None)
+_pipeboard_token: contextvars.ContextVar[Optional[str]] = contextvars.ContextVar('pipeboard_token', default=None)
class FastMCPAuthIntegration:
"""Direct integration with FastMCP for HTTP authentication"""
@@ -35,11 +36,34 @@ class FastMCPAuthIntegration:
"""
return _auth_token.get(None)
+ @staticmethod
+ def set_pipeboard_token(token: str) -> None:
+ """Set Pipeboard token for the current context
+
+ Args:
+ token: Pipeboard API token to use for this request
+ """
+ _pipeboard_token.set(token)
+
+ @staticmethod
+ def get_pipeboard_token() -> Optional[str]:
+ """Get Pipeboard token for the current context
+
+ Returns:
+ Pipeboard token if set, None otherwise
+ """
+ return _pipeboard_token.get(None)
+
@staticmethod
def clear_auth_token() -> None:
"""Clear authentication token for the current context"""
_auth_token.set(None)
+ @staticmethod
+ def clear_pipeboard_token() -> None:
+ """Clear Pipeboard token for the current context"""
+ _pipeboard_token.set(None)
+
@staticmethod
def extract_token_from_headers(headers: dict) -> Optional[str]:
"""Extract token from HTTP headers
@@ -69,6 +93,30 @@ class FastMCPAuthIntegration:
return pipeboard_token
return None
+
+ @staticmethod
+ def extract_pipeboard_token_from_headers(headers: dict) -> Optional[str]:
+ """Extract Pipeboard token from HTTP headers
+
+ Args:
+ headers: HTTP request headers
+
+ Returns:
+ Pipeboard token if found, None otherwise
+ """
+ # Check for Pipeboard token in X-Pipeboard-Token header (duplication API pattern)
+ pipeboard_token = headers.get('X-Pipeboard-Token') or headers.get('x-pipeboard-token')
+ if pipeboard_token:
+ logger.debug("Found Pipeboard token in X-Pipeboard-Token header")
+ return pipeboard_token
+
+ # Check for legacy Pipeboard token header
+ legacy_token = headers.get('X-PIPEBOARD-API-TOKEN') or headers.get('x-pipeboard-api-token')
+ if legacy_token:
+ logger.debug("Found Pipeboard token in legacy X-PIPEBOARD-API-TOKEN header")
+ return legacy_token
+
+ return None
def patch_fastmcp_server(mcp_server):
"""Patch FastMCP server to inject authentication from HTTP headers
@@ -203,21 +251,32 @@ class AuthInjectionMiddleware(BaseHTTPMiddleware):
logger.debug(f"HTTP Auth Middleware: Processing request to {request.url.path}")
logger.debug(f"HTTP Auth Middleware: Request headers: {list(request.headers.keys())}")
- token = FastMCPAuthIntegration.extract_token_from_headers(dict(request.headers))
+ # Extract both types of tokens for dual-header authentication
+ auth_token = FastMCPAuthIntegration.extract_token_from_headers(dict(request.headers))
+ pipeboard_token = FastMCPAuthIntegration.extract_pipeboard_token_from_headers(dict(request.headers))
- if token:
- logger.debug(f"HTTP Auth Middleware: Extracted token: {token[:10]}...")
+ if auth_token:
+ logger.debug(f"HTTP Auth Middleware: Extracted auth token: {auth_token[:10]}...")
logger.debug("Injecting auth token into request context")
- FastMCPAuthIntegration.set_auth_token(token)
- else:
- logger.warning("HTTP Auth Middleware: No authentication token found in headers")
+ FastMCPAuthIntegration.set_auth_token(auth_token)
+
+ if pipeboard_token:
+ logger.debug(f"HTTP Auth Middleware: Extracted Pipeboard token: {pipeboard_token[:10]}...")
+ logger.debug("Injecting Pipeboard token into request context")
+ FastMCPAuthIntegration.set_pipeboard_token(pipeboard_token)
+
+ if not auth_token and not pipeboard_token:
+ logger.warning("HTTP Auth Middleware: No authentication tokens found in headers")
try:
response = await call_next(request)
return response
finally:
- if token: # Clear only if a token was set for this request
+ # Clear tokens that were set for this request
+ if auth_token:
FastMCPAuthIntegration.clear_auth_token()
+ if pipeboard_token:
+ FastMCPAuthIntegration.clear_pipeboard_token()
def setup_starlette_middleware(app):
"""Add AuthInjectionMiddleware to the Starlette app if not already present.
diff --git a/pyproject.toml b/pyproject.toml
index 8e112a8..fcf8d86 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "meta-ads-mcp"
-version = "0.4.1"
+version = "0.4.2"
description = "Model Context Protocol (MCP) plugin for interacting with Meta Ads API"
readme = "README.md"
requires-python = ">=3.10"
diff --git a/tests/test_duplication.py b/tests/test_duplication.py
index 5cfb4dd..699ce88 100644
--- a/tests/test_duplication.py
+++ b/tests/test_duplication.py
@@ -3,7 +3,7 @@
import os
import json
import pytest
-from unittest.mock import patch, AsyncMock
+from unittest.mock import patch, AsyncMock, Mock
from meta_ads_mcp.core.duplication import ENABLE_DUPLICATION
@@ -27,54 +27,116 @@ def test_duplication_enabled_with_env_var():
@pytest.mark.asyncio
-async def test_forward_duplication_request_no_token():
- """Test that _forward_duplication_request handles missing access token."""
+async def test_forward_duplication_request_no_pipeboard_token():
+ """Test that _forward_duplication_request handles missing Pipeboard token."""
from meta_ads_mcp.core.duplication import _forward_duplication_request
- result = await _forward_duplication_request("campaign", "123456789", None, {})
- result_json = json.loads(result)
+ # Mock the auth integration to return no Pipeboard token but a Facebook token
+ with patch("meta_ads_mcp.core.duplication.FastMCPAuthIntegration") as mock_auth:
+ mock_auth.get_pipeboard_token.return_value = None # No Pipeboard token
+ mock_auth.get_auth_token.return_value = "facebook_token" # Has Facebook token
+
+ result = await _forward_duplication_request("campaign", "123456789", None, {})
+ result_json = json.loads(result)
+
+ assert result_json["error"] == "authentication_required"
+ assert "Pipeboard API token not found" in result_json["message"]
+
+
+async def test_forward_duplication_request_no_facebook_token():
+ """Test that _forward_duplication_request handles missing Facebook token."""
+ from meta_ads_mcp.core.duplication import _forward_duplication_request
- assert result_json["error"] == "authentication_required"
- assert "access token not found" in result_json["message"]
+ # Mock the auth integration to return Pipeboard token but no Facebook token
+ with patch("meta_ads_mcp.core.duplication.FastMCPAuthIntegration") as mock_auth:
+ mock_auth.get_pipeboard_token.return_value = "pipeboard_token" # Has Pipeboard token
+ mock_auth.get_auth_token.return_value = None # No Facebook token
+
+ # Mock get_current_access_token to also return None
+ with patch("meta_ads_mcp.core.duplication.get_current_access_token") as mock_get_token:
+ mock_get_token.return_value = None
+
+ result = await _forward_duplication_request("campaign", "123456789", None, {})
+ result_json = json.loads(result)
+
+ assert result_json["error"] == "authentication_required"
+ assert "Meta Ads access token not found" in result_json["message"]
@pytest.mark.asyncio
-async def test_forward_duplication_request_with_token():
- """Test that _forward_duplication_request makes HTTP request with proper headers."""
+async def test_forward_duplication_request_with_both_tokens():
+ """Test that _forward_duplication_request makes HTTP request with dual headers."""
from meta_ads_mcp.core.duplication import _forward_duplication_request
- from unittest.mock import Mock
mock_response = Mock()
mock_response.status_code = 403
mock_response.json.return_value = {"error": "premium_feature"}
- with patch("meta_ads_mcp.core.duplication.httpx.AsyncClient") as mock_client:
- mock_client.return_value.__aenter__.return_value.post.return_value = mock_response
-
- result = await _forward_duplication_request("campaign", "123456789", "test_token", {
- "name_suffix": " - Test"
- })
- result_json = json.loads(result)
-
- # Should return premium feature message for 403 response
- assert result_json["error"] == "premium_feature_required"
- assert "premium feature" in result_json["message"]
-
- # Verify the HTTP request was made with correct parameters
- mock_client.return_value.__aenter__.return_value.post.assert_called_once()
- call_args = mock_client.return_value.__aenter__.return_value.post.call_args
+ # Mock the auth integration to return both tokens
+ with patch("meta_ads_mcp.core.duplication.FastMCPAuthIntegration") as mock_auth:
+ mock_auth.get_pipeboard_token.return_value = "pipeboard_token"
+ mock_auth.get_auth_token.return_value = "facebook_token"
- # Check URL
- assert call_args[0][0] == "https://mcp.pipeboard.co/api/meta/duplicate/campaign/123456789"
-
- # Check headers
- headers = call_args[1]["headers"]
- assert headers["Authorization"] == "Bearer test_token"
- assert headers["Content-Type"] == "application/json"
+ with patch("meta_ads_mcp.core.duplication.httpx.AsyncClient") as mock_client:
+ mock_client.return_value.__aenter__.return_value.post.return_value = mock_response
+
+ result = await _forward_duplication_request("campaign", "123456789", None, {
+ "name_suffix": " - Test"
+ })
+ result_json = json.loads(result)
+
+ # Should return premium feature message for 403 response
+ assert result_json["error"] == "premium_feature_required"
+ assert "premium feature" in result_json["message"]
+
+ # Verify the HTTP request was made with correct parameters
+ mock_client.return_value.__aenter__.return_value.post.assert_called_once()
+ call_args = mock_client.return_value.__aenter__.return_value.post.call_args
+
+ # Check URL
+ assert call_args[0][0] == "https://mcp.pipeboard.co/api/meta/duplicate/campaign/123456789"
+
+ # Check dual headers (the key change!)
+ headers = call_args[1]["headers"]
+ assert headers["Authorization"] == "Bearer facebook_token" # Facebook token for Meta API
+ assert headers["X-Pipeboard-Token"] == "pipeboard_token" # Pipeboard token for auth
+ assert headers["Content-Type"] == "application/json"
+
+ # Check JSON payload
+ json_payload = call_args[1]["json"]
+ assert json_payload == {"name_suffix": " - Test"}
+
+
+async def test_forward_duplication_request_with_provided_access_token():
+ """Test that provided access_token parameter is used when available."""
+ from meta_ads_mcp.core.duplication import _forward_duplication_request
+
+ mock_response = Mock()
+ mock_response.status_code = 200
+ mock_response.json.return_value = {"success": True, "new_campaign_id": "987654321"}
+
+ # Mock the auth integration to return Pipeboard token but no Facebook token in context
+ with patch("meta_ads_mcp.core.duplication.FastMCPAuthIntegration") as mock_auth:
+ mock_auth.get_pipeboard_token.return_value = "pipeboard_token"
+ mock_auth.get_auth_token.return_value = None # No Facebook token in context
- # Check JSON payload
- json_payload = call_args[1]["json"]
- assert json_payload == {"name_suffix": " - Test"}
+ with patch("meta_ads_mcp.core.duplication.httpx.AsyncClient") as mock_client:
+ mock_client.return_value.__aenter__.return_value.post.return_value = mock_response
+
+ # Provide access_token as parameter
+ result = await _forward_duplication_request("campaign", "123456789", "provided_facebook_token", {})
+ result_json = json.loads(result)
+
+ # Should succeed
+ assert result_json["success"] is True
+
+ # Verify the HTTP request used the provided token
+ call_args = mock_client.return_value.__aenter__.return_value.post.call_args
+ headers = call_args[1]["headers"]
+ assert headers["Authorization"] == "Bearer provided_facebook_token"
+ assert headers["X-Pipeboard-Token"] == "pipeboard_token"
@pytest.mark.asyncio
@@ -133,4 +195,50 @@ def test_get_estimated_components():
# Test creative only
creative_result = _get_estimated_components("creative", {})
- assert creative_result == {"creatives": 1}
\ No newline at end of file
+ assert creative_result == {"creatives": 1}
+
+
+async def test_dual_header_authentication_integration():
+ """Test that the dual-header authentication works end-to-end."""
+ from meta_ads_mcp.core.duplication import _forward_duplication_request
+
+ mock_response = Mock()
+ mock_response.status_code = 200
+ mock_response.json.return_value = {
+ "success": True,
+ "new_campaign_id": "987654321",
+ "subscription": {"status": "active"}
+ }
+
+ # Test the complete dual-header flow
+ with patch("meta_ads_mcp.core.duplication.FastMCPAuthIntegration") as mock_auth:
+ mock_auth.get_pipeboard_token.return_value = "pb_token_12345"
+ mock_auth.get_auth_token.return_value = "fb_token_67890"
+
+ with patch("meta_ads_mcp.core.duplication.httpx.AsyncClient") as mock_client:
+ mock_client.return_value.__aenter__.return_value.post.return_value = mock_response
+
+ result = await _forward_duplication_request("adset", "456789", None, {
+ "target_campaign_id": "123456",
+ "include_ads": True
+ })
+ result_json = json.loads(result)
+
+ # Should succeed
+ assert result_json["success"] is True
+ assert result_json["new_campaign_id"] == "987654321"
+
+ # Verify correct endpoint was called
+ call_args = mock_client.return_value.__aenter__.return_value.post.call_args
+ assert "adset/456789" in call_args[0][0]
+
+ # Verify dual headers were sent correctly
+ headers = call_args[1]["headers"]
+ assert headers["Authorization"] == "Bearer fb_token_67890"
+ assert headers["X-Pipeboard-Token"] == "pb_token_12345"
+
+ # Verify payload
+ payload = call_args[1]["json"]
+ assert payload["target_campaign_id"] == "123456"
+ assert payload["include_ads"] is True
\ No newline at end of file
diff --git a/tests/test_duplication_regression.py b/tests/test_duplication_regression.py
index de24dce..b658fa8 100644
--- a/tests/test_duplication_regression.py
+++ b/tests/test_duplication_regression.py
@@ -131,6 +131,36 @@ class TestDuplicationAPIContract:
]
for resource_type, resource_id, expected_url in test_cases:
+ # Mock dual-header authentication
+ with patch("meta_ads_mcp.core.duplication.FastMCPAuthIntegration") as mock_auth:
+ mock_auth.get_pipeboard_token.return_value = "pipeboard_token"
+ mock_auth.get_auth_token.return_value = "facebook_token"
+
+ with patch("meta_ads_mcp.core.duplication.httpx.AsyncClient") as mock_client:
+ mock_response = AsyncMock()
+ mock_response.status_code = 200
+ mock_response.json.return_value = {"success": True}
+ mock_client.return_value.__aenter__.return_value.post.return_value = mock_response
+
+ await duplication._forward_duplication_request(
+ resource_type, resource_id, "test_token", {}
+ )
+
+ # Verify the correct URL was called
+ call_args = mock_client.return_value.__aenter__.return_value.post.call_args
+ actual_url = call_args[0][0]
+ assert actual_url == expected_url, f"Expected {expected_url}, got {actual_url}"
+
+ @pytest.mark.asyncio
+ async def test_request_headers_format(self, enable_feature):
+ """Test that request headers are formatted correctly."""
+ duplication = enable_feature
+
+ # Mock dual-header authentication
+ with patch("meta_ads_mcp.core.duplication.FastMCPAuthIntegration") as mock_auth:
+ mock_auth.get_pipeboard_token.return_value = "pipeboard_token_12345"
+ mock_auth.get_auth_token.return_value = "facebook_token_67890"
+
with patch("meta_ads_mcp.core.duplication.httpx.AsyncClient") as mock_client:
mock_response = AsyncMock()
mock_response.status_code = 200
@@ -138,54 +168,41 @@ class TestDuplicationAPIContract:
mock_client.return_value.__aenter__.return_value.post.return_value = mock_response
await duplication._forward_duplication_request(
- resource_type, resource_id, "test_token", {}
+ "campaign", "123456789", "test_token_12345", {"name_suffix": " - Test"}
)
- # Verify the correct URL was called
+ # Verify dual headers are sent correctly
call_args = mock_client.return_value.__aenter__.return_value.post.call_args
- actual_url = call_args[0][0]
- assert actual_url == expected_url, f"Expected {expected_url}, got {actual_url}"
-
- @pytest.mark.asyncio
- async def test_request_headers_format(self, enable_feature):
- """Test that request headers are formatted correctly."""
- duplication = enable_feature
-
- with patch("meta_ads_mcp.core.duplication.httpx.AsyncClient") as mock_client:
- mock_response = AsyncMock()
- mock_response.status_code = 200
- mock_response.json.return_value = {"success": True}
- mock_client.return_value.__aenter__.return_value.post.return_value = mock_response
-
- await duplication._forward_duplication_request(
- "campaign", "123456789", "test_token_12345", {"name_suffix": " - Test"}
- )
-
- # Verify headers
- call_args = mock_client.return_value.__aenter__.return_value.post.call_args
- headers = call_args[1]["headers"]
-
- assert headers["Authorization"] == "Bearer test_token_12345"
- assert headers["Content-Type"] == "application/json"
- assert headers["User-Agent"] == "meta-ads-mcp/1.0"
-
+ headers = call_args[1]["headers"]
+
+ # Check the dual-header authentication pattern
+ assert headers["Authorization"] == "Bearer facebook_token_67890" # Facebook token for Meta API
+ assert headers["X-Pipeboard-Token"] == "pipeboard_token_12345" # Pipeboard token for auth
+ assert headers["Content-Type"] == "application/json"
+ assert headers["User-Agent"] == "meta-ads-mcp/1.0"
+
@pytest.mark.asyncio
async def test_request_timeout_configuration(self, enable_feature):
"""Test that request timeout is configured correctly."""
duplication = enable_feature
- with patch("meta_ads_mcp.core.duplication.httpx.AsyncClient") as mock_client:
- mock_response = AsyncMock()
- mock_response.status_code = 200
- mock_response.json.return_value = {"success": True}
- mock_client.return_value.__aenter__.return_value.post.return_value = mock_response
-
- await duplication._forward_duplication_request(
- "campaign", "123456789", "test_token", {}
- )
+ # Mock dual-header authentication
+ with patch("meta_ads_mcp.core.duplication.FastMCPAuthIntegration") as mock_auth:
+ mock_auth.get_pipeboard_token.return_value = "pipeboard_token"
+ mock_auth.get_auth_token.return_value = "facebook_token"
- # Verify timeout is set to 30 seconds
- mock_client.assert_called_once_with(timeout=30.0)
+ with patch("meta_ads_mcp.core.duplication.httpx.AsyncClient") as mock_client:
+ mock_response = AsyncMock()
+ mock_response.status_code = 200
+ mock_response.json.return_value = {"success": True}
+ mock_client.return_value.__aenter__.return_value.post.return_value = mock_response
+
+ await duplication._forward_duplication_request(
+ "campaign", "123456789", "test_token", {}
+ )
+
+ # Verify timeout is set to 30 seconds
+ mock_client.assert_called_once_with(timeout=30.0)
class TestDuplicationErrorHandling:
@@ -202,15 +219,33 @@ class TestDuplicationErrorHandling:
@pytest.mark.asyncio
async def test_missing_access_token_error(self, enable_feature):
- """Test error handling when access token is missing."""
+ """Test error handling when authentication tokens are missing."""
duplication = enable_feature
- result = await duplication._forward_duplication_request("campaign", "123", None, {})
- result_json = json.loads(result)
+ # Test missing Pipeboard token (primary authentication failure)
+ with patch("meta_ads_mcp.core.duplication.FastMCPAuthIntegration") as mock_auth:
+ mock_auth.get_pipeboard_token.return_value = None # No Pipeboard token
+ mock_auth.get_auth_token.return_value = "facebook_token" # Has Facebook token
+
+ result = await duplication._forward_duplication_request("campaign", "123", None, {})
+ result_json = json.loads(result)
+
+ assert result_json["error"] == "authentication_required"
+ assert "Pipeboard API token not found" in result_json["message"]
- assert result_json["error"] == "authentication_required"
- assert "access token not found" in result_json["message"]
- assert result_json["details"]["required"] == "Valid access token from authenticated session"
+ # Test missing Facebook token (secondary authentication failure)
+ with patch("meta_ads_mcp.core.duplication.FastMCPAuthIntegration") as mock_auth:
+ mock_auth.get_pipeboard_token.return_value = "pipeboard_token" # Has Pipeboard token
+ mock_auth.get_auth_token.return_value = None # No Facebook token
+
+ with patch("meta_ads_mcp.core.duplication.get_current_access_token") as mock_get_token:
+ mock_get_token.return_value = None # No fallback token
+
+ result = await duplication._forward_duplication_request("campaign", "123", None, {})
+ result_json = json.loads(result)
+
+ assert result_json["error"] == "authentication_required"
+ assert "Meta Ads access token not found" in result_json["message"]
@pytest.mark.asyncio
async def test_http_status_code_handling(self, enable_feature):
@@ -230,7 +265,9 @@ class TestDuplicationErrorHandling:
]
for status_code, expected_error_type, response_type in status_code_tests:
- with patch("meta_ads_mcp.core.duplication.httpx.AsyncClient") as mock_client:
+ with patch("meta_ads_mcp.core.duplication.httpx.AsyncClient") as mock_client, \
+ patch("meta_ads_mcp.core.duplication.FastMCPAuthIntegration.get_pipeboard_token", return_value="test_pipeboard_token"), \
+ patch("meta_ads_mcp.core.duplication.FastMCPAuthIntegration.get_auth_token", return_value="test_facebook_token"):
# Use MagicMock instead of AsyncMock for more predictable behavior
mock_response = MagicMock()
mock_response.status_code = status_code
@@ -304,7 +341,9 @@ class TestDuplicationErrorHandling:
]
for exception, expected_error in network_errors:
- with patch("meta_ads_mcp.core.duplication.httpx.AsyncClient") as mock_client:
+ with patch("meta_ads_mcp.core.duplication.httpx.AsyncClient") as mock_client, \
+ patch("meta_ads_mcp.core.duplication.FastMCPAuthIntegration.get_pipeboard_token", return_value="test_pipeboard_token"), \
+ patch("meta_ads_mcp.core.duplication.FastMCPAuthIntegration.get_auth_token", return_value="test_facebook_token"):
mock_client.return_value.__aenter__.return_value.post.side_effect = exception
result = await duplication._forward_duplication_request(
@@ -332,33 +371,37 @@ class TestDuplicationParameterHandling:
"""Test that None values are filtered from options."""
duplication = enable_feature
- with patch("meta_ads_mcp.core.duplication.httpx.AsyncClient") as mock_client:
- mock_response = AsyncMock()
- mock_response.status_code = 200
- mock_response.json.return_value = {"success": True}
- mock_client.return_value.__aenter__.return_value.post.return_value = mock_response
-
- # Test with options containing None values
- options_with_none = {
- "name_suffix": " - Test",
- "new_daily_budget": None,
- "new_status": "PAUSED",
- "new_headline": None,
- }
+ # Mock dual-header authentication
+ with patch("meta_ads_mcp.core.duplication.FastMCPAuthIntegration") as mock_auth:
+ mock_auth.get_pipeboard_token.return_value = "pipeboard_token"
+ mock_auth.get_auth_token.return_value = "facebook_token"
- await duplication._forward_duplication_request(
- "campaign", "123", "token", options_with_none
- )
-
- # Verify None values were filtered out
- call_args = mock_client.return_value.__aenter__.return_value.post.call_args
- json_payload = call_args[1]["json"]
-
- expected_payload = {
- "name_suffix": " - Test",
- "new_status": "PAUSED"
- }
- assert json_payload == expected_payload
+ with patch("meta_ads_mcp.core.duplication.httpx.AsyncClient") as mock_client:
+ mock_response = AsyncMock()
+ mock_response.status_code = 200
+ mock_response.json.return_value = {"success": True}
+ mock_client.return_value.__aenter__.return_value.post.return_value = mock_response
+
+ # Test with options containing None values
+ options_with_none = {
+ "name_suffix": " - Test",
+ "new_daily_budget": None,
+ "new_status": "PAUSED",
+ "new_headline": None,
+ }
+
+ await duplication._forward_duplication_request(
+ "campaign", "123", "token", options_with_none
+ )
+
+ # Verify None values were filtered out
+ call_args = mock_client.return_value.__aenter__.return_value.post.call_args
+ json_payload = call_args[1]["json"]
+
+ assert "name_suffix" in json_payload
+ assert "new_status" in json_payload
+ assert "new_daily_budget" not in json_payload
+ assert "new_headline" not in json_payload
@pytest.mark.asyncio
async def test_campaign_duplication_parameter_forwarding(self, enable_feature):
@@ -736,44 +779,54 @@ class TestDuplicationRegressionEdgeCases:
"""Test handling of unicode parameters."""
duplication = enable_feature
- with patch("meta_ads_mcp.core.duplication.httpx.AsyncClient") as mock_client:
- mock_response = AsyncMock()
- mock_response.status_code = 200
- mock_response.json.return_value = {"success": True}
- mock_client.return_value.__aenter__.return_value.post.return_value = mock_response
+ # Mock dual-header authentication
+ with patch("meta_ads_mcp.core.duplication.FastMCPAuthIntegration") as mock_auth:
+ mock_auth.get_pipeboard_token.return_value = "pipeboard_token"
+ mock_auth.get_auth_token.return_value = "facebook_token"
- # Test with unicode characters
- unicode_suffix = " - 复制版本 🚀"
- await duplication._forward_duplication_request(
- "campaign", "123", "token", {"name_suffix": unicode_suffix}
- )
-
- # Verify unicode is preserved in the request
- call_args = mock_client.return_value.__aenter__.return_value.post.call_args
- json_payload = call_args[1]["json"]
- assert json_payload["name_suffix"] == unicode_suffix
-
+ with patch("meta_ads_mcp.core.duplication.httpx.AsyncClient") as mock_client:
+ mock_response = AsyncMock()
+ mock_response.status_code = 200
+ mock_response.json.return_value = {"success": True}
+ mock_client.return_value.__aenter__.return_value.post.return_value = mock_response
+
+ # Test with unicode characters
+ unicode_suffix = " - 复制版本 🚀"
+ await duplication._forward_duplication_request(
+ "campaign", "123", "token", {"name_suffix": unicode_suffix}
+ )
+
+ # Verify unicode is preserved in the request
+ call_args = mock_client.return_value.__aenter__.return_value.post.call_args
+ json_payload = call_args[1]["json"]
+ assert json_payload["name_suffix"] == unicode_suffix
+
@pytest.mark.asyncio
async def test_large_parameter_values(self, enable_feature):
"""Test handling of large parameter values."""
duplication = enable_feature
- with patch("meta_ads_mcp.core.duplication.httpx.AsyncClient") as mock_client:
- mock_response = AsyncMock()
- mock_response.status_code = 200
- mock_response.json.return_value = {"success": True}
- mock_client.return_value.__aenter__.return_value.post.return_value = mock_response
-
- # Test with very large budget value
- large_budget = 999999999.99
- await duplication._forward_duplication_request(
- "campaign", "123", "token", {"new_daily_budget": large_budget}
- )
+ # Mock dual-header authentication
+ with patch("meta_ads_mcp.core.duplication.FastMCPAuthIntegration") as mock_auth:
+ mock_auth.get_pipeboard_token.return_value = "pipeboard_token"
+ mock_auth.get_auth_token.return_value = "facebook_token"
- # Verify large values are preserved
- call_args = mock_client.return_value.__aenter__.return_value.post.call_args
- json_payload = call_args[1]["json"]
- assert json_payload["new_daily_budget"] == large_budget
+ with patch("meta_ads_mcp.core.duplication.httpx.AsyncClient") as mock_client:
+ mock_response = AsyncMock()
+ mock_response.status_code = 200
+ mock_response.json.return_value = {"success": True}
+ mock_client.return_value.__aenter__.return_value.post.return_value = mock_response
+
+ # Test with very large budget value
+ large_budget = 999999999.99
+ await duplication._forward_duplication_request(
+ "campaign", "123", "token", {"new_daily_budget": large_budget}
+ )
+
+ # Verify large values are preserved
+ call_args = mock_client.return_value.__aenter__.return_value.post.call_args
+ json_payload = call_args[1]["json"]
+ assert json_payload["new_daily_budget"] == large_budget
def test_module_reload_safety(self):
"""Test that module can be safely reloaded without side effects."""