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.

tentative fix: update DOF creative content via ad endpoint instead of creative endpoint

Yves Junqueirac24bcb288264
diff --git a/meta_ads_mcp/core/ads.py b/meta_ads_mcp/core/ads.py
index 5145270..4ee73f2 100644
--- a/meta_ads_mcp/core/ads.py
+++ b/meta_ads_mcp/core/ads.py
@@ -1470,11 +1470,57 @@ async def create_ad_creative(
}, indent=2)
+async def _fetch_creative_details(creative_id: str, access_token: str) -> Dict[str, Any]:
+ """Fetch a creative's full details including asset_feed_spec and account_id.
+
+ Returns the API response dict with fields: id, asset_feed_spec, object_story_spec, account_id.
+ """
+ params = {
+ "fields": "id,asset_feed_spec,object_story_spec,account_id"
+ }
+ return await make_api_request(creative_id, access_token, params)
+
+
+async def _find_ads_by_creative_id(creative_id: str, access_token: str) -> List[str]:
+ """Find ad IDs that use a given creative_id.
+
+ 1. GET /{creative_id}?fields=id,account_id to get the ad account
+ 2. GET /act_{account_id}/ads?fields=id,creative{id} to list ads
+ 3. Filter for ads whose creative.id matches creative_id
+
+ Returns list of ad_id strings (may be empty).
+ """
+ # Step 1: get account_id from the creative
+ creative_info = await make_api_request(creative_id, access_token, {"fields": "id,account_id"})
+ account_id = creative_info.get("account_id")
+ if not account_id:
+ logger.warning(f"Could not determine account_id for creative {creative_id}")
+ return []
+
+ # Step 2: list ads in the account
+ ads_endpoint = f"act_{account_id}/ads" if not account_id.startswith("act_") else f"{account_id}/ads"
+ ads_response = await make_api_request(
+ ads_endpoint, access_token,
+ {"fields": "id,creative{id}", "limit": "100"}
+ )
+
+ # Step 3: filter for matching creative_id
+ ads_data = ads_response.get("data", [])
+ matching_ad_ids = []
+ for ad in ads_data:
+ ad_creative = ad.get("creative", {})
+ if ad_creative.get("id") == creative_id:
+ matching_ad_ids.append(ad["id"])
+
+ return matching_ad_ids
+
+
@mcp_server.tool()
@meta_api_tool
async def update_ad_creative(
creative_id: str,
access_token: Optional[str] = None,
+ ad_id: Optional[str] = None,
name: Optional[str] = None,
message: Optional[str] = None,
messages: Optional[List[str]] = None,
@@ -1489,27 +1535,32 @@ async def update_ad_creative(
ad_formats: Optional[List[str]] = None
) -> str:
"""
- Update an existing ad creative's name or optimization settings.
+ Update an existing ad creative's name or content.
+
+ For FLEX/DOF creatives (those with asset_feed_spec), content updates (headlines,
+ descriptions, messages) are applied by POSTing to the Ad endpoint with the merged
+ asset_feed_spec. This is the only way Meta allows updating content on DOF creatives.
- IMPORTANT — Meta API limitation: The Meta API does NOT allow updating content
- fields (message, headline, description, CTA, image, video, URL) on existing
- creatives. Only the creative `name` and optimization settings (asset_feed_spec)
- can be changed. To change ad content, create a new creative with the desired
- content and update the ad to reference the new creative via `update_ad`.
+ For non-DOF creatives, content updates will still be attempted via the Creative
+ endpoint but will likely be rejected by Meta (error_subcode 1815573).
+
+ Name-only updates always go directly to the Creative endpoint.
Args:
creative_id: Meta Ads creative ID to update
access_token: Meta API access token (optional - will use cached token if not provided)
+ ad_id: Optional ad ID to target directly. If provided, skips the ad lookup when
+ updating DOF content. Use this for efficiency when you already know the ad ID.
name: New creative name (this is the most reliable update)
- message: New ad copy/text — NOTE: Meta API may reject this on existing creatives
- messages: List of primary text variants — NOTE: Meta API may reject this on existing creatives
- headline: Single headline — NOTE: Meta API may reject this on existing creatives
- headlines: New list of headlines — NOTE: Meta API may reject this on existing creatives
- description: Single description — NOTE: Meta API may reject this on existing creatives
- descriptions: New list of descriptions — NOTE: Meta API may reject this on existing creatives
+ message: New ad copy/text (primary text)
+ messages: List of primary text variants for DOF creatives
+ headline: Single headline
+ headlines: New list of headlines for DOF creatives
+ description: Single description
+ descriptions: New list of descriptions for DOF creatives
optimization_type: Set to "DEGREES_OF_FREEDOM" for FLEX (Advantage+) creatives
dynamic_creative_spec: New dynamic creative optimization settings
- call_to_action_type: New call to action button type — NOTE: Meta API may reject this on existing creatives
+ call_to_action_type: New call to action button type
lead_gen_form_id: Lead generation form ID for lead generation campaigns
ad_formats: List of ad format strings for asset_feed_spec (e.g., ["AUTOMATIC_FORMAT"] for
Flexible ads, ["SINGLE_IMAGE"] for single image)
@@ -1551,54 +1602,145 @@ async def update_ad_creative(
if len(d) > 125:
return json.dumps({"error": f"Description {i+1} exceeds 125 character limit"}, indent=2)
- # Prepare the update data
+ # Determine if this is a content update that needs the asset_feed_spec path
+ has_content_changes = bool(headlines or descriptions or messages or headline or description or message)
+ use_asset_feed = bool(headlines or descriptions or messages or optimization_type or dynamic_creative_spec)
+
+ # --- DOF content update path: update via the Ad endpoint ---
+ # When content changes are requested AND the creative is a DOF creative,
+ # we must POST to /{ad_id} with the merged asset_feed_spec.
+ if use_asset_feed and has_content_changes:
+ try:
+ # Fetch the existing creative to check if it has asset_feed_spec
+ creative_details = await _fetch_creative_details(creative_id, access_token)
+ existing_afs = creative_details.get("asset_feed_spec")
+
+ if existing_afs:
+ # This IS a DOF creative — update via the Ad endpoint
+ # Build the merged asset_feed_spec
+ merged_afs = dict(existing_afs)
+
+ if headlines:
+ merged_afs["titles"] = [{"text": h} for h in headlines]
+ elif headline:
+ merged_afs["titles"] = [{"text": headline}]
+
+ if descriptions:
+ merged_afs["descriptions"] = [{"text": d} for d in descriptions]
+ elif description:
+ merged_afs["descriptions"] = [{"text": description}]
+
+ if messages:
+ merged_afs["bodies"] = [{"text": m} for m in messages]
+ elif message:
+ merged_afs["bodies"] = [{"text": message}]
+
+ if optimization_type:
+ merged_afs["optimization_type"] = optimization_type
+
+ if call_to_action_type:
+ merged_afs["call_to_action_types"] = [call_to_action_type]
+
+ # Find the ad(s) using this creative
+ if ad_id:
+ target_ad_ids = [ad_id]
+ else:
+ target_ad_ids = await _find_ads_by_creative_id(creative_id, access_token)
+
+ if not target_ad_ids:
+ return json.dumps({
+ "error": "No ads found using this creative",
+ "explanation": (
+ "To update content on a DOF/FLEX creative, the creative must be "
+ "attached to an ad. No ads were found referencing this creative."
+ ),
+ "suggestion": (
+ "If you know the ad ID, pass it via the ad_id parameter. "
+ "Alternatively, use update_ad directly with the ad_id and the "
+ "desired asset_feed_spec changes."
+ ),
+ "creative_id": creative_id
+ }, indent=2)
+
+ # Also handle name update if requested
+ if name:
+ try:
+ await make_api_request(creative_id, access_token, {"name": name}, method="POST")
+ except Exception as e:
+ logger.warning(f"Name update failed for creative {creative_id}: {e}")
+
+ # POST to each ad with the merged asset_feed_spec
+ updated_ads = []
+ errors = []
+ for target_ad_id in target_ad_ids:
+ ad_update_params = {
+ "creative": json.dumps({
+ "creative_id": creative_id,
+ "asset_feed_spec": merged_afs
+ })
+ }
+ try:
+ ad_result = await make_api_request(
+ target_ad_id, access_token, ad_update_params, method="POST"
+ )
+ if "error" in ad_result:
+ errors.append({"ad_id": target_ad_id, "error": ad_result["error"]})
+ else:
+ updated_ads.append(target_ad_id)
+ except Exception as e:
+ errors.append({"ad_id": target_ad_id, "error": str(e)})
+
+ result = {
+ "success": len(updated_ads) > 0,
+ "creative_id": creative_id,
+ "updated_ads": updated_ads,
+ "merged_asset_feed_spec": merged_afs,
+ "method": "ad_endpoint_update"
+ }
+ if errors:
+ result["errors"] = errors
+ return json.dumps(result, indent=2)
+
+ except Exception as e:
+ logger.exception("DOF content update path failed, falling through to direct creative update")
+ # Fall through to the legacy direct-creative-update path below
+
+ # --- Legacy path: direct Creative endpoint update ---
+ # Used for: name-only updates, non-DOF creatives, optimization_type-only changes,
+ # or when the DOF path above failed/fell through.
update_data = {}
if name:
update_data["name"] = name
- # 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_spec
asset_feed_spec = {}
# Determine ad_formats: use explicit value if provided, otherwise smart default.
- # NOTE: AUTOMATIC_FORMAT is NOT valid for creation/update — Meta silently
- # ignores the entire asset_feed_spec when it encounters it.
- # Always use SINGLE_IMAGE; Meta handles format selection automatically
- # via optimization_type=DEGREES_OF_FREEDOM.
if ad_formats:
asset_feed_spec["ad_formats"] = ad_formats
else:
asset_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_spec
- # Auto-promote singular headline to single-element array when in asset_feed_spec path
if headlines:
asset_feed_spec["titles"] = [{"text": headline_text} for headline_text in headlines]
elif headline:
asset_feed_spec["titles"] = [{"text": headline}]
- # Handle descriptions
- # Auto-promote singular description to single-element array when in asset_feed_spec path
if descriptions:
asset_feed_spec["descriptions"] = [{"text": description_text} for description_text in descriptions]
elif description:
asset_feed_spec["descriptions"] = [{"text": description}]
- # 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 provided
if call_to_action_type:
asset_feed_spec["call_to_action_types"] = [call_to_action_type]
@@ -1607,50 +1749,41 @@ async def update_ad_creative(
# Use traditional object_story_spec with link_data for simple creatives
if message or headline or description or call_to_action_type or lead_gen_form_id:
update_data["object_story_spec"] = {"link_data": {}}
-
+
if message:
update_data["object_story_spec"]["link_data"]["message"] = message
-
- # Add headline (singular) to link_data
+
if headline:
update_data["object_story_spec"]["link_data"]["name"] = headline
-
- # Add description (singular) to link_data
+
if description:
update_data["object_story_spec"]["link_data"]["description"] = description
-
- # Add call_to_action to link_data for simple creatives
+
if call_to_action_type or lead_gen_form_id:
cta_data = {}
if 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}
-
+
if cta_data:
update_data["object_story_spec"]["link_data"]["call_to_action"] = cta_data
-
- # Add dynamic creative spec if provided
+
if dynamic_creative_spec:
update_data["dynamic_creative_spec"] = dynamic_creative_spec
-
- # 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)
+ creative_details = await make_api_request(creative_id, access_token, creative_params)
return json.dumps({
"success": True,
"creative_id": creative_id,
diff --git a/tests/test_ad_formats_flexible.py b/tests/test_ad_formats_flexible.py
index 87441be..acd7d4c 100644
--- a/tests/test_ad_formats_flexible.py
+++ b/tests/test_ad_formats_flexible.py
@@ -174,17 +174,31 @@ class TestAdFormatsDefaultCreate:
@pytest.mark.asyncio
class TestAdFormatsDefaultUpdate:
- """Test ad_formats defaults in update_ad_creative."""
-
- async def test_update_dof_defaults_to_single_image(self):
- """update_ad_creative with DEGREES_OF_FREEDOM defaults to SINGLE_IMAGE.
+ """Test ad_formats handling in update_ad_creative.
+
+ With DOF content updates going through the ad endpoint, these tests verify
+ that the existing ad_formats in the creative's asset_feed_spec are preserved
+ or that the legacy path defaults correctly for non-DOF creatives.
+ """
+
+ async def test_update_dof_preserves_existing_ad_formats(self):
+ """DOF creative update preserves existing ad_formats from asset_feed_spec."""
+ existing_creative = {
+ "id": "123456789",
+ "asset_feed_spec": {
+ "titles": [{"text": "Old"}],
+ "images": [{"hash": "abc"}],
+ "ad_formats": ["SINGLE_IMAGE"],
+ "optimization_type": "DEGREES_OF_FREEDOM"
+ }
+ }
- AUTOMATIC_FORMAT is NOT valid — Meta silently ignores asset_feed_spec.
- """
- sample_data = {"id": "123", "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_data
+ with patch('meta_ads_mcp.core.ads._fetch_creative_details', new_callable=AsyncMock) as mock_fetch, \
+ patch('meta_ads_mcp.core.ads._find_ads_by_creative_id', new_callable=AsyncMock) as mock_find, \
+ patch('meta_ads_mcp.core.ads.make_api_request', new_callable=AsyncMock) as mock_api:
+ mock_fetch.return_value = existing_creative
+ mock_find.return_value = ["ad_999"]
+ mock_api.return_value = {"success": True}
result = await update_ad_creative(
access_token="test_token",
@@ -195,16 +209,20 @@ class TestAdFormatsDefaultUpdate:
result_data = json.loads(result)
assert result_data["success"] is True
-
- creative_data = mock_api.call_args_list[0][0][2]
- afs = creative_data["asset_feed_spec"]
- assert afs["ad_formats"] == ["SINGLE_IMAGE"]
-
- async def test_update_without_dof_defaults_to_single_image(self):
- """update_ad_creative without DEGREES_OF_FREEDOM defaults to SINGLE_IMAGE."""
+ merged = result_data["merged_asset_feed_spec"]
+ assert merged["ad_formats"] == ["SINGLE_IMAGE"]
+
+ async def test_update_non_dof_creative_defaults_to_single_image(self):
+ """Non-DOF creative (no asset_feed_spec) falls to legacy path with SINGLE_IMAGE default."""
+ existing_creative = {
+ "id": "123456789",
+ "object_story_spec": {"link_data": {"message": "Old"}}
+ }
sample_data = {"id": "123", "name": "Updated", "status": "ACTIVE"}
- with patch('meta_ads_mcp.core.ads.make_api_request', new_callable=AsyncMock) as mock_api:
+ with patch('meta_ads_mcp.core.ads._fetch_creative_details', new_callable=AsyncMock) as mock_fetch, \
+ patch('meta_ads_mcp.core.ads.make_api_request', new_callable=AsyncMock) as mock_api:
+ mock_fetch.return_value = existing_creative
mock_api.return_value = sample_data
result = await update_ad_creative(
@@ -216,31 +234,43 @@ class TestAdFormatsDefaultUpdate:
result_data = json.loads(result)
assert result_data["success"] is True
+ # Legacy path: make_api_request called with asset_feed_spec on the creative endpoint
creative_data = mock_api.call_args_list[0][0][2]
afs = creative_data["asset_feed_spec"]
assert afs["ad_formats"] == ["SINGLE_IMAGE"]
- async def test_update_explicit_ad_formats_overrides(self):
- """update_ad_creative with explicit ad_formats overrides default."""
- sample_data = {"id": "123", "name": "Updated", "status": "ACTIVE"}
+ async def test_update_dof_explicit_ad_formats_not_needed(self):
+ """DOF creative update merges from existing spec, ad_formats param not used in DOF path."""
+ existing_creative = {
+ "id": "123456789",
+ "asset_feed_spec": {
+ "titles": [{"text": "Old"}],
+ "images": [{"hash": "abc"}],
+ "ad_formats": ["SINGLE_IMAGE"],
+ "optimization_type": "DEGREES_OF_FREEDOM"
+ }
+ }
- with patch('meta_ads_mcp.core.ads.make_api_request', new_callable=AsyncMock) as mock_api:
- mock_api.return_value = sample_data
+ with patch('meta_ads_mcp.core.ads._fetch_creative_details', new_callable=AsyncMock) as mock_fetch, \
+ patch('meta_ads_mcp.core.ads._find_ads_by_creative_id', new_callable=AsyncMock) as mock_find, \
+ patch('meta_ads_mcp.core.ads.make_api_request', new_callable=AsyncMock) as mock_api:
+ mock_fetch.return_value = existing_creative
+ mock_find.return_value = ["ad_999"]
+ mock_api.return_value = {"success": True}
result = await update_ad_creative(
access_token="test_token",
creative_id="123456789",
optimization_type="DEGREES_OF_FREEDOM",
headlines=["New Headline"],
- ad_formats=["SINGLE_IMAGE"] # explicit override
+ ad_formats=["SINGLE_IMAGE"]
)
result_data = json.loads(result)
assert result_data["success"] is True
-
- creative_data = mock_api.call_args_list[0][0][2]
- afs = creative_data["asset_feed_spec"]
- assert afs["ad_formats"] == ["SINGLE_IMAGE"]
+ merged = result_data["merged_asset_feed_spec"]
+ # ad_formats comes from existing spec (merged), not from the parameter
+ assert merged["ad_formats"] == ["SINGLE_IMAGE"]
@pytest.mark.asyncio
diff --git a/tests/test_dynamic_creatives.py b/tests/test_dynamic_creatives.py
index 10d87b0..9325ee1 100644
--- a/tests/test_dynamic_creatives.py
+++ b/tests/test_dynamic_creatives.py
@@ -390,77 +390,71 @@ class TestDynamicCreatives:
async def test_update_ad_creative_add_headlines(self):
- """Test updating an existing creative to add multiple headlines."""
-
- sample_creative_data = {
+ """Test updating an existing DOF creative to add multiple headlines via ad endpoint."""
+ existing_creative = {
"id": "123456789",
- "name": "Updated Creative",
- "status": "ACTIVE"
+ "asset_feed_spec": {
+ "titles": [{"text": "Old"}],
+ "bodies": [{"text": "Body"}],
+ "images": [{"hash": "abc"}],
+ "ad_formats": ["SINGLE_IMAGE"]
+ }
}
-
- with patch('meta_ads_mcp.core.ads.make_api_request', new_callable=AsyncMock) as mock_api:
- mock_api.return_value = sample_creative_data
-
+
+ with patch('meta_ads_mcp.core.ads._fetch_creative_details', new_callable=AsyncMock) as mock_fetch, \
+ patch('meta_ads_mcp.core.ads._find_ads_by_creative_id', new_callable=AsyncMock) as mock_find, \
+ patch('meta_ads_mcp.core.ads.make_api_request', new_callable=AsyncMock) as mock_api:
+ mock_fetch.return_value = existing_creative
+ mock_find.return_value = ["ad_999"]
+ mock_api.return_value = {"success": True}
+
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 "titles" in creative_data["asset_feed_spec"]
- assert creative_data["asset_feed_spec"]["titles"] == [
- {"text": "New Headline 1"},
- {"text": "New Headline 2"},
+
+ merged = result_data["merged_asset_feed_spec"]
+ assert merged["titles"] == [
+ {"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 = {
+ """Test updating an existing DOF creative to add multiple descriptions via ad endpoint."""
+ existing_creative = {
"id": "123456789",
- "name": "Updated Creative",
- "status": "ACTIVE"
+ "asset_feed_spec": {
+ "titles": [{"text": "Headline"}],
+ "descriptions": [{"text": "Old"}],
+ "images": [{"hash": "abc"}],
+ "ad_formats": ["SINGLE_IMAGE"]
+ }
}
-
- with patch('meta_ads_mcp.core.ads.make_api_request', new_callable=AsyncMock) as mock_api:
- mock_api.return_value = sample_creative_data
-
+
+ with patch('meta_ads_mcp.core.ads._fetch_creative_details', new_callable=AsyncMock) as mock_fetch, \
+ patch('meta_ads_mcp.core.ads._find_ads_by_creative_id', new_callable=AsyncMock) as mock_find, \
+ patch('meta_ads_mcp.core.ads.make_api_request', new_callable=AsyncMock) as mock_api:
+ mock_fetch.return_value = existing_creative
+ mock_find.return_value = ["ad_999"]
+ mock_api.return_value = {"success": True}
+
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"},
+
+ merged = result_data["merged_asset_feed_spec"]
+ assert merged["descriptions"] == [
+ {"text": "New Description 1"},
{"text": "New Description 2"}
]
@@ -715,37 +709,36 @@ class TestDynamicCreatives:
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 = {
+ """Test updating call_to_action_type with dynamic creative content via ad endpoint."""
+ existing_creative = {
"id": "123456789",
- "name": "Test Creative",
- "status": "ACTIVE"
+ "asset_feed_spec": {
+ "titles": [{"text": "Old"}],
+ "images": [{"hash": "abc"}],
+ "ad_formats": ["SINGLE_IMAGE"]
+ }
}
-
- with patch('meta_ads_mcp.core.ads.make_api_request', new_callable=AsyncMock) as mock_api:
- mock_api.return_value = sample_creative_data
-
+
+ with patch('meta_ads_mcp.core.ads._fetch_creative_details', new_callable=AsyncMock) as mock_fetch, \
+ patch('meta_ads_mcp.core.ads._find_ads_by_creative_id', new_callable=AsyncMock) as mock_find, \
+ patch('meta_ads_mcp.core.ads.make_api_request', new_callable=AsyncMock) as mock_api:
+ mock_fetch.return_value = existing_creative
+ mock_find.return_value = ["ad_999"]
+ mock_api.return_value = {"success": True}
+
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"]
+
+ merged = result_data["merged_asset_feed_spec"]
+ assert merged["call_to_action_types"] == ["SHOP_NOW"]
+ assert merged["titles"] == [{"text": "Test Headline"}]
async def test_update_ad_creative_cta_without_dynamic_content(self):
"""Test updating call_to_action_type without dynamic creative content."""
@@ -780,17 +773,26 @@ class TestDynamicCreatives:
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 = {
+ """Test updating multiple parameters at once via DOF ad endpoint path."""
+ existing_creative = {
"id": "123456789",
- "name": "Multi-Updated Creative",
- "status": "ACTIVE"
+ "asset_feed_spec": {
+ "titles": [{"text": "Old"}],
+ "bodies": [{"text": "Old body"}],
+ "descriptions": [{"text": "Old desc"}],
+ "images": [{"hash": "abc"}],
+ "ad_formats": ["SINGLE_IMAGE"]
+ }
}
-
- with patch('meta_ads_mcp.core.ads.make_api_request', new_callable=AsyncMock) as mock_api:
- mock_api.return_value = sample_creative_data
-
+
+ with patch('meta_ads_mcp.core.ads._fetch_creative_details', new_callable=AsyncMock) as mock_fetch, \
+ patch('meta_ads_mcp.core.ads._find_ads_by_creative_id', new_callable=AsyncMock) as mock_find, \
+ patch('meta_ads_mcp.core.ads.make_api_request', new_callable=AsyncMock) as mock_api:
+ mock_fetch.return_value = existing_creative
+ mock_find.return_value = ["ad_999"]
+ # First call: name update on creative, second call: ad update
+ mock_api.return_value = {"success": True}
+
result = await update_ad_creative(
access_token="test_token",
creative_id="123456789",
@@ -800,38 +802,19 @@ class TestDynamicCreatives:
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 "titles" in creative_data["asset_feed_spec"]
- assert "descriptions" in creative_data["asset_feed_spec"]
- assert "bodies" 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"]["titles"] == [
+
+ merged = result_data["merged_asset_feed_spec"]
+ assert merged["titles"] == [
{"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"]["bodies"] == [
- {"text": "Updated message"}
- ]
- assert creative_data["asset_feed_spec"]["call_to_action_types"] == ["SIGN_UP"]
+ assert merged["descriptions"] == [{"text": "New Description 1"}]
+ assert merged["bodies"] == [{"text": "Updated message"}]
+ assert merged["call_to_action_types"] == ["SIGN_UP"]
+ # Existing images preserved
+ assert merged["images"] == [{"hash": "abc"}]
async def test_update_ad_creative_api_error_handling(self):
"""Test error handling when API request fails."""
diff --git a/tests/test_flex_creatives.py b/tests/test_flex_creatives.py
index 7bc546d..84e0bb8 100644
--- a/tests/test_flex_creatives.py
+++ b/tests/test_flex_creatives.py
@@ -399,16 +399,25 @@ class TestFlexCreatives:
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 = {
+ async def test_update_dof_creative_with_headlines_via_ad_endpoint(self):
+ """DOF creative with headlines update goes through ad endpoint with merged spec."""
+ existing_creative = {
"id": "123456789",
- "name": "Updated FLEX",
- "status": "ACTIVE"
+ "asset_feed_spec": {
+ "titles": [{"text": "Old Headline"}],
+ "bodies": [{"text": "Old body"}],
+ "images": [{"hash": "abc123"}],
+ "optimization_type": "DEGREES_OF_FREEDOM",
+ "ad_formats": ["SINGLE_IMAGE"]
+ }
}
- with patch('meta_ads_mcp.core.ads.make_api_request', new_callable=AsyncMock) as mock_api:
- mock_api.return_value = sample_creative_data
+ with patch('meta_ads_mcp.core.ads._fetch_creative_details', new_callable=AsyncMock) as mock_fetch, \
+ patch('meta_ads_mcp.core.ads._find_ads_by_creative_id', new_callable=AsyncMock) as mock_find, \
+ patch('meta_ads_mcp.core.ads.make_api_request', new_callable=AsyncMock) as mock_api:
+ mock_fetch.return_value = existing_creative
+ mock_find.return_value = ["ad_999"]
+ mock_api.return_value = {"success": True}
result = await update_ad_creative(
access_token="test_token",
@@ -419,42 +428,147 @@ class TestFlexCreativesUpdate:
result_data = json.loads(result)
assert result_data["success"] is True
+ assert result_data["method"] == "ad_endpoint_update"
+ assert "ad_999" in result_data["updated_ads"]
+
+ merged = result_data["merged_asset_feed_spec"]
+ assert merged["titles"] == [{"text": "New Headline"}]
+ assert merged["optimization_type"] == "DEGREES_OF_FREEDOM"
+ # Existing fields preserved
+ assert merged["bodies"] == [{"text": "Old body"}]
+ assert merged["images"] == [{"hash": "abc123"}]
+
+ async def test_update_dof_creative_with_messages_via_ad_endpoint(self):
+ """DOF creative with messages update merges correctly."""
+ existing_creative = {
+ "id": "123456789",
+ "asset_feed_spec": {
+ "titles": [{"text": "Headline"}],
+ "bodies": [{"text": "Old body"}],
+ "images": [{"hash": "abc123"}],
+ "ad_formats": ["SINGLE_IMAGE"]
+ }
+ }
- call_args_list = mock_api.call_args_list
- first_call = call_args_list[0]
- creative_data = first_call[0][2]
+ with patch('meta_ads_mcp.core.ads._fetch_creative_details', new_callable=AsyncMock) as mock_fetch, \
+ patch('meta_ads_mcp.core.ads._find_ads_by_creative_id', new_callable=AsyncMock) as mock_find, \
+ patch('meta_ads_mcp.core.ads.make_api_request', new_callable=AsyncMock) as mock_api:
+ mock_fetch.return_value = existing_creative
+ mock_find.return_value = ["ad_999"]
+ mock_api.return_value = {"success": True}
- assert "asset_feed_spec" in creative_data
- assert creative_data["asset_feed_spec"]["optimization_type"] == "DEGREES_OF_FREEDOM"
+ result = await update_ad_creative(
+ access_token="test_token",
+ creative_id="123456789",
+ messages=["Text A", "Text B"]
+ )
- async def test_update_with_messages_plural(self):
- """Update creative with messages (plural) produces correct bodies array."""
- sample_creative_data = {
+ result_data = json.loads(result)
+ assert result_data["success"] is True
+
+ merged = result_data["merged_asset_feed_spec"]
+ assert merged["bodies"] == [{"text": "Text A"}, {"text": "Text B"}]
+ # Existing fields preserved
+ assert merged["titles"] == [{"text": "Headline"}]
+
+ async def test_update_dof_creative_with_ad_id_skips_lookup(self):
+ """When ad_id is provided, skip the ad lookup for efficiency."""
+ existing_creative = {
"id": "123456789",
- "name": "Updated",
- "status": "ACTIVE"
+ "asset_feed_spec": {
+ "titles": [{"text": "Old"}],
+ "bodies": [{"text": "Old body"}],
+ "images": [{"hash": "abc123"}],
+ "ad_formats": ["SINGLE_IMAGE"]
+ }
}
- with patch('meta_ads_mcp.core.ads.make_api_request', new_callable=AsyncMock) as mock_api:
- mock_api.return_value = sample_creative_data
+ with patch('meta_ads_mcp.core.ads._fetch_creative_details', new_callable=AsyncMock) as mock_fetch, \
+ patch('meta_ads_mcp.core.ads._find_ads_by_creative_id', new_callable=AsyncMock) as mock_find, \
+ patch('meta_ads_mcp.core.ads.make_api_request', new_callable=AsyncMock) as mock_api:
+ mock_fetch.return_value = existing_creative
+ mock_api.return_value = {"success": True}
result = await update_ad_creative(
access_token="test_token",
creative_id="123456789",
- messages=["Text A", "Text B"]
+ ad_id="ad_direct_456",
+ headlines=["Direct Headline"]
)
result_data = json.loads(result)
assert result_data["success"] is True
+ assert "ad_direct_456" in result_data["updated_ads"]
+ # _find_ads_by_creative_id should NOT have been called
+ mock_find.assert_not_called()
- call_args_list = mock_api.call_args_list
- first_call = call_args_list[0]
- creative_data = first_call[0][2]
+ async def test_update_dof_creative_no_ads_found_returns_error(self):
+ """When no ads use this creative, return helpful error."""
+ existing_creative = {
+ "id": "123456789",
+ "asset_feed_spec": {
+ "titles": [{"text": "Old"}],
+ "ad_formats": ["SINGLE_IMAGE"]
+ }
+ }
- assert "asset_feed_spec" in creative_data
- assert creative_data["asset_feed_spec"]["bodies"] == [
- {"text": "Text A"}, {"text": "Text B"}
- ]
+ with patch('meta_ads_mcp.core.ads._fetch_creative_details', new_callable=AsyncMock) as mock_fetch, \
+ patch('meta_ads_mcp.core.ads._find_ads_by_creative_id', new_callable=AsyncMock) as mock_find:
+ mock_fetch.return_value = existing_creative
+ mock_find.return_value = []
+
+ result = await update_ad_creative(
+ access_token="test_token",
+ creative_id="123456789",
+ headlines=["New Headline"]
+ )
+
+ result_data = json.loads(result)
+ if "data" in result_data:
+ result_data = json.loads(result_data["data"])
+ assert "error" in result_data
+ assert "No ads found" in result_data["error"]
+ assert "ad_id" in result_data.get("suggestion", "")
+
+ async def test_update_non_dof_creative_falls_through_to_legacy(self):
+ """Non-DOF creative (no asset_feed_spec) falls through to legacy path."""
+ # Creative without asset_feed_spec
+ existing_creative = {
+ "id": "123456789",
+ "object_story_spec": {"link_data": {"message": "Old"}}
+ }
+
+ api_error = {
+ "error": {
+ "message": "HTTP Error: 400",
+ "details": {
+ "error": {
+ "message": "(#100) The parameter is not supported",
+ "type": "OAuthException",
+ "code": 100,
+ "error_subcode": 1815573,
+ }
+ },
+ "full_response": {"status_code": 400}
+ }
+ }
+
+ with patch('meta_ads_mcp.core.ads._fetch_creative_details', new_callable=AsyncMock) as mock_fetch, \
+ patch('meta_ads_mcp.core.ads.make_api_request', new_callable=AsyncMock) as mock_api:
+ mock_fetch.return_value = existing_creative
+ mock_api.return_value = api_error
+
+ result = await update_ad_creative(
+ access_token="test_token",
+ creative_id="123456789",
+ headlines=["New Headline"]
+ )
+
+ result_data = json.loads(result)
+ if "data" in result_data:
+ result_data = json.loads(result_data["data"])
+ assert result_data["error"] == "Content updates are not allowed on existing creatives"
+ assert "workaround" in result_data
async def test_update_validation_cannot_mix_message_and_messages(self):
"""Cannot specify both message and messages in update."""
@@ -492,7 +606,7 @@ class TestFlexCreativesUpdate:
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."""
+ """Setting only optimization_type (no content changes) uses legacy creative endpoint."""
sample_creative_data = {
"id": "123456789",
"name": "FLEX",
@@ -634,15 +748,23 @@ class TestSingularParamPromotion:
}
async def test_update_singular_headline_promoted_with_optimization_type(self):
- """Singular headline promoted in update_ad_creative when optimization_type is set."""
- sample_creative_data = {
+ """Singular headline promoted in update_ad_creative when optimization_type is set (DOF path)."""
+ existing_creative = {
"id": "123456789",
- "name": "Updated",
- "status": "ACTIVE"
+ "asset_feed_spec": {
+ "titles": [{"text": "Old Headline"}],
+ "bodies": [{"text": "Body"}],
+ "images": [{"hash": "abc123"}],
+ "ad_formats": ["SINGLE_IMAGE"]
+ }
}
- with patch('meta_ads_mcp.core.ads.make_api_request', new_callable=AsyncMock) as mock_api:
- mock_api.return_value = sample_creative_data
+ with patch('meta_ads_mcp.core.ads._fetch_creative_details', new_callable=AsyncMock) as mock_fetch, \
+ patch('meta_ads_mcp.core.ads._find_ads_by_creative_id', new_callable=AsyncMock) as mock_find, \
+ patch('meta_ads_mcp.core.ads.make_api_request', new_callable=AsyncMock) as mock_api:
+ mock_fetch.return_value = existing_creative
+ mock_find.return_value = ["ad_999"]
+ mock_api.return_value = {"success": True}
result = await update_ad_creative(
access_token="test_token",
@@ -653,10 +775,6 @@ class TestSingularParamPromotion:
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"]["titles"] == [{"text": "Updated Headline"}]
+ merged = result_data["merged_asset_feed_spec"]
+ assert merged["titles"] == [{"text": "Updated Headline"}]
+ assert merged["optimization_type"] == "DEGREES_OF_FREEDOM"