Meta Ads (Facebook/Instagram) MCP server for Claude, ChatGPT, Perplexity & Cursor — the Meta node of Pipeboard’s 5-platform family (+ Google, TikTok, Snap, Reddit). Hosted remote MCP, badged Meta Business Partner, free plan — no self-hosting required.
Python advertisingai-agentschatgptclaudefacebook-adsinstagram-adsmcpmeta-adsmodel-context-protocolpipeboard
feat: enhance create_ad_creative with FLEX support and validation
Yves Junqueira1dbf4f883a2c
diff --git a/meta_ads_mcp/core/ads.py b/meta_ads_mcp/core/ads.pyindex 0d351f3..6f4d92b 100644--- a/meta_ads_mcp/core/ads.py+++ b/meta_ads_mcp/core/ads.py@@ -747,16 +747,19 @@ async def upload_ad_image(@meta_api_toolasync def create_ad_creative(account_id: str,- image_hash: str,+ image_hash: Optional[str] = None,access_token: Optional[str] = None,name: Optional[str] = None,page_id: Optional[str] = None,link_url: Optional[str] = None,message: Optional[str] = None,+ messages: Optional[List[str]] = None,headline: Optional[str] = None,headlines: Optional[List[str]] = None,description: Optional[str] = None,descriptions: Optional[List[str]] = None,+ image_hashes: Optional[List[str]] = None,+ optimization_type: Optional[str] = None,dynamic_creative_spec: Optional[Dict[str, Any]] = None,call_to_action_type: Optional[str] = None,lead_gen_form_id: Optional[str] = None,@@ -764,34 +767,56 @@ async def create_ad_creative() -> str:"""Create a new ad creative using an uploaded image hash.-+Args:account_id: Meta Ads account ID (format: act_XXXXXXXXX)- image_hash: Hash of the uploaded image+ image_hash: Hash of a single uploaded image (cannot be used with image_hashes)access_token: Meta API access token (optional - will use cached token if not provided)name: Creative namepage_id: Facebook Page ID (string or int; coerced to string)link_url: Destination URL for the ad- message: Ad copy/text+ message: Single ad copy/text (cannot be used with messages)+ messages: List of primary text variants for FLEX/dynamic creatives (cannot be used with message)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)+ image_hashes: List of image hashes for FLEX creatives (up to 10, cannot be used with image_hash)+ optimization_type: Set to "DEGREES_OF_FREEDOM" for FLEX (Advantage+) creatives that allow+ Meta to auto-optimize across all asset combinations without requiring+ is_dynamic_creative=true on the ad setdynamic_creative_spec: Dynamic creative optimization settingscall_to_action_type: Call to action button type (e.g., 'LEARN_MORE', 'SIGN_UP', 'SHOP_NOW')lead_gen_form_id: Lead generation form ID for lead generation campaigns. Required when usinglead generation CTAs like 'SIGN_UP', 'GET_OFFER', 'SUBSCRIBE', etc.instagram_actor_id: Optional Instagram account ID for Instagram placements-+Returns:JSON response with created creative details"""# Check required parametersif not account_id:return json.dumps({"error": "No account ID provided"}, indent=2)-- if not image_hash:- return json.dumps({"error": "No image hash provided"}, indent=2)++ # Validate image_hash / image_hashes mutual exclusivity+ if image_hash and image_hashes:+ return json.dumps({"error": "Cannot specify both 'image_hash' and 'image_hashes'. Use 'image_hash' for a single image or 'image_hashes' for multiple."}, indent=2)++ if not image_hash and not image_hashes:+ return json.dumps({"error": "No image hash provided. Specify 'image_hash' for a single image or 'image_hashes' for multiple."}, indent=2)++ # Validate image_hashes limits+ if image_hashes:+ if len(image_hashes) > 10:+ return json.dumps({"error": "Maximum 10 image hashes allowed for FLEX creatives"}, indent=2)++ # Validate optimization_type+ if optimization_type and optimization_type != "DEGREES_OF_FREEDOM":+ return json.dumps({"error": f"Invalid optimization_type '{optimization_type}'. Only 'DEGREES_OF_FREEDOM' is supported."}, indent=2)++ # Validate message / messages mutual exclusivity+ if message and messages:+ return json.dumps({"error": "Cannot specify both 'message' and 'messages'. Use 'message' for single text or 'messages' for multiple variants."}, indent=2)if not name:name = f"Creative {int(time.time())}"@@ -844,51 +869,63 @@ async def create_ad_creative(for i, h in enumerate(headlines):if len(h) > 40:return json.dumps({"error": f"Headline {i+1} exceeds 40 character limit"}, indent=2)-+if descriptions:if len(descriptions) > 5:return json.dumps({"error": "Maximum 5 descriptions allowed for dynamic creatives"}, indent=2)for i, d in enumerate(descriptions):if len(d) > 125:return json.dumps({"error": f"Description {i+1} exceeds 125 character limit"}, indent=2)-+# Prepare the creative datacreative_data = {"name": name}-- # Choose between asset_feed_spec (dynamic creative) or object_story_spec (traditional)- # ONLY use asset_feed_spec when user explicitly provides plural parameters (headlines/descriptions)- if headlines or descriptions:- # Use asset_feed_spec for dynamic creatives with multiple variants- # Structure based on Meta API working example from documentation- # ad_formats must be specified with exactly one format++ # Determine whether to use asset_feed_spec path:+ # - plural parameters (headlines/descriptions/messages/image_hashes), OR+ # - optimization_type is set (FLEX creatives always use asset_feed_spec)+ use_asset_feed = bool(headlines or descriptions or messages or image_hashes or optimization_type)++ if use_asset_feed:+ # Build the images array from image_hashes (plural) or image_hash (singular)+ if image_hashes:+ images_array = [{"hash": h} for h in image_hashes]+ else:+ images_array = [{"hash": image_hash}]++ # Use asset_feed_spec for dynamic/FLEX creatives with multiple variantsasset_feed_spec = {- "images": [{"hash": image_hash}],+ "images": images_array,"link_urls": [{"website_url": link_url if link_url else "https://facebook.com"}],"ad_formats": ["SINGLE_IMAGE"]}-++ # Add optimization_type for FLEX (Advantage+) creatives+ if optimization_type:+ asset_feed_spec["optimization_type"] = optimization_type+# Handle headlines - Meta API uses "titles" not "headlines" in asset_feed_specif headlines:asset_feed_spec["titles"] = [{"text": headline_text} for headline_text in headlines]-- # Handle descriptions++ # Handle descriptionsif descriptions:asset_feed_spec["descriptions"] = [{"text": description_text} for description_text in descriptions]-- # Add message as bodies - Meta API uses "bodies" not "primary_texts" in asset_feed_spec- if message:++ # Handle bodies: messages (plural) or message (singular)+ if messages:+ asset_feed_spec["bodies"] = [{"text": m} for m in messages]+ elif message:asset_feed_spec["bodies"] = [{"text": message}]-+# Add call_to_action_types if providedif 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 with asset_feed_spec, object_story_spec only needs page_id- # Link information is already in asset_feed_spec.link_urls++ # For dynamic/FLEX creatives with asset_feed_spec, object_story_spec only needs page_idcreative_data["object_story_spec"] = {"page_id": page_id}@@ -901,27 +938,27 @@ async def create_ad_creative("link": link_url if link_url else "https://facebook.com"}}-+# Add optional parameters if providedif message:creative_data["object_story_spec"]["link_data"]["message"] = message-+# Add headline (singular) to link_dataif headline:creative_data["object_story_spec"]["link_data"]["name"] = headline-+# Add description (singular) to link_dataif description:creative_data["object_story_spec"]["link_data"]["description"] = description-+# Add call_to_action to link_data for simple creativesif call_to_action_type:cta_data = {"type": call_to_action_type}-+# Add lead form ID to value object if provided (required for lead generation campaigns)if lead_gen_form_id:cta_data["value"] = {"lead_gen_form_id": lead_gen_form_id}-+creative_data["object_story_spec"]["link_data"]["call_to_action"] = cta_data# Add dynamic creative spec if provided@@ -970,45 +1007,57 @@ async def update_ad_creative(access_token: Optional[str] = None,name: Optional[str] = None,message: Optional[str] = None,+ messages: Optional[List[str]] = None,headline: Optional[str] = None,headlines: Optional[List[str]] = None,description: Optional[str] = None,descriptions: Optional[List[str]] = None,+ optimization_type: Optional[str] = None,dynamic_creative_spec: Optional[Dict[str, Any]] = None,call_to_action_type: Optional[str] = None,lead_gen_form_id: Optional[str] = None) -> str:"""Update an existing ad creative with new content or settings.-+Args:creative_id: Meta Ads creative ID to updateaccess_token: Meta API access token (optional - will use cached token if not provided)name: New creative name- message: New ad copy/text+ message: New ad copy/text (cannot be used with messages)+ messages: List of primary text variants for FLEX/dynamic creatives (cannot be used with message)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)+ optimization_type: Set to "DEGREES_OF_FREEDOM" for FLEX (Advantage+) creativesdynamic_creative_spec: New dynamic creative optimization settingscall_to_action_type: New call to action button typelead_gen_form_id: Lead generation form ID for lead generation campaigns. Required when usinglead generation CTAs like 'SIGN_UP', 'GET_OFFER', 'SUBSCRIBE', etc.-+Returns:JSON response with updated creative details"""# Check required parametersif not creative_id:return json.dumps({"error": "No creative ID provided"}, indent=2)-+# Validate headline/description parameters - cannot mix simple and complexif 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)-++ # Validate message / messages mutual exclusivity+ if message and messages:+ return json.dumps({"error": "Cannot specify both 'message' and 'messages'. Use 'message' for single text or 'messages' for multiple variants."}, indent=2)++ # Validate optimization_type+ if optimization_type and optimization_type != "DEGREES_OF_FREEDOM":+ return json.dumps({"error": f"Invalid optimization_type '{optimization_type}'. Only 'DEGREES_OF_FREEDOM' is supported."}, indent=2)+# Validate dynamic creative parameters (plural forms only)if headlines:if len(headlines) > 5:@@ -1016,45 +1065,52 @@ async def update_ad_creative(for i, h in enumerate(headlines):if len(h) > 40:return json.dumps({"error": f"Headline {i+1} exceeds 40 character limit"}, indent=2)-+if descriptions:if len(descriptions) > 5:return json.dumps({"error": "Maximum 5 descriptions allowed for dynamic creatives"}, indent=2)for i, d in enumerate(descriptions):if len(d) > 125:return json.dumps({"error": f"Description {i+1} exceeds 125 character limit"}, indent=2)-+# Prepare the update dataupdate_data = {}-+if name:update_data["name"] = name-- # Choose between asset_feed_spec (dynamic creative) or object_story_spec (traditional)- # ONLY use asset_feed_spec when user explicitly provides plural parameters (headlines/descriptions)- if headlines or descriptions or dynamic_creative_spec:- # Handle dynamic creative assets via asset_feed_spec++ # Choose between asset_feed_spec (dynamic/FLEX creative) or object_story_spec (traditional)+ use_asset_feed = bool(headlines or descriptions or messages or optimization_type or dynamic_creative_spec)++ if use_asset_feed:+ # Handle dynamic/FLEX creative assets via asset_feed_specasset_feed_spec = {}-+# Add required ad_formats field for dynamic creativesasset_feed_spec["ad_formats"] = ["SINGLE_IMAGE"]-++ # Add optimization_type for FLEX (Advantage+) creatives+ if optimization_type:+ asset_feed_spec["optimization_type"] = optimization_type+# Handle headlines - Meta API uses "titles" not "headlines" in asset_feed_specif headlines:asset_feed_spec["titles"] = [{"text": headline_text} for headline_text in headlines]-- # Handle descriptions++ # Handle descriptionsif descriptions:asset_feed_spec["descriptions"] = [{"text": description_text} for description_text in descriptions]-- # Add message as bodies - Meta API uses "bodies" not "primary_texts" in asset_feed_spec- if message:++ # Handle bodies: messages (plural) or message (singular)+ if messages:+ asset_feed_spec["bodies"] = [{"text": m} for m in messages]+ elif message:asset_feed_spec["bodies"] = [{"text": message}]-+# Add call_to_action_types if providedif call_to_action_type:asset_feed_spec["call_to_action_types"] = [call_to_action_type]-+update_data["asset_feed_spec"] = asset_feed_specelse:# Use traditional object_story_spec with link_data for simple creativesdiff --git a/tests/test_flex_creatives.py b/tests/test_flex_creatives.pynew file mode 100644index 0000000..ee5e501--- /dev/null+++ b/tests/test_flex_creatives.py@@ -0,0 +1,494 @@+"""Tests for FLEX (DEGREES_OF_FREEDOM) creative features.++Tests for create_ad_creative and update_ad_creative support for:+- optimization_type="DEGREES_OF_FREEDOM" in asset_feed_spec+- Multiple image_hashes (up to 10)+- Multiple messages (primary text variants)+- Validation of mutual exclusivity and limits+- Backward compatibility (no optimization_type → same behavior as before)+"""++import pytest+import json+from unittest.mock import AsyncMock, patch+from meta_ads_mcp.core.ads import create_ad_creative, update_ad_creative+++class TestFlexCreatives:+ """Test cases for FLEX (Advantage+) creative features."""++ async def test_flex_creative_includes_optimization_type(self):+ """FLEX creative with optimization_type='DEGREES_OF_FREEDOM' includes it in asset_feed_spec."""+ sample_creative_data = {+ "id": "123456789",+ "name": "FLEX 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="FLEX Creative",+ image_hash="abc123",+ page_id="987654321",+ link_url="https://example.com",+ message="Test message",+ optimization_type="DEGREES_OF_FREEDOM",+ call_to_action_type="LEARN_MORE"+ )++ result_data = json.loads(result)+ assert result_data["success"] is True++ call_args_list = mock_api.call_args_list+ first_call = call_args_list[0]+ creative_data = first_call[0][2]++ assert "asset_feed_spec" in creative_data+ assert creative_data["asset_feed_spec"]["optimization_type"] == "DEGREES_OF_FREEDOM"++ async def test_flex_creative_multiple_image_hashes(self):+ """Multiple image_hashes produces correct images array in asset_feed_spec."""+ sample_creative_data = {+ "id": "123456789",+ "name": "Multi-Image FLEX",+ "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="Multi-Image FLEX",+ image_hashes=["hash1", "hash2", "hash3"],+ page_id="987654321",+ link_url="https://example.com",+ message="Test message",+ optimization_type="DEGREES_OF_FREEDOM"+ )++ result_data = json.loads(result)+ assert result_data["success"] is True++ call_args_list = mock_api.call_args_list+ first_call = call_args_list[0]+ creative_data = first_call[0][2]++ assert "asset_feed_spec" in creative_data+ assert creative_data["asset_feed_spec"]["images"] == [+ {"hash": "hash1"},+ {"hash": "hash2"},+ {"hash": "hash3"}+ ]++ async def test_flex_creative_multiple_messages(self):+ """Multiple messages produces correct bodies array in asset_feed_spec."""+ sample_creative_data = {+ "id": "123456789",+ "name": "Multi-Message FLEX",+ "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="Multi-Message FLEX",+ image_hash="abc123",+ page_id="987654321",+ link_url="https://example.com",+ messages=["Primary text A", "Primary text B", "Primary text C"],+ optimization_type="DEGREES_OF_FREEDOM"+ )++ result_data = json.loads(result)+ assert result_data["success"] is True++ call_args_list = mock_api.call_args_list+ first_call = call_args_list[0]+ creative_data = first_call[0][2]++ assert "asset_feed_spec" in creative_data+ assert creative_data["asset_feed_spec"]["bodies"] == [+ {"text": "Primary text A"},+ {"text": "Primary text B"},+ {"text": "Primary text C"}+ ]++ async def test_validation_cannot_mix_image_hash_and_image_hashes(self):+ """Cannot specify both image_hash and image_hashes."""+ result = await create_ad_creative(+ access_token="test_token",+ account_id="act_123456789",+ name="Test",+ image_hash="abc123",+ image_hashes=["hash1", "hash2"],+ page_id="987654321"+ )++ result_data = json.loads(result)+ if "data" in result_data:+ error_data = json.loads(result_data["data"])+ assert "error" in error_data+ assert "Cannot specify both 'image_hash' and 'image_hashes'" in error_data["error"]+ else:+ assert "error" in result_data+ assert "Cannot specify both 'image_hash' and 'image_hashes'" in result_data["error"]++ async def test_validation_cannot_mix_message_and_messages(self):+ """Cannot specify both message and messages."""+ result = await create_ad_creative(+ access_token="test_token",+ account_id="act_123456789",+ name="Test",+ image_hash="abc123",+ page_id="987654321",+ message="Single text",+ messages=["Text A", "Text B"]+ )++ result_data = json.loads(result)+ if "data" in result_data:+ error_data = json.loads(result_data["data"])+ assert "error" in error_data+ assert "Cannot specify both 'message' and 'messages'" in error_data["error"]+ else:+ assert "error" in result_data+ assert "Cannot specify both 'message' and 'messages'" in result_data["error"]++ async def test_validation_max_10_image_hashes(self):+ """Maximum 10 image hashes allowed for FLEX creatives."""+ too_many = [f"hash{i}" for i in range(11)]++ result = await create_ad_creative(+ access_token="test_token",+ account_id="act_123456789",+ name="Test",+ image_hashes=too_many,+ page_id="987654321"+ )++ result_data = json.loads(result)+ if "data" in result_data:+ error_data = json.loads(result_data["data"])+ assert "error" in error_data+ assert "Maximum 10 image hashes" in error_data["error"]+ else:+ assert "error" in result_data+ assert "Maximum 10 image hashes" in result_data["error"]++ async def test_validation_invalid_optimization_type(self):+ """Invalid optimization_type values are rejected."""+ result = await create_ad_creative(+ access_token="test_token",+ account_id="act_123456789",+ name="Test",+ image_hash="abc123",+ page_id="987654321",+ optimization_type="INVALID_VALUE"+ )++ result_data = json.loads(result)+ if "data" in result_data:+ error_data = json.loads(result_data["data"])+ assert "error" in error_data+ assert "Invalid optimization_type" in error_data["error"]+ else:+ assert "error" in result_data+ assert "Invalid optimization_type" in result_data["error"]++ async def test_flex_creative_single_image_uses_asset_feed_spec(self):+ """FLEX creative with single image still uses asset_feed_spec when optimization_type is set."""+ sample_creative_data = {+ "id": "123456789",+ "name": "Single Image FLEX",+ "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="Single Image FLEX",+ image_hash="abc123",+ page_id="987654321",+ link_url="https://example.com",+ message="Test message",+ optimization_type="DEGREES_OF_FREEDOM"+ )++ result_data = json.loads(result)+ assert result_data["success"] is True++ call_args_list = mock_api.call_args_list+ first_call = call_args_list[0]+ creative_data = first_call[0][2]++ # Should use asset_feed_spec even with single image when optimization_type is set+ assert "asset_feed_spec" in creative_data+ assert creative_data["asset_feed_spec"]["images"] == [{"hash": "abc123"}]+ assert creative_data["asset_feed_spec"]["optimization_type"] == "DEGREES_OF_FREEDOM"+ # object_story_spec should only have page_id (no link_data)+ assert creative_data["object_story_spec"] == {"page_id": "987654321"}++ async def test_no_optimization_type_unchanged_behavior(self):+ """Without optimization_type, single image+headline uses object_story_spec (backward compat)."""+ sample_creative_data = {+ "id": "123456789",+ "name": "Simple 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="Simple Creative",+ image_hash="abc123",+ page_id="987654321",+ link_url="https://example.com",+ message="Test message",+ headline="Single Headline"+ )++ result_data = json.loads(result)+ assert result_data["success"] is True++ call_args_list = mock_api.call_args_list+ first_call = call_args_list[0]+ creative_data = first_call[0][2]++ # Should use traditional object_story_spec with link_data+ assert "object_story_spec" in creative_data+ assert "link_data" in creative_data["object_story_spec"]+ assert creative_data["object_story_spec"]["link_data"]["image_hash"] == "abc123"+ assert "asset_feed_spec" not in creative_data++ async def test_flex_creative_full_combination(self):+ """FLEX creative with all plural params: image_hashes, messages, headlines, descriptions."""+ sample_creative_data = {+ "id": "123456789",+ "name": "Full FLEX",+ "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="Full FLEX",+ image_hashes=["hash1", "hash2"],+ page_id="987654321",+ link_url="https://example.com",+ messages=["Text A", "Text B"],+ headlines=["Headline 1", "Headline 2"],+ descriptions=["Desc 1", "Desc 2"],+ optimization_type="DEGREES_OF_FREEDOM",+ call_to_action_type="SHOP_NOW"+ )++ result_data = json.loads(result)+ assert result_data["success"] is True++ call_args_list = mock_api.call_args_list+ first_call = call_args_list[0]+ creative_data = first_call[0][2]++ afs = creative_data["asset_feed_spec"]+ assert afs["optimization_type"] == "DEGREES_OF_FREEDOM"+ assert afs["images"] == [{"hash": "hash1"}, {"hash": "hash2"}]+ assert afs["bodies"] == [{"text": "Text A"}, {"text": "Text B"}]+ assert afs["titles"] == [{"text": "Headline 1"}, {"text": "Headline 2"}]+ assert afs["descriptions"] == [{"text": "Desc 1"}, {"text": "Desc 2"}]+ assert afs["call_to_action_types"] == ["SHOP_NOW"]++ async def test_image_hashes_without_optimization_type_uses_asset_feed(self):+ """image_hashes (plural) triggers asset_feed_spec even without optimization_type."""+ sample_creative_data = {+ "id": "123456789",+ "name": "Multi Image",+ "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="Multi Image",+ image_hashes=["hash1", "hash2"],+ page_id="987654321",+ link_url="https://example.com",+ message="Test message"+ )++ result_data = json.loads(result)+ assert result_data["success"] is True++ call_args_list = mock_api.call_args_list+ first_call = call_args_list[0]+ creative_data = first_call[0][2]++ assert "asset_feed_spec" in creative_data+ assert creative_data["asset_feed_spec"]["images"] == [+ {"hash": "hash1"}, {"hash": "hash2"}+ ]+ # No optimization_type should be set+ assert "optimization_type" not in creative_data["asset_feed_spec"]++ async def test_no_image_hash_or_image_hashes_returns_error(self):+ """Must provide either image_hash or image_hashes."""+ result = await create_ad_creative(+ access_token="test_token",+ account_id="act_123456789",+ name="Test",+ page_id="987654321"+ )++ result_data = json.loads(result)+ if "data" in result_data:+ error_data = json.loads(result_data["data"])+ assert "error" in error_data+ assert "image hash" in error_data["error"].lower()+ else:+ assert "error" in result_data+ assert "image hash" in result_data["error"].lower()+++class TestFlexCreativesUpdate:+ """Test cases for FLEX creative support in update_ad_creative."""++ async def test_update_with_optimization_type(self):+ """Update creative with optimization_type includes it in asset_feed_spec."""+ sample_creative_data = {+ "id": "123456789",+ "name": "Updated FLEX",+ "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",+ optimization_type="DEGREES_OF_FREEDOM",+ headlines=["New Headline"]+ )++ result_data = json.loads(result)+ assert result_data["success"] is True++ call_args_list = mock_api.call_args_list+ first_call = call_args_list[0]+ creative_data = first_call[0][2]++ assert "asset_feed_spec" in creative_data+ assert creative_data["asset_feed_spec"]["optimization_type"] == "DEGREES_OF_FREEDOM"++ async def test_update_with_messages_plural(self):+ """Update creative with messages (plural) produces correct bodies array."""+ sample_creative_data = {+ "id": "123456789",+ "name": "Updated",+ "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",+ messages=["Text A", "Text B"]+ )++ result_data = json.loads(result)+ assert result_data["success"] is True++ call_args_list = mock_api.call_args_list+ first_call = call_args_list[0]+ creative_data = first_call[0][2]++ assert "asset_feed_spec" in creative_data+ assert creative_data["asset_feed_spec"]["bodies"] == [+ {"text": "Text A"}, {"text": "Text B"}+ ]++ async def test_update_validation_cannot_mix_message_and_messages(self):+ """Cannot specify both message and messages in update."""+ result = await update_ad_creative(+ access_token="test_token",+ creative_id="123456789",+ message="Single",+ messages=["A", "B"]+ )++ result_data = json.loads(result)+ if "data" in result_data:+ error_data = json.loads(result_data["data"])+ assert "error" in error_data+ assert "Cannot specify both 'message' and 'messages'" in error_data["error"]+ else:+ assert "error" in result_data+ assert "Cannot specify both 'message' and 'messages'" in result_data["error"]++ async def test_update_validation_invalid_optimization_type(self):+ """Invalid optimization_type rejected in update."""+ result = await update_ad_creative(+ access_token="test_token",+ creative_id="123456789",+ optimization_type="BAD_VALUE"+ )++ result_data = json.loads(result)+ if "data" in result_data:+ error_data = json.loads(result_data["data"])+ assert "error" in error_data+ assert "Invalid optimization_type" in error_data["error"]+ else:+ assert "error" in result_data+ assert "Invalid optimization_type" in result_data["error"]++ async def test_update_optimization_type_alone_triggers_asset_feed(self):+ """Setting only optimization_type triggers asset_feed_spec path."""+ sample_creative_data = {+ "id": "123456789",+ "name": "FLEX",+ "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",+ optimization_type="DEGREES_OF_FREEDOM"+ )++ result_data = json.loads(result)+ assert result_data["success"] is True++ call_args_list = mock_api.call_args_list+ first_call = call_args_list[0]+ creative_data = first_call[0][2]++ assert "asset_feed_spec" in creative_data+ assert creative_data["asset_feed_spec"]["optimization_type"] == "DEGREES_OF_FREEDOM"