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.

Implement improved headlines/descriptions API with dual parameter support

Yves Junqueira76f1307a4c9a
diff --git a/README.md b/README.md
index 03d26d0..8a18f38 100644
--- a/README.md
+++ b/README.md
@@ -86,6 +86,7 @@ For detailed step-by-step instructions, authentication setup, debugging, and tro
- **Automated Monitoring**: Ask any MCP-compatible LLM to track performance metrics and alert you about significant changes
- **Budget Optimization**: Get recommendations for reallocating budget to better-performing ad sets
- **Creative Improvement**: Receive feedback on ad copy, imagery, and calls-to-action
+- **Dynamic Creative Testing**: Easy API for both simple ads (single headline/description) and advanced A/B testing (multiple headlines/descriptions)
- **Campaign Management**: Request changes to campaigns, ad sets, and ads (all changes require explicit confirmation)
- **Cross-Platform Integration**: Works with Facebook, Instagram, and all Meta ad platforms
- **Universal LLM Support**: Compatible with any MCP client including Claude Desktop, Cursor, Cherry Studio, and more
@@ -236,14 +237,32 @@ For local installation configuration, authentication options, and advanced techn
- `page_id`: Facebook Page ID for the ad
- `link_url`: Destination URL
- `message`: Ad copy/text
- - `headline`: Ad headline
- - `description`: Ad description
+ - `headline`: Single headline for simple ads (cannot be used with headlines)
+ - `headlines`: List of headlines for dynamic creative testing (cannot be used with headline)
+ - `description`: Single description for simple ads (cannot be used with descriptions)
+ - `descriptions`: List of descriptions for dynamic creative testing (cannot be used with description)
+ - `dynamic_creative_spec`: Dynamic creative optimization settings
- `call_to_action_type`: CTA button type (e.g., 'LEARN_MORE')
- `instagram_actor_id`: Optional Instagram account ID
- `access_token` (optional): Meta API access token
- Returns: Confirmation with new creative details
-15. `mcp_meta_ads_upload_ad_image`
+15. `mcp_meta_ads_update_ad_creative`
+ - Update an existing ad creative with new content or settings
+ - Inputs:
+ - `creative_id`: Meta Ads creative ID to update
+ - `name`: New creative name
+ - `message`: New ad copy/text
+ - `headline`: Single headline for simple ads (cannot be used with headlines)
+ - `headlines`: New list of headlines for dynamic creative testing (cannot be used with headline)
+ - `description`: Single description for simple ads (cannot be used with descriptions)
+ - `descriptions`: New list of descriptions for dynamic creative testing (cannot be used with description)
+ - `dynamic_creative_spec`: New dynamic creative optimization settings
+ - `call_to_action_type`: New call to action button type
+ - `access_token` (optional): Meta API access token (will use cached token if not provided)
+ - Returns: Confirmation with updated creative details
+
+16. `mcp_meta_ads_upload_ad_image`
- Upload an image to use in Meta Ads creatives
- Inputs:
- `account_id`: Meta Ads account ID (format: act_XXXXXXXXX)
@@ -252,14 +271,14 @@ For local installation configuration, authentication options, and advanced techn
- `access_token` (optional): Meta API access token
- Returns: JSON response with image details including hash
-16. `mcp_meta_ads_get_ad_image`
+17. `mcp_meta_ads_get_ad_image`
- Get, download, and visualize a Meta ad image in one step
- Inputs:
- `access_token` (optional): Meta API access token (will use cached token if not provided)
- `ad_id`: Meta Ads ad ID
- Returns: The ad image ready for direct visual analysis
-17. `mcp_meta_ads_update_ad`
+18. `mcp_meta_ads_update_ad`
- Update an ad with new settings
- Inputs:
- `ad_id`: Meta Ads ad ID
@@ -268,7 +287,7 @@ For local installation configuration, authentication options, and advanced techn
- `access_token` (optional): Meta API access token (will use cached token if not provided)
- Returns: Confirmation with updated ad details and a confirmation link
-18. `mcp_meta_ads_update_adset`
+19. `mcp_meta_ads_update_adset`
- Update an ad set with new settings including frequency caps
- Inputs:
- `adset_id`: Meta Ads ad set ID
@@ -280,7 +299,7 @@ For local installation configuration, authentication options, and advanced techn
- `access_token` (optional): Meta API access token (will use cached token if not provided)
- Returns: Confirmation with updated ad set details and a confirmation link
-19. `mcp_meta_ads_get_insights`
+20. `mcp_meta_ads_get_insights`
- Get performance insights for a campaign, ad set, ad or account
- Inputs:
- `access_token` (optional): Meta API access token (will use cached token if not provided)
@@ -290,13 +309,13 @@ For local installation configuration, authentication options, and advanced techn
- `level`: Level of aggregation (ad, adset, campaign, account)
- Returns: Performance metrics for the specified object
-20. `mcp_meta_ads_get_login_link`
+21. `mcp_meta_ads_get_login_link`
- Get a clickable login link for Meta Ads authentication
- Inputs:
- `access_token` (optional): Meta API access token (will use cached token if not provided)
- Returns: A clickable resource link for Meta authentication
-21. `mcp_meta-ads_create_budget_schedule`
+22. `mcp_meta-ads_create_budget_schedule`
- Create a budget schedule for a Meta Ads campaign.
- Inputs:
- `campaign_id`: Meta Ads campaign ID.
@@ -307,7 +326,7 @@ For local installation configuration, authentication options, and advanced techn
- `access_token` (optional): Meta API access token.
- Returns: JSON string with the ID of the created budget schedule or an error message.
-22. `mcp_meta_ads_search_interests`
+23. `mcp_meta_ads_search_interests`
- Search for interest targeting options by keyword
- Inputs:
- `access_token` (optional): Meta API access token (will use cached token if not provided)
@@ -315,7 +334,7 @@ For local installation configuration, authentication options, and advanced techn
- `limit`: Maximum number of results to return (default: 25)
- Returns: Interest data with id, name, audience_size, and path fields
-23. `mcp_meta_ads_get_interest_suggestions`
+24. `mcp_meta_ads_get_interest_suggestions`
- Get interest suggestions based on existing interests
- Inputs:
- `access_token` (optional): Meta API access token (will use cached token if not provided)
diff --git a/meta_ads_mcp/core/ads.py b/meta_ads_mcp/core/ads.py
index 8171dca..9ec3b70 100644
--- a/meta_ads_mcp/core/ads.py
+++ b/meta_ads_mcp/core/ads.py
@@ -633,7 +633,10 @@ async def create_ad_creative(
link_url: str = None,
message: str = None,
headline: str = None,
+ headlines: List[str] = None,
description: str = None,
+ descriptions: List[str] = None,
+ dynamic_creative_spec: Dict[str, Any] = None,
call_to_action_type: str = None,
instagram_actor_id: str = None
) -> str:
@@ -648,8 +651,11 @@ async def create_ad_creative(
page_id: Facebook Page ID to be used for the ad
link_url: Destination URL for the ad
message: Ad copy/text
- headline: Ad headline
- description: Ad description
+ headline: Single headline for simple ads (cannot be used with headlines)
+ headlines: List of headlines for dynamic creative testing (cannot be used with headline)
+ description: Single description for simple ads (cannot be used with descriptions)
+ descriptions: List of descriptions for dynamic creative testing (cannot be used with description)
+ dynamic_creative_spec: Dynamic creative optimization settings
call_to_action_type: Call to action button type (e.g., 'LEARN_MORE', 'SIGN_UP', 'SHOP_NOW')
instagram_actor_id: Optional Instagram account ID for Instagram placements
@@ -697,29 +703,98 @@ async def create_ad_creative(
"suggestion": "Please provide a page_id parameter or use get_account_pages to find available pages"
}, indent=2)
+ # Validate headline/description parameters - cannot mix simple and complex
+ if headline and headlines:
+ return json.dumps({"error": "Cannot specify both 'headline' and 'headlines'. Use 'headline' for single headline or 'headlines' for multiple."}, indent=2)
+
+ if description and descriptions:
+ return json.dumps({"error": "Cannot specify both 'description' and 'descriptions'. Use 'description' for single description or 'descriptions' for multiple."}, indent=2)
+
+ # Convert simple parameters to complex format for internal processing
+ final_headlines = None
+ final_descriptions = None
+
+ if headline:
+ final_headlines = [headline]
+ elif headlines:
+ final_headlines = headlines
+
+ if description:
+ final_descriptions = [description]
+ elif descriptions:
+ final_descriptions = descriptions
+
+ # Validate dynamic creative parameters
+ if final_headlines:
+ if len(final_headlines) > 5:
+ return json.dumps({"error": "Maximum 5 headlines allowed for dynamic creatives"}, indent=2)
+ for i, h in enumerate(final_headlines):
+ if len(h) > 40:
+ return json.dumps({"error": f"Headline {i+1} exceeds 40 character limit"}, indent=2)
+
+ if final_descriptions:
+ if len(final_descriptions) > 5:
+ return json.dumps({"error": "Maximum 5 descriptions allowed for dynamic creatives"}, indent=2)
+ for i, d in enumerate(final_descriptions):
+ if len(d) > 125:
+ return json.dumps({"error": f"Description {i+1} exceeds 125 character limit"}, indent=2)
+
# Prepare the creative data
creative_data = {
- "name": name,
- "object_story_spec": {
+ "name": name
+ }
+
+ # Choose between asset_feed_spec (dynamic creative) or object_story_spec (traditional)
+ if final_headlines or final_descriptions:
+ # Use asset_feed_spec for dynamic creatives
+ asset_feed_spec = {
+ "ad_formats": ["SINGLE_IMAGE"],
+ "images": [{"hash": image_hash}],
+ "link_urls": [{"website_url": link_url if link_url else "https://facebook.com"}]
+ }
+
+ # Handle headlines
+ if final_headlines:
+ asset_feed_spec["headlines"] = [{"text": headline_text} for headline_text in final_headlines]
+
+ # Handle descriptions
+ if final_descriptions:
+ asset_feed_spec["descriptions"] = [{"text": description_text} for description_text in final_descriptions]
+
+ # Add message as primary_texts if provided
+ if message:
+ asset_feed_spec["primary_texts"] = [{"text": message}]
+
+ # Add call_to_action_types if provided
+ if call_to_action_type:
+ asset_feed_spec["call_to_action_types"] = [call_to_action_type]
+
+ creative_data["asset_feed_spec"] = asset_feed_spec
+
+ # For dynamic creatives, we need a simplified object_story_spec
+ creative_data["object_story_spec"] = {
+ "page_id": page_id
+ }
+ else:
+ # Use traditional object_story_spec for single creative
+ creative_data["object_story_spec"] = {
"page_id": page_id,
"link_data": {
"image_hash": image_hash,
"link": link_url if link_url else "https://facebook.com"
}
}
- }
-
- # Add optional parameters if provided
- if message:
- creative_data["object_story_spec"]["link_data"]["message"] = message
-
- if headline:
- creative_data["object_story_spec"]["link_data"]["name"] = headline
- if description:
- creative_data["object_story_spec"]["link_data"]["description"] = description
+ # Add optional parameters if provided
+ if message:
+ creative_data["object_story_spec"]["link_data"]["message"] = message
- if call_to_action_type:
+ # Add dynamic creative spec if provided
+ if dynamic_creative_spec:
+ creative_data["dynamic_creative_spec"] = dynamic_creative_spec
+
+ # Only add call_to_action to object_story_spec if we're not using asset_feed_spec
+ if call_to_action_type and "asset_feed_spec" not in creative_data:
creative_data["object_story_spec"]["link_data"]["call_to_action"] = {
"type": call_to_action_type
}
@@ -739,7 +814,7 @@ async def create_ad_creative(
creative_id = data["id"]
creative_endpoint = f"{creative_id}"
creative_params = {
- "fields": "id,name,status,thumbnail_url,image_url,image_hash,object_story_spec,url_tags,link_url"
+ "fields": "id,name,status,thumbnail_url,image_url,image_hash,object_story_spec,asset_feed_spec,url_tags,link_url"
}
creative_details = await make_api_request(creative_endpoint, access_token, creative_params)
@@ -759,6 +834,154 @@ async def create_ad_creative(
}, indent=2)
+@mcp_server.tool()
+@meta_api_tool
+async def update_ad_creative(
+ access_token: str = None,
+ creative_id: str = None,
+ name: str = None,
+ message: str = None,
+ headline: str = None,
+ headlines: List[str] = None,
+ description: str = None,
+ descriptions: List[str] = None,
+ dynamic_creative_spec: Dict[str, Any] = None,
+ call_to_action_type: str = None
+) -> str:
+ """
+ Update an existing ad creative with new content or settings.
+
+ Args:
+ access_token: Meta API access token (optional - will use cached token if not provided)
+ creative_id: Meta Ads creative ID to update
+ name: New creative name
+ message: New ad copy/text
+ headline: Single headline for simple ads (cannot be used with headlines)
+ headlines: New list of headlines for dynamic creative testing (cannot be used with headline)
+ description: Single description for simple ads (cannot be used with descriptions)
+ descriptions: New list of descriptions for dynamic creative testing (cannot be used with description)
+ dynamic_creative_spec: New dynamic creative optimization settings
+ call_to_action_type: New call to action button type
+
+ Returns:
+ JSON response with updated creative details
+ """
+ # Check required parameters
+ if not creative_id:
+ return json.dumps({"error": "No creative ID provided"}, indent=2)
+
+ # Validate headline/description parameters - cannot mix simple and complex
+ if headline and headlines:
+ return json.dumps({"error": "Cannot specify both 'headline' and 'headlines'. Use 'headline' for single headline or 'headlines' for multiple."}, indent=2)
+
+ if description and descriptions:
+ return json.dumps({"error": "Cannot specify both 'description' and 'descriptions'. Use 'description' for single description or 'descriptions' for multiple."}, indent=2)
+
+ # Convert simple parameters to complex format for internal processing
+ final_headlines = None
+ final_descriptions = None
+
+ if headline:
+ final_headlines = [headline]
+ elif headlines:
+ final_headlines = headlines
+
+ if description:
+ final_descriptions = [description]
+ elif descriptions:
+ final_descriptions = descriptions
+
+ # Validate dynamic creative parameters
+ if final_headlines:
+ if len(final_headlines) > 5:
+ return json.dumps({"error": "Maximum 5 headlines allowed for dynamic creatives"}, indent=2)
+ for i, h in enumerate(final_headlines):
+ if len(h) > 40:
+ return json.dumps({"error": f"Headline {i+1} exceeds 40 character limit"}, indent=2)
+
+ if final_descriptions:
+ if len(final_descriptions) > 5:
+ return json.dumps({"error": "Maximum 5 descriptions allowed for dynamic creatives"}, indent=2)
+ for i, d in enumerate(final_descriptions):
+ if len(d) > 125:
+ return json.dumps({"error": f"Description {i+1} exceeds 125 character limit"}, indent=2)
+
+ # Prepare the update data
+ update_data = {}
+
+ if name:
+ update_data["name"] = name
+
+ if message:
+ update_data["object_story_spec"] = {"link_data": {"message": message}}
+
+ # Handle dynamic creative assets via asset_feed_spec
+ if final_headlines or final_descriptions or dynamic_creative_spec:
+ asset_feed_spec = {}
+
+ # Add required ad_formats field for dynamic creatives
+ asset_feed_spec["ad_formats"] = ["SINGLE_IMAGE"]
+
+ # Handle headlines
+ if final_headlines:
+ asset_feed_spec["headlines"] = [{"text": headline_text} for headline_text in final_headlines]
+
+ # Handle descriptions
+ if final_descriptions:
+ asset_feed_spec["descriptions"] = [{"text": description_text} for description_text in final_descriptions]
+
+ # Add message as primary_texts if provided
+ if message:
+ asset_feed_spec["primary_texts"] = [{"text": message}]
+
+ update_data["asset_feed_spec"] = asset_feed_spec
+
+ # Add dynamic creative spec if provided
+ if dynamic_creative_spec:
+ update_data["dynamic_creative_spec"] = dynamic_creative_spec
+
+ # Handle call_to_action - add to asset_feed_spec if using dynamic creative, otherwise to object_story_spec
+ if call_to_action_type:
+ if "asset_feed_spec" in update_data:
+ update_data["asset_feed_spec"]["call_to_action_types"] = [call_to_action_type]
+ else:
+ if "object_story_spec" not in update_data:
+ update_data["object_story_spec"] = {"link_data": {}}
+ update_data["object_story_spec"]["link_data"]["call_to_action"] = {
+ "type": call_to_action_type
+ }
+
+ # Prepare the API endpoint for updating the creative
+ endpoint = f"{creative_id}"
+
+ try:
+ # Make API request to update the creative
+ data = await make_api_request(endpoint, access_token, update_data, method="POST")
+
+ # If successful, get more details about the updated creative
+ if "id" in data:
+ creative_endpoint = f"{creative_id}"
+ creative_params = {
+ "fields": "id,name,status,thumbnail_url,image_url,image_hash,object_story_spec,url_tags,link_url,dynamic_creative_spec"
+ }
+
+ creative_details = await make_api_request(creative_endpoint, access_token, creative_params)
+ return json.dumps({
+ "success": True,
+ "creative_id": creative_id,
+ "details": creative_details
+ }, indent=2)
+
+ return json.dumps(data, indent=2)
+
+ except Exception as e:
+ return json.dumps({
+ "error": "Failed to update ad creative",
+ "details": str(e),
+ "update_data_sent": update_data
+ }, indent=2)
+
+
async def _discover_pages_for_account(account_id: str, access_token: str) -> dict:
"""
Internal function to discover pages for an account using multiple approaches.
diff --git a/tests/test_duplication_regression.py b/tests/test_duplication_regression.py
index b658fa8..12ba588 100644
--- a/tests/test_duplication_regression.py
+++ b/tests/test_duplication_regression.py
@@ -546,16 +546,12 @@ class TestDuplicationIntegration:
duplication = enable_feature
# Mock the auth system completely to bypass the @meta_api_tool decorator checks
- with patch("meta_ads_mcp.core.auth.get_current_access_token") as mock_get_token:
- with patch("meta_ads_mcp.core.auth.auth_manager") as mock_auth_manager:
- with patch("meta_ads_mcp.core.auth.meta_config") as mock_meta_config:
- # Setup complete auth mocking
- mock_get_token.return_value = "valid_token"
- mock_auth_manager.app_id = "valid_app_id"
- mock_auth_manager.use_pipeboard = False
- mock_meta_config.get_app_id.return_value = "valid_app_id"
-
- with patch("meta_ads_mcp.core.duplication.httpx.AsyncClient") as mock_client:
+ with patch("meta_ads_mcp.core.duplication.FastMCPAuthIntegration") as mock_auth_integration:
+ # Mock dual authentication tokens
+ mock_auth_integration.get_pipeboard_token.return_value = "pipeboard_token"
+ mock_auth_integration.get_auth_token.return_value = "facebook_token"
+
+ with patch("meta_ads_mcp.core.duplication.httpx.AsyncClient") as mock_client:
# Mock successful response
mock_response = MagicMock()
mock_response.status_code = 200
@@ -579,7 +575,7 @@ class TestDuplicationIntegration:
# Call the function with explicit token
result = await duplication.duplicate_campaign(
campaign_id="123456789",
- access_token="valid_token",
+ access_token="facebook_token", # Use the mocked token
name_suffix=" - Test Copy"
)
@@ -599,17 +595,13 @@ class TestDuplicationIntegration:
"""Test Facebook connection required error flow."""
duplication = enable_feature
- # Mock the auth system completely to bypass the @meta_api_tool decorator checks
- with patch("meta_ads_mcp.core.auth.get_current_access_token") as mock_get_token:
- with patch("meta_ads_mcp.core.auth.auth_manager") as mock_auth_manager:
- with patch("meta_ads_mcp.core.auth.meta_config") as mock_meta_config:
- # Setup complete auth mocking
- mock_get_token.return_value = "valid_token"
- mock_auth_manager.app_id = "valid_app_id"
- mock_auth_manager.use_pipeboard = False
- mock_meta_config.get_app_id.return_value = "valid_app_id"
-
- with patch("meta_ads_mcp.core.duplication.httpx.AsyncClient") as mock_client:
+ # Mock the auth system completely to bypass the @meta_api_tool decorator checks
+ with patch("meta_ads_mcp.core.duplication.FastMCPAuthIntegration") as mock_auth_integration:
+ # Mock dual authentication tokens
+ mock_auth_integration.get_pipeboard_token.return_value = "pipeboard_token"
+ mock_auth_integration.get_auth_token.return_value = "facebook_token"
+
+ with patch("meta_ads_mcp.core.duplication.httpx.AsyncClient") as mock_client:
# Mock 403 response (Facebook connection required)
mock_response = MagicMock()
mock_response.status_code = 403
@@ -624,7 +616,7 @@ class TestDuplicationIntegration:
result = await duplication.duplicate_campaign(
campaign_id="123456789",
- access_token="valid_token"
+ access_token="facebook_token" # Use the mocked token
)
# The @meta_api_tool decorator wraps the result in a data field
@@ -646,16 +638,12 @@ class TestDuplicationIntegration:
duplication = enable_feature
# Mock the auth system completely to bypass the @meta_api_tool decorator checks
- with patch("meta_ads_mcp.core.auth.get_current_access_token") as mock_get_token:
- with patch("meta_ads_mcp.core.auth.auth_manager") as mock_auth_manager:
- with patch("meta_ads_mcp.core.auth.meta_config") as mock_meta_config:
- # Setup complete auth mocking
- mock_get_token.return_value = "valid_token"
- mock_auth_manager.app_id = "valid_app_id"
- mock_auth_manager.use_pipeboard = False
- mock_meta_config.get_app_id.return_value = "valid_app_id"
-
- with patch("meta_ads_mcp.core.duplication.httpx.AsyncClient") as mock_client:
+ with patch("meta_ads_mcp.core.duplication.FastMCPAuthIntegration") as mock_auth_integration:
+ # Mock dual authentication tokens
+ mock_auth_integration.get_pipeboard_token.return_value = "pipeboard_token"
+ mock_auth_integration.get_auth_token.return_value = "facebook_token"
+
+ with patch("meta_ads_mcp.core.duplication.httpx.AsyncClient") as mock_client:
# Mock 402 response (subscription required)
mock_response = MagicMock()
mock_response.status_code = 402
@@ -668,7 +656,7 @@ class TestDuplicationIntegration:
result = await duplication.duplicate_campaign(
campaign_id="123456789",
- access_token="valid_token"
+ access_token="facebook_token" # Use the mocked token
)
# The @meta_api_tool decorator wraps the result in a data field
diff --git a/tests/test_dynamic_creatives.py b/tests/test_dynamic_creatives.py
new file mode 100644
index 0000000..ee99e2e
--- /dev/null
+++ b/tests/test_dynamic_creatives.py
@@ -0,0 +1,860 @@
+"""Tests for dynamic creative features including multiple headlines and descriptions.
+
+Tests for the enhanced create_ad_creative function that supports:
+- Multiple headlines
+- Multiple descriptions
+- Dynamic creative optimization settings
+- Creative update functionality
+"""
+
+import pytest
+import json
+from unittest.mock import AsyncMock, patch
+from meta_ads_mcp.core.ads import create_ad_creative, update_ad_creative
+
+
+class TestDynamicCreatives:
+ """Test cases for dynamic creative features."""
+
+ async def test_create_ad_creative_single_headline(self):
+ """Test creating ad creative with single headline (simple case)."""
+
+ sample_creative_data = {
+ "id": "123456789",
+ "name": "Test Creative",
+ "status": "ACTIVE"
+ }
+
+ with patch('meta_ads_mcp.core.ads.make_api_request', new_callable=AsyncMock) as mock_api:
+ mock_api.return_value = sample_creative_data
+
+ result = await create_ad_creative(
+ access_token="test_token",
+ account_id="act_123456789",
+ name="Test Creative",
+ image_hash="abc123",
+ page_id="987654321",
+ link_url="https://example.com",
+ message="Test message",
+ headline="Single Headline",
+ call_to_action_type="LEARN_MORE"
+ )
+
+ result_data = json.loads(result)
+ assert result_data["success"] is True
+
+ # Verify the API call was made with single headline converted to array
+ call_args_list = mock_api.call_args_list
+ assert len(call_args_list) >= 1
+
+ # First call should be the creative creation
+ first_call = call_args_list[0]
+ creative_data = first_call[0][2] # params is the third argument
+
+ # Should use asset_feed_spec with headlines array format (internally converted)
+ assert "asset_feed_spec" in creative_data
+ assert "headlines" in creative_data["asset_feed_spec"]
+ assert creative_data["asset_feed_spec"]["headlines"] == [
+ {"text": "Single Headline"}
+ ]
+
+ async def test_create_ad_creative_single_description(self):
+ """Test creating ad creative with single description (simple case)."""
+
+ sample_creative_data = {
+ "id": "123456789",
+ "name": "Test Creative",
+ "status": "ACTIVE"
+ }
+
+ with patch('meta_ads_mcp.core.ads.make_api_request', new_callable=AsyncMock) as mock_api:
+ mock_api.return_value = sample_creative_data
+
+ result = await create_ad_creative(
+ access_token="test_token",
+ account_id="act_123456789",
+ name="Test Creative",
+ image_hash="abc123",
+ page_id="987654321",
+ link_url="https://example.com",
+ message="Test message",
+ description="Single Description",
+ call_to_action_type="LEARN_MORE"
+ )
+
+ result_data = json.loads(result)
+ assert result_data["success"] is True
+
+ # Verify the API call was made with single description converted to array
+ call_args_list = mock_api.call_args_list
+ assert len(call_args_list) >= 1
+
+ # First call should be the creative creation
+ first_call = call_args_list[0]
+ creative_data = first_call[0][2] # params is the third argument
+
+ # Should use asset_feed_spec with descriptions array format (internally converted)
+ assert "asset_feed_spec" in creative_data
+ assert "descriptions" in creative_data["asset_feed_spec"]
+ assert creative_data["asset_feed_spec"]["descriptions"] == [
+ {"text": "Single Description"}
+ ]
+
+ async def test_create_ad_creative_cannot_mix_headline_and_headlines(self):
+ """Test that mixing headline and headlines parameters raises error."""
+
+ result = await create_ad_creative(
+ access_token="test_token",
+ account_id="act_123456789",
+ name="Test Creative",
+ image_hash="abc123",
+ page_id="987654321",
+ link_url="https://example.com",
+ message="Test message",
+ headline="Single Headline",
+ headlines=["Headline 1", "Headline 2"],
+ call_to_action_type="LEARN_MORE"
+ )
+
+ result_data = json.loads(result)
+
+ # Check if error is wrapped in "data" field (MCP error response format)
+ if "data" in result_data:
+ error_data = json.loads(result_data["data"])
+ assert "error" in error_data
+ assert "Cannot specify both 'headline' and 'headlines'" in error_data["error"]
+ else:
+ assert "error" in result_data
+ assert "Cannot specify both 'headline' and 'headlines'" in result_data["error"]
+
+ async def test_create_ad_creative_cannot_mix_description_and_descriptions(self):
+ """Test that mixing description and descriptions parameters raises error."""
+
+ result = await create_ad_creative(
+ access_token="test_token",
+ account_id="act_123456789",
+ name="Test Creative",
+ image_hash="abc123",
+ page_id="987654321",
+ link_url="https://example.com",
+ message="Test message",
+ description="Single Description",
+ descriptions=["Description 1", "Description 2"],
+ call_to_action_type="LEARN_MORE"
+ )
+
+ result_data = json.loads(result)
+
+ # Check if error is wrapped in "data" field (MCP error response format)
+ if "data" in result_data:
+ error_data = json.loads(result_data["data"])
+ assert "error" in error_data
+ assert "Cannot specify both 'description' and 'descriptions'" in error_data["error"]
+ else:
+ assert "error" in result_data
+ assert "Cannot specify both 'description' and 'descriptions'" in result_data["error"]
+
+
+ async def test_create_ad_creative_multiple_headlines(self):
+ """Test creating ad creative with multiple headlines."""
+
+ sample_creative_data = {
+ "id": "123456789",
+ "name": "Test Creative",
+ "status": "ACTIVE"
+ }
+
+ with patch('meta_ads_mcp.core.ads.make_api_request', new_callable=AsyncMock) as mock_api:
+ mock_api.return_value = sample_creative_data
+
+ result = await create_ad_creative(
+ access_token="test_token",
+ account_id="act_123456789",
+ name="Test Creative",
+ image_hash="abc123",
+ page_id="987654321",
+ link_url="https://example.com",
+ message="Test message",
+ headlines=["Headline 1", "Headline 2", "Headline 3"],
+ call_to_action_type="LEARN_MORE"
+ )
+
+ result_data = json.loads(result)
+ assert result_data["success"] is True
+
+ # Verify the API call was made with multiple headlines
+ # We need to check the first call (creative creation), not the second call (details fetch)
+ call_args_list = mock_api.call_args_list
+ assert len(call_args_list) >= 1
+
+ # First call should be the creative creation
+ first_call = call_args_list[0]
+ creative_data = first_call[0][2] # params is the third argument
+
+ # Should use asset_feed_spec with headlines array format
+ assert "asset_feed_spec" in creative_data
+ assert "headlines" in creative_data["asset_feed_spec"]
+ assert creative_data["asset_feed_spec"]["headlines"] == [
+ {"text": "Headline 1"},
+ {"text": "Headline 2"},
+ {"text": "Headline 3"}
+ ]
+
+ async def test_create_ad_creative_multiple_descriptions(self):
+ """Test creating ad creative with multiple descriptions."""
+
+ sample_creative_data = {
+ "id": "123456789",
+ "name": "Test Creative",
+ "status": "ACTIVE"
+ }
+
+ with patch('meta_ads_mcp.core.ads.make_api_request', new_callable=AsyncMock) as mock_api:
+ mock_api.return_value = sample_creative_data
+
+ result = await create_ad_creative(
+ access_token="test_token",
+ account_id="act_123456789",
+ name="Test Creative",
+ image_hash="abc123",
+ page_id="987654321",
+ link_url="https://example.com",
+ message="Test message",
+ descriptions=["Description 1", "Description 2"],
+ call_to_action_type="LEARN_MORE"
+ )
+
+ result_data = json.loads(result)
+ assert result_data["success"] is True
+
+ # Verify the API call was made with multiple descriptions
+ # We need to check the first call (creative creation), not the second call (details fetch)
+ call_args_list = mock_api.call_args_list
+ assert len(call_args_list) >= 1
+
+ # First call should be the creative creation
+ first_call = call_args_list[0]
+ creative_data = first_call[0][2] # params is the third argument
+
+ # Should use asset_feed_spec with descriptions array format
+ assert "asset_feed_spec" in creative_data
+ assert "descriptions" in creative_data["asset_feed_spec"]
+ assert creative_data["asset_feed_spec"]["descriptions"] == [
+ {"text": "Description 1"},
+ {"text": "Description 2"}
+ ]
+
+ async def test_create_ad_creative_dynamic_creative_spec(self):
+ """Test creating ad creative with dynamic_creative_spec optimization settings."""
+
+ sample_creative_data = {
+ "id": "123456789",
+ "name": "Test Creative",
+ "status": "ACTIVE"
+ }
+
+ with patch('meta_ads_mcp.core.ads.make_api_request', new_callable=AsyncMock) as mock_api:
+ mock_api.return_value = sample_creative_data
+
+ result = await create_ad_creative(
+ access_token="test_token",
+ account_id="act_123456789",
+ name="Test Creative",
+ image_hash="abc123",
+ page_id="987654321",
+ link_url="https://example.com",
+ message="Test message",
+ headlines=["Headline 1", "Headline 2"],
+ descriptions=["Description 1", "Description 2"],
+ dynamic_creative_spec={
+ "headline_optimization": True,
+ "description_optimization": True
+ },
+ call_to_action_type="LEARN_MORE"
+ )
+
+ result_data = json.loads(result)
+ assert result_data["success"] is True
+
+ # Verify the API call was made with dynamic_creative_spec
+ # We need to check the first call (creative creation), not the second call (details fetch)
+ call_args_list = mock_api.call_args_list
+ assert len(call_args_list) >= 1
+
+ # First call should be the creative creation
+ first_call = call_args_list[0]
+ creative_data = first_call[0][2] # params is the third argument
+
+ # Should include dynamic_creative_spec
+ assert "dynamic_creative_spec" in creative_data
+ assert creative_data["dynamic_creative_spec"]["headline_optimization"] is True
+ assert creative_data["dynamic_creative_spec"]["description_optimization"] is True
+
+ async def test_create_ad_creative_multiple_headlines_and_descriptions(self):
+ """Test creating ad creative with both multiple headlines and descriptions."""
+
+ sample_creative_data = {
+ "id": "123456789",
+ "name": "Test Creative",
+ "status": "ACTIVE"
+ }
+
+ with patch('meta_ads_mcp.core.ads.make_api_request', new_callable=AsyncMock) as mock_api:
+ mock_api.return_value = sample_creative_data
+
+ result = await create_ad_creative(
+ access_token="test_token",
+ account_id="act_123456789",
+ name="Test Creative",
+ image_hash="abc123",
+ page_id="987654321",
+ link_url="https://example.com",
+ message="Test message",
+ headlines=["Headline 1", "Headline 2", "Headline 3"],
+ descriptions=["Description 1", "Description 2"],
+ dynamic_creative_spec={
+ "headline_optimization": True,
+ "description_optimization": True
+ },
+ call_to_action_type="LEARN_MORE"
+ )
+
+ result_data = json.loads(result)
+ assert result_data["success"] is True
+
+ # Verify the API call was made with both multiple headlines and descriptions
+ # We need to check the first call (creative creation), not the second call (details fetch)
+ call_args_list = mock_api.call_args_list
+ assert len(call_args_list) >= 1
+
+ # First call should be the creative creation
+ first_call = call_args_list[0]
+ creative_data = first_call[0][2] # params is the third argument
+
+ assert "asset_feed_spec" in creative_data
+ assert "headlines" in creative_data["asset_feed_spec"]
+ assert "descriptions" in creative_data["asset_feed_spec"]
+ assert "dynamic_creative_spec" in creative_data
+
+ async def test_create_ad_creative_validation_max_headlines(self):
+ """Test validation for maximum number of headlines."""
+
+ # Create list with more than 5 headlines (assuming 5 is the limit)
+ too_many_headlines = [f"Headline {i}" for i in range(6)]
+
+ result = await create_ad_creative(
+ access_token="test_token",
+ account_id="act_123456789",
+ name="Test Creative",
+ image_hash="abc123",
+ page_id="987654321",
+ headlines=too_many_headlines
+ )
+
+ result_data = json.loads(result)
+ # The error might be wrapped in a 'data' field
+ if "data" in result_data:
+ error_data = json.loads(result_data["data"])
+ assert "error" in error_data
+ assert "maximum" in error_data["error"].lower() or "limit" in error_data["error"].lower()
+ else:
+ assert "error" in result_data
+ assert "maximum" in result_data["error"].lower() or "limit" in result_data["error"].lower()
+
+ async def test_create_ad_creative_validation_max_descriptions(self):
+ """Test validation for maximum number of descriptions."""
+
+ # Create list with more than 5 descriptions (assuming 5 is the limit)
+ too_many_descriptions = [f"Description {i}" for i in range(6)]
+
+ result = await create_ad_creative(
+ access_token="test_token",
+ account_id="act_123456789",
+ name="Test Creative",
+ image_hash="abc123",
+ page_id="987654321",
+ descriptions=too_many_descriptions
+ )
+
+ result_data = json.loads(result)
+ # The error might be wrapped in a 'data' field
+ if "data" in result_data:
+ error_data = json.loads(result_data["data"])
+ assert "error" in error_data
+ assert "maximum" in error_data["error"].lower() or "limit" in error_data["error"].lower()
+ else:
+ assert "error" in result_data
+ assert "maximum" in result_data["error"].lower() or "limit" in result_data["error"].lower()
+
+
+
+ async def test_update_ad_creative_add_headlines(self):
+ """Test updating an existing creative to add multiple headlines."""
+
+ sample_creative_data = {
+ "id": "123456789",
+ "name": "Updated Creative",
+ "status": "ACTIVE"
+ }
+
+ with patch('meta_ads_mcp.core.ads.make_api_request', new_callable=AsyncMock) as mock_api:
+ mock_api.return_value = sample_creative_data
+
+ result = await update_ad_creative(
+ access_token="test_token",
+ creative_id="123456789",
+ headlines=["New Headline 1", "New Headline 2", "New Headline 3"]
+ )
+
+ result_data = json.loads(result)
+ assert result_data["success"] is True
+
+ # Verify the API call was made with updated headlines
+ # We need to check the first call (creative update), not the second call (details fetch)
+ call_args_list = mock_api.call_args_list
+ assert len(call_args_list) >= 1
+
+ # First call should be the creative update
+ first_call = call_args_list[0]
+ creative_data = first_call[0][2] # params is the third argument
+
+ assert "asset_feed_spec" in creative_data
+ assert "headlines" in creative_data["asset_feed_spec"]
+ assert creative_data["asset_feed_spec"]["headlines"] == [
+ {"text": "New Headline 1"},
+ {"text": "New Headline 2"},
+ {"text": "New Headline 3"}
+ ]
+
+ async def test_update_ad_creative_add_descriptions(self):
+ """Test updating an existing creative to add multiple descriptions."""
+
+ sample_creative_data = {
+ "id": "123456789",
+ "name": "Updated Creative",
+ "status": "ACTIVE"
+ }
+
+ with patch('meta_ads_mcp.core.ads.make_api_request', new_callable=AsyncMock) as mock_api:
+ mock_api.return_value = sample_creative_data
+
+ result = await update_ad_creative(
+ access_token="test_token",
+ creative_id="123456789",
+ descriptions=["New Description 1", "New Description 2"]
+ )
+
+ result_data = json.loads(result)
+ assert result_data["success"] is True
+
+ # Verify the API call was made with updated descriptions
+ # We need to check the first call (creative update), not the second call (details fetch)
+ call_args_list = mock_api.call_args_list
+ assert len(call_args_list) >= 1
+
+ # First call should be the creative update
+ first_call = call_args_list[0]
+ creative_data = first_call[0][2] # params is the third argument
+
+ assert "asset_feed_spec" in creative_data
+ assert "descriptions" in creative_data["asset_feed_spec"]
+ assert creative_data["asset_feed_spec"]["descriptions"] == [
+ {"text": "New Description 1"},
+ {"text": "New Description 2"}
+ ]
+
+ async def test_update_ad_creative_update_dynamic_spec(self):
+ """Test updating an existing creative's dynamic_creative_spec."""
+
+ sample_creative_data = {
+ "id": "123456789",
+ "name": "Updated Creative",
+ "status": "ACTIVE"
+ }
+
+ with patch('meta_ads_mcp.core.ads.make_api_request', new_callable=AsyncMock) as mock_api:
+ mock_api.return_value = sample_creative_data
+
+ result = await update_ad_creative(
+ access_token="test_token",
+ creative_id="123456789",
+ dynamic_creative_spec={
+ "headline_optimization": True,
+ "description_optimization": False
+ }
+ )
+
+ result_data = json.loads(result)
+ assert result_data["success"] is True
+
+ # Verify the API call was made with updated dynamic_creative_spec
+ # We need to check the first call (creative update), not the second call (details fetch)
+ call_args_list = mock_api.call_args_list
+ assert len(call_args_list) >= 1
+
+ # First call should be the creative update
+ first_call = call_args_list[0]
+ creative_data = first_call[0][2] # params is the third argument
+
+ assert "dynamic_creative_spec" in creative_data
+ assert creative_data["dynamic_creative_spec"]["headline_optimization"] is True
+ assert creative_data["dynamic_creative_spec"]["description_optimization"] is False
+
+ async def test_update_ad_creative_no_creative_id(self):
+ """Test update_ad_creative with no creative_id provided."""
+
+ result = await update_ad_creative(
+ access_token="test_token",
+ headlines=["New Headline"]
+ )
+
+ result_data = json.loads(result)
+ # The error might be wrapped in a 'data' field
+ if "data" in result_data:
+ error_data = json.loads(result_data["data"])
+ assert "error" in error_data
+ assert "creative id" in error_data["error"].lower()
+ else:
+ assert "error" in result_data
+ assert "creative id" in result_data["error"].lower()
+
+ async def test_update_ad_creative_cannot_mix_headline_and_headlines(self):
+ """Test that mixing headline and headlines parameters raises error in update."""
+
+ result = await update_ad_creative(
+ access_token="test_token",
+ creative_id="123456789",
+ headline="Single Headline",
+ headlines=["Headline 1", "Headline 2"]
+ )
+
+ result_data = json.loads(result)
+
+ # Check if error is wrapped in "data" field (MCP error response format)
+ if "data" in result_data:
+ error_data = json.loads(result_data["data"])
+ assert "error" in error_data
+ assert "Cannot specify both 'headline' and 'headlines'" in error_data["error"]
+ else:
+ assert "error" in result_data
+ assert "Cannot specify both 'headline' and 'headlines'" in result_data["error"]
+
+ async def test_update_ad_creative_cannot_mix_description_and_descriptions(self):
+ """Test that mixing description and descriptions parameters raises error in update."""
+
+ result = await update_ad_creative(
+ access_token="test_token",
+ creative_id="123456789",
+ description="Single Description",
+ descriptions=["Description 1", "Description 2"]
+ )
+
+ result_data = json.loads(result)
+
+ # Check if error is wrapped in "data" field (MCP error response format)
+ if "data" in result_data:
+ error_data = json.loads(result_data["data"])
+ assert "error" in error_data
+ assert "Cannot specify both 'description' and 'descriptions'" in error_data["error"]
+ else:
+ assert "error" in result_data
+ assert "Cannot specify both 'description' and 'descriptions'" in result_data["error"]
+
+ async def test_update_ad_creative_validation_max_headlines(self):
+ """Test validation for maximum number of headlines in update."""
+
+ # Create list with more than 5 headlines (limit)
+ too_many_headlines = [f"Headline {i}" for i in range(6)]
+
+ result = await update_ad_creative(
+ access_token="test_token",
+ creative_id="123456789",
+ headlines=too_many_headlines
+ )
+
+ result_data = json.loads(result)
+ # The error might be wrapped in a 'data' field
+ if "data" in result_data:
+ error_data = json.loads(result_data["data"])
+ assert "error" in error_data
+ assert "maximum 5 headlines" in error_data["error"].lower()
+ else:
+ assert "error" in result_data
+ assert "maximum 5 headlines" in result_data["error"].lower()
+
+ async def test_update_ad_creative_validation_max_descriptions(self):
+ """Test validation for maximum number of descriptions in update."""
+
+ # Create list with more than 5 descriptions (limit)
+ too_many_descriptions = [f"Description {i}" for i in range(6)]
+
+ result = await update_ad_creative(
+ access_token="test_token",
+ creative_id="123456789",
+ descriptions=too_many_descriptions
+ )
+
+ result_data = json.loads(result)
+ # The error might be wrapped in a 'data' field
+ if "data" in result_data:
+ error_data = json.loads(result_data["data"])
+ assert "error" in error_data
+ assert "maximum 5 descriptions" in error_data["error"].lower()
+ else:
+ assert "error" in result_data
+ assert "maximum 5 descriptions" in result_data["error"].lower()
+
+ async def test_update_ad_creative_validation_headline_length(self):
+ """Test validation for headline character limit."""
+
+ # Create headline longer than 40 characters
+ long_headline = "A" * 41
+
+ result = await update_ad_creative(
+ access_token="test_token",
+ creative_id="123456789",
+ headlines=[long_headline]
+ )
+
+ result_data = json.loads(result)
+ # The error might be wrapped in a 'data' field
+ if "data" in result_data:
+ error_data = json.loads(result_data["data"])
+ assert "error" in error_data
+ assert "40 character limit" in error_data["error"]
+ else:
+ assert "error" in result_data
+ assert "40 character limit" in result_data["error"]
+
+ async def test_update_ad_creative_validation_description_length(self):
+ """Test validation for description character limit."""
+
+ # Create description longer than 125 characters
+ long_description = "A" * 126
+
+ result = await update_ad_creative(
+ access_token="test_token",
+ creative_id="123456789",
+ descriptions=[long_description]
+ )
+
+ result_data = json.loads(result)
+ # The error might be wrapped in a 'data' field
+ if "data" in result_data:
+ error_data = json.loads(result_data["data"])
+ assert "error" in error_data
+ assert "125 character limit" in error_data["error"]
+ else:
+ assert "error" in result_data
+ assert "125 character limit" in result_data["error"]
+
+ async def test_update_ad_creative_name_only(self):
+ """Test updating just the creative name."""
+
+ sample_creative_data = {
+ "id": "123456789",
+ "name": "Updated Creative Name",
+ "status": "ACTIVE"
+ }
+
+ with patch('meta_ads_mcp.core.ads.make_api_request', new_callable=AsyncMock) as mock_api:
+ mock_api.return_value = sample_creative_data
+
+ result = await update_ad_creative(
+ access_token="test_token",
+ creative_id="123456789",
+ name="Updated Creative Name"
+ )
+
+ result_data = json.loads(result)
+ assert result_data["success"] is True
+
+ # Verify the API call was made with just the name
+ call_args_list = mock_api.call_args_list
+ assert len(call_args_list) >= 1
+
+ first_call = call_args_list[0]
+ creative_data = first_call[0][2] # params is the third argument
+
+ assert "name" in creative_data
+ assert creative_data["name"] == "Updated Creative Name"
+ # Should not have asset_feed_spec since no dynamic content
+ assert "asset_feed_spec" not in creative_data
+
+ async def test_update_ad_creative_message_only(self):
+ """Test updating just the creative message."""
+
+ sample_creative_data = {
+ "id": "123456789",
+ "name": "Test Creative",
+ "status": "ACTIVE"
+ }
+
+ with patch('meta_ads_mcp.core.ads.make_api_request', new_callable=AsyncMock) as mock_api:
+ mock_api.return_value = sample_creative_data
+
+ result = await update_ad_creative(
+ access_token="test_token",
+ creative_id="123456789",
+ message="Updated message text"
+ )
+
+ result_data = json.loads(result)
+ assert result_data["success"] is True
+
+ # Verify the API call was made with object_story_spec
+ call_args_list = mock_api.call_args_list
+ assert len(call_args_list) >= 1
+
+ first_call = call_args_list[0]
+ creative_data = first_call[0][2] # params is the third argument
+
+ assert "object_story_spec" in creative_data
+ assert creative_data["object_story_spec"]["link_data"]["message"] == "Updated message text"
+
+ async def test_update_ad_creative_cta_with_dynamic_content(self):
+ """Test updating call_to_action_type with dynamic creative content."""
+
+ sample_creative_data = {
+ "id": "123456789",
+ "name": "Test Creative",
+ "status": "ACTIVE"
+ }
+
+ with patch('meta_ads_mcp.core.ads.make_api_request', new_callable=AsyncMock) as mock_api:
+ mock_api.return_value = sample_creative_data
+
+ result = await update_ad_creative(
+ access_token="test_token",
+ creative_id="123456789",
+ headlines=["Test Headline"],
+ call_to_action_type="SHOP_NOW"
+ )
+
+ result_data = json.loads(result)
+ assert result_data["success"] is True
+
+ # Verify CTA is added to asset_feed_spec when dynamic content exists
+ call_args_list = mock_api.call_args_list
+ assert len(call_args_list) >= 1
+
+ first_call = call_args_list[0]
+ creative_data = first_call[0][2] # params is the third argument
+
+ assert "asset_feed_spec" in creative_data
+ assert "call_to_action_types" in creative_data["asset_feed_spec"]
+ assert creative_data["asset_feed_spec"]["call_to_action_types"] == ["SHOP_NOW"]
+
+ async def test_update_ad_creative_cta_without_dynamic_content(self):
+ """Test updating call_to_action_type without dynamic creative content."""
+
+ sample_creative_data = {
+ "id": "123456789",
+ "name": "Test Creative",
+ "status": "ACTIVE"
+ }
+
+ with patch('meta_ads_mcp.core.ads.make_api_request', new_callable=AsyncMock) as mock_api:
+ mock_api.return_value = sample_creative_data
+
+ result = await update_ad_creative(
+ access_token="test_token",
+ creative_id="123456789",
+ call_to_action_type="LEARN_MORE"
+ )
+
+ result_data = json.loads(result)
+ assert result_data["success"] is True
+
+ # Verify CTA is added to object_story_spec when no dynamic content
+ call_args_list = mock_api.call_args_list
+ assert len(call_args_list) >= 1
+
+ first_call = call_args_list[0]
+ creative_data = first_call[0][2] # params is the third argument
+
+ assert "object_story_spec" in creative_data
+ assert "call_to_action" in creative_data["object_story_spec"]["link_data"]
+ assert creative_data["object_story_spec"]["link_data"]["call_to_action"]["type"] == "LEARN_MORE"
+
+ async def test_update_ad_creative_combined_updates(self):
+ """Test updating multiple parameters at once."""
+
+ sample_creative_data = {
+ "id": "123456789",
+ "name": "Multi-Updated Creative",
+ "status": "ACTIVE"
+ }
+
+ with patch('meta_ads_mcp.core.ads.make_api_request', new_callable=AsyncMock) as mock_api:
+ mock_api.return_value = sample_creative_data
+
+ result = await update_ad_creative(
+ access_token="test_token",
+ creative_id="123456789",
+ name="Multi-Updated Creative",
+ message="Updated message",
+ headlines=["New Headline 1", "New Headline 2"],
+ descriptions=["New Description 1"],
+ call_to_action_type="SIGN_UP"
+ )
+
+ result_data = json.loads(result)
+ assert result_data["success"] is True
+
+ # Verify all updates are included
+ call_args_list = mock_api.call_args_list
+ assert len(call_args_list) >= 1
+
+ first_call = call_args_list[0]
+ creative_data = first_call[0][2] # params is the third argument
+
+ # Should have name
+ assert creative_data["name"] == "Multi-Updated Creative"
+
+ # Should have asset_feed_spec with all dynamic content
+ assert "asset_feed_spec" in creative_data
+ assert "headlines" in creative_data["asset_feed_spec"]
+ assert "descriptions" in creative_data["asset_feed_spec"]
+ assert "primary_texts" in creative_data["asset_feed_spec"]
+ assert "call_to_action_types" in creative_data["asset_feed_spec"]
+
+ # Verify content
+ assert creative_data["asset_feed_spec"]["headlines"] == [
+ {"text": "New Headline 1"}, {"text": "New Headline 2"}
+ ]
+ assert creative_data["asset_feed_spec"]["descriptions"] == [
+ {"text": "New Description 1"}
+ ]
+ assert creative_data["asset_feed_spec"]["primary_texts"] == [
+ {"text": "Updated message"}
+ ]
+ assert creative_data["asset_feed_spec"]["call_to_action_types"] == ["SIGN_UP"]
+
+ async def test_update_ad_creative_api_error_handling(self):
+ """Test error handling when API request fails."""
+
+ with patch('meta_ads_mcp.core.ads.make_api_request', new_callable=AsyncMock) as mock_api:
+ mock_api.side_effect = Exception("API request failed")
+
+ result = await update_ad_creative(
+ access_token="test_token",
+ creative_id="123456789",
+ name="Test Creative"
+ )
+
+ result_data = json.loads(result)
+ # The error might be wrapped in a 'data' field
+ if "data" in result_data:
+ error_data = json.loads(result_data["data"])
+ assert "error" in error_data
+ assert error_data["error"] == "Failed to update ad creative"
+ assert "details" in error_data
+ assert "update_data_sent" in error_data
+ else:
+ assert "error" in result_data
+ assert result_data["error"] == "Failed to update ad creative"
+ assert "details" in result_data
+ assert "update_data_sent" in result_data
+
\ No newline at end of file
diff --git a/tests/test_page_discovery_integration.py b/tests/test_page_discovery_integration.py
index db33d8d..7275d78 100644
--- a/tests/test_page_discovery_integration.py
+++ b/tests/test_page_discovery_integration.py
@@ -37,10 +37,10 @@ class TestPageDiscoveryIntegration:
with patch('meta_ads_mcp.core.ads._discover_pages_for_account') as mock_discover, \
patch('meta_ads_mcp.core.ads.make_api_request') as mock_api, \
- patch('meta_ads_mcp.core.api.meta_api_tool') as mock_decorator:
+ patch('meta_ads_mcp.core.auth.get_current_access_token') as mock_get_token:
- # Make the decorator just return the function
- mock_decorator.side_effect = lambda func: func
+ # Provide a valid access token to bypass authentication
+ mock_get_token.return_value = "test_token_123"
mock_discover.return_value = mock_discovery_result
mock_api.return_value = mock_creative_response
@@ -51,18 +51,23 @@ class TestPageDiscoveryIntegration:
name="Test Creative",
image_hash="test_hash_123",
message="Test message",
- headline="Test Headline",
- description="Test description"
+ access_token="test_token_123" # Provide explicit token
)
result_data = json.loads(result)
+ # Handle MCP wrapper - check if result is wrapped in 'data' field
+ if "data" in result_data:
+ actual_result = json.loads(result_data["data"])
+ else:
+ actual_result = result_data
+
# Verify that the function attempted to create a creative (even though it failed due to invalid image)
- assert "error" in result_data["data"]
- assert "Image Not Found" in result_data["data"]["error"]["error_user_title"]
+ assert "error" in actual_result
+ assert "Image Not Found" in actual_result["error"]["error_user_title"]
# Verify that page discovery was called
- mock_discover.assert_called_once_with("act_123456789", None)
+ mock_discover.assert_called_once_with("act_123456789", "test_token_123")
@pytest.mark.asyncio
async def test_search_pages_by_name_integration(self):
@@ -76,28 +81,35 @@ class TestPageDiscoveryIntegration:
}
with patch('meta_ads_mcp.core.ads._discover_pages_for_account') as mock_discover, \
- patch('meta_ads_mcp.core.api.meta_api_tool') as mock_decorator:
+ patch('meta_ads_mcp.core.auth.get_current_access_token') as mock_get_token:
- # Make the decorator just return the function
- mock_decorator.side_effect = lambda func: func
+ # Provide a valid access token to bypass authentication
+ mock_get_token.return_value = "test_token_123"
mock_discover.return_value = mock_discovery_result
# Test searching for pages
result = await search_pages_by_name(
account_id="act_123456789",
- search_term="Injury"
+ search_term="Injury",
+ access_token="test_token_123" # Provide explicit token
)
result_data = json.loads(result)
+ # Handle MCP wrapper - check if result is wrapped in 'data' field
+ if "data" in result_data and isinstance(result_data["data"], str):
+ actual_result = json.loads(result_data["data"])
+ else:
+ actual_result = result_data
+
# Verify the search results
- assert len(result_data["data"]) == 1
- assert result_data["data"][0]["id"] == "123456789"
- assert result_data["data"][0]["name"] == "Injury Payouts"
- assert result_data["search_term"] == "Injury"
- assert result_data["total_found"] == 1
- assert result_data["total_available"] == 1
+ assert len(actual_result["data"]) == 1
+ assert actual_result["data"][0]["id"] == "123456789"
+ assert actual_result["data"][0]["name"] == "Injury Payouts"
+ assert actual_result["search_term"] == "Injury"
+ assert actual_result["total_found"] == 1
+ assert actual_result["total_available"] == 1
@pytest.mark.asyncio
async def test_create_ad_creative_with_manual_page_id(self):
@@ -115,10 +127,10 @@ class TestPageDiscoveryIntegration:
}
with patch('meta_ads_mcp.core.ads.make_api_request') as mock_api, \
- patch('meta_ads_mcp.core.api.meta_api_tool') as mock_decorator:
+ patch('meta_ads_mcp.core.auth.get_current_access_token') as mock_get_token:
- # Make the decorator just return the function
- mock_decorator.side_effect = lambda func: func
+ # Provide a valid access token to bypass authentication
+ mock_get_token.return_value = "test_token_123"
mock_api.return_value = mock_creative_response
@@ -129,15 +141,20 @@ class TestPageDiscoveryIntegration:
image_hash="test_hash_123",
page_id="123456789", # Manual page ID
message="Test message",
- headline="Test Headline",
- description="Test description"
+ access_token="test_token_123" # Provide explicit token
)
result_data = json.loads(result)
+ # Handle MCP wrapper - check if result is wrapped in 'data' field
+ if "data" in result_data:
+ actual_result = json.loads(result_data["data"])
+ else:
+ actual_result = result_data
+
# Verify that the function attempted to create a creative
- assert "error" in result_data["data"]
- assert "Image Not Found" in result_data["data"]["error"]["error_user_title"]
+ assert "error" in actual_result
+ assert "Image Not Found" in actual_result["error"]["error_user_title"]
# Verify that make_api_request was called for creating the creative
mock_api.assert_called_once()
@@ -152,10 +169,10 @@ class TestPageDiscoveryIntegration:
}
with patch('meta_ads_mcp.core.ads._discover_pages_for_account') as mock_discover, \
- patch('meta_ads_mcp.core.api.meta_api_tool') as mock_decorator:
+ patch('meta_ads_mcp.core.auth.get_current_access_token') as mock_get_token:
- # Make the decorator just return the function
- mock_decorator.side_effect = lambda func: func
+ # Provide a valid access token to bypass authentication
+ mock_get_token.return_value = "test_token_123"
mock_discover.return_value = mock_discovery_result
@@ -164,15 +181,22 @@ class TestPageDiscoveryIntegration:
account_id="act_123456789",
name="Test Creative",
image_hash="test_hash_123",
- message="Test message"
+ message="Test message",
+ access_token="test_token_123" # Provide explicit token
)
result_data = json.loads(result)
+ # Handle MCP wrapper - check if result is wrapped in 'data' field
+ if "data" in result_data:
+ actual_result = json.loads(result_data["data"])
+ else:
+ actual_result = result_data
+
# Verify that the function returned an error about no pages found
- assert "error" in result_data["data"]
- assert "No page ID provided and no suitable pages found" in result_data["data"]["error"]
- assert "suggestions" in result_data["data"]["error"]
+ assert "error" in actual_result
+ assert "No page ID provided and no suitable pages found" in actual_result["error"]
+ assert "suggestions" in actual_result
@pytest.mark.asyncio
async def test_search_pages_by_name_no_search_term(self):
@@ -186,26 +210,33 @@ class TestPageDiscoveryIntegration:
}
with patch('meta_ads_mcp.core.ads._discover_pages_for_account') as mock_discover, \
- patch('meta_ads_mcp.core.api.meta_api_tool') as mock_decorator:
+ patch('meta_ads_mcp.core.auth.get_current_access_token') as mock_get_token:
- # Make the decorator just return the function
- mock_decorator.side_effect = lambda func: func
+ # Provide a valid access token to bypass authentication
+ mock_get_token.return_value = "test_token_123"
mock_discover.return_value = mock_discovery_result
# Test searching without a search term
result = await search_pages_by_name(
- account_id="act_123456789"
+ account_id="act_123456789",
+ access_token="test_token_123" # Provide explicit token
)
result_data = json.loads(result)
+ # Handle MCP wrapper - check if result is wrapped in 'data' field
+ if "data" in result_data and isinstance(result_data["data"], str):
+ actual_result = json.loads(result_data["data"])
+ else:
+ actual_result = result_data
+
# Verify the results
- assert len(result_data["data"]) == 1
- assert result_data["data"][0]["id"] == "123456789"
- assert result_data["data"][0]["name"] == "Test Page"
- assert result_data["total_available"] == 1
- assert "note" in result_data
+ assert len(actual_result["data"]) == 1
+ assert actual_result["data"][0]["id"] == "123456789"
+ assert actual_result["data"][0]["name"] == "Test Page"
+ assert actual_result["total_available"] == 1
+ assert "note" in actual_result
@pytest.mark.asyncio
async def test_search_pages_by_name_no_matches(self):
@@ -219,26 +250,33 @@ class TestPageDiscoveryIntegration:
}
with patch('meta_ads_mcp.core.ads._discover_pages_for_account') as mock_discover, \
- patch('meta_ads_mcp.core.api.meta_api_tool') as mock_decorator:
+ patch('meta_ads_mcp.core.auth.get_current_access_token') as mock_get_token:
- # Make the decorator just return the function
- mock_decorator.side_effect = lambda func: func
+ # Provide a valid access token to bypass authentication
+ mock_get_token.return_value = "test_token_123"
mock_discover.return_value = mock_discovery_result
# Test searching for a term that doesn't match
result = await search_pages_by_name(
account_id="act_123456789",
- search_term="Nonexistent"
+ search_term="Nonexistent",
+ access_token="test_token_123" # Provide explicit token
)
result_data = json.loads(result)
+ # Handle MCP wrapper - check if result is wrapped in 'data' field
+ if "data" in result_data and isinstance(result_data["data"], str):
+ actual_result = json.loads(result_data["data"])
+ else:
+ actual_result = result_data
+
# Verify that no pages were found
- assert len(result_data["data"]) == 0
- assert result_data["search_term"] == "Nonexistent"
- assert result_data["total_found"] == 0
- assert result_data["total_available"] == 1
+ assert len(actual_result["data"]) == 0
+ assert actual_result["search_term"] == "Nonexistent"
+ assert actual_result["total_found"] == 0
+ assert actual_result["total_available"] == 1
if __name__ == "__main__":