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
fix(create_ad_creative): single video + IG actor -> object_story_spec for CTWA (#119)
Yves Junqueira18769152438a
diff --git a/meta_ads_mcp/__init__.py b/meta_ads_mcp/__init__.pyindex 85bec76..67bf161 100644--- a/meta_ads_mcp/__init__.py+++ b/meta_ads_mcp/__init__.py@@ -6,7 +6,7 @@ This package provides a Meta Ads MCP integrationfrom meta_ads_mcp.core.server import main-__version__ = "1.0.87"+__version__ = "1.0.104"__all__ = ['get_ad_accounts',diff --git a/meta_ads_mcp/core/ads.py b/meta_ads_mcp/core/ads.pyindex eda3302..a342461 100644--- a/meta_ads_mcp/core/ads.py+++ b/meta_ads_mcp/core/ads.py@@ -2066,18 +2066,51 @@ async def create_ad_creative(# 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), OR- # - asset_customization_rules requires asset_feed_spec, OR- # - video_id + description: Meta's video_data rejects "description" directly,- # so route through asset_feed_spec which supports descriptions for video ads- # - video_id + instagram_actor_id: Meta requires ad_formats=["SINGLE_VIDEO"] in- # asset_feed_spec alongside instagram_user_id in object_story_spec — error 1443048- # ("object_story_spec ill formed") occurs when asset_feed_spec is absent. Routing- # through asset_feed_spec ensures ad_formats is automatically included.+ # - optimization_type is set to one of the dynamic-creative modes+ # (DEGREES_OF_FREEDOM, PLACEMENT, ASSET_CUSTOMIZATION, LANGUAGE), OR+ # - asset_customization_rules requires asset_feed_spec.+ #+ # NOTE: `optimization_type="REGULAR"` is a Meta-documented asset_feed_spec+ # value meaning "no extra optimization on top of the spec", but callers+ # also use it as a signal that they do NOT want a dynamic creative. With+ # only single-variant inputs (one message, one headline, one video) the+ # caller's intent is the plain `object_story_spec.video_data` shape, so+ # we treat REGULAR as a no-op for routing and let the simple path render+ # the creative. The value is dropped on the wire (we never send+ # asset_feed_spec.optimization_type=REGULAR for a single-video creative).+ #+ # We do NOT route a single video + instagram_actor_id through asset_feed_spec.+ # Per Meta's docs the canonical shape for a video creative with an Instagram+ # identity is `object_story_spec.video_data` + `instagram_user_id` sibling, no+ # asset_feed_spec. Routing every single-video creative through asset_feed_spec+ # silently produces a "dynamic creative" that CTWA campaigns (OUTCOME_SALES /+ # OUTCOME_ENGAGEMENT with destination=WHATSAPP) reject with+ # `error_subcode 1885392` ("O objetivo da campanha nao e aceito pelo criativo+ # dinamico"). The single-video path keeps the creative regular so it serves in+ # CTWA, lead-gen, traffic, and engagement campaigns alike.+ #+ # `description` is also no longer a routing trigger. Meta's `video_data` schema+ # does not carry a `description` field for a single-video creative, so when a+ # caller passes `description` alongside a single video we drop it and surface a+ # warning in the response (the caller's intent — video + IG + WhatsApp CTA — is+ # what matters, not an unrenderable field). To attach descriptions to a video+ # creative, pass `descriptions=[...]` (plural) or `optimization_type` to opt+ # explicitly into the dynamic-creative path.+ #+ # Normalize REGULAR -> None so the rest of the function does not echo it+ # into asset_feed_spec.optimization_type when asset_feed_spec is built for+ # another reason (e.g. plural params).+ if optimization_type == "REGULAR":+ optimization_type = Noneuse_asset_feed = bool(headlines or descriptions or messages or image_hashes or videos or images- or optimization_type or asset_customization_rules or (video_id and description)- or (video_id and instagram_actor_id)+ or optimization_type or asset_customization_rules+ )++ # Track whether `description` was provided but cannot be rendered in the+ # simple video_data path so we can warn the caller after the API call.+ single_video_description_dropped = bool(+ video_id and description and not use_asset_feed)# Track if this is a video creative@@ -2414,16 +2447,27 @@ async def create_ad_creative(# Build call_to_action with the destination URL.# For video creatives, link_url MUST go in call_to_action.value.link# (not as a top-level field in video_data).- cta_value = {}- if link_url:- cta_value["link"] = link_url- if lead_gen_form_id:- cta_value["lead_gen_form_id"] = lead_gen_form_id- if phone_number:- # CALL_NOW: Meta v24 supports only- # call_to_action.value.link = "tel:+<E.164 number>".- cta_value["link"] = f"tel:{phone_number}"cta_type = call_to_action_type or ("LEARN_MORE" if link_url else None)+ cta_value = {}+ if cta_type == "WHATSAPP_MESSAGE":+ # Click-to-WhatsApp: Meta derives the destination from the+ # Page's linked WhatsApp number, so the CTA carries no value.+ # Passing ANY extra parameter here (callers commonly send a+ # wa.me URL via link_url) makes Meta v24 reject the creative+ # with code 105 / error_subcode 1815630 ("Too many parameters+ # in Call To Action — Please remove parameter 'link' from the+ # value of WHATSAPP_MESSAGE call to action type"). The correct+ # shape is just {"type": "WHATSAPP_MESSAGE"} with no value.+ pass+ else:+ if link_url:+ cta_value["link"] = link_url+ if lead_gen_form_id:+ cta_value["lead_gen_form_id"] = lead_gen_form_id+ if phone_number:+ # CALL_NOW: Meta v24 supports only+ # call_to_action.value.link = "tel:+<E.164 number>".+ cta_value["link"] = f"tel:{phone_number}"if cta_type:cta_data = {"type": cta_type}if cta_value:@@ -2626,6 +2670,16 @@ async def create_ad_creative("is_dynamic_creative=true, or use image_crops on a single ""image_hash for per-placement cropping.")+ if single_video_description_dropped:+ warnings_.append(+ "`description` was dropped because Meta's video_data schema does "+ "not carry a description field for a single-video creative. The "+ "creative was created with message + headline only. To attach a "+ "description to a video creative, pass `descriptions=[...]` "+ "(plural) or `optimization_type` — both route through "+ "asset_feed_spec, which is incompatible with CTWA campaigns "+ "(OUTCOME_SALES/OUTCOME_ENGAGEMENT with destination=WHATSAPP)."+ )if warnings_:result["warning"] = warnings_[0] if len(warnings_) == 1 else warnings_return json.dumps(result, indent=2)diff --git a/pyproject.toml b/pyproject.tomlindex 2ac7d40..c7a4557 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -4,7 +4,7 @@ build-backend = "hatchling.build"[project]name = "meta-ads-mcp"-version = "1.0.103"+version = "1.0.104"description = "Model Context Protocol (MCP) server for Meta Ads - Use Remote MCP at pipeboard.co for easiest setup"readme = "README.md"requires-python = ">=3.10"diff --git a/server.json b/server.jsonindex 8a8cd8f..b55b383 100644--- a/server.json+++ b/server.json@@ -2,7 +2,7 @@"$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json","name": "co.pipeboard/meta-ads-mcp","description": "Facebook / Meta Ads automation with AI: analyze performance, test creatives, optimize spend.",- "version": "1.0.103",+ "version": "1.0.104","remotes": [{"type": "streamable-http",diff --git a/tests/test_video_creatives.py b/tests/test_video_creatives.pyindex 57af089..8a37c30 100644--- a/tests/test_video_creatives.py+++ b/tests/test_video_creatives.py@@ -120,12 +120,13 @@ async def test_video_creative_with_thumbnail():@pytest.mark.asyncioasync def test_video_creative_with_instagram_actor_id():- """Test that video_id + instagram_actor_id routes through asset_feed_spec.+ """video_id + instagram_actor_id (no plural params) must route through the simple+ object_story_spec.video_data path so the creative is NOT a dynamic creative.- Meta returns error 1443048 ("object_story_spec ill formed") when instagram_user_id is- in object_story_spec but ad_formats=["SINGLE_VIDEO"] is absent from asset_feed_spec.- The fix: video_id + instagram_actor_id always triggers asset_feed_spec so that- ad_formats=["SINGLE_VIDEO"] is automatically included in the API call.+ CTWA campaigns (OUTCOME_SALES / OUTCOME_ENGAGEMENT with destination=WHATSAPP)+ reject dynamic creatives with error_subcode 1885392 ("O objetivo da campanha+ nao e aceito pelo criativo dinamico"). The canonical shape per Meta docs is+ `object_story_spec.video_data` + `instagram_user_id` as a sibling of video_data."""with patch('meta_ads_mcp.core.ads.make_api_request') as mock_api, \@@ -154,27 +155,83 @@ async def test_video_creative_with_instagram_actor_id():creative_data = mock_api.call_args_list[1][0][2]- # Must use asset_feed_spec path (not simple video_data-only path) so that- # ad_formats=["SINGLE_VIDEO"] is present alongside instagram_user_id.- assert "asset_feed_spec" in creative_data, (- "video_id + instagram_actor_id must route through asset_feed_spec "- "to include ad_formats — otherwise Meta returns error 1443048"+ # Must NOT use asset_feed_spec — that would make the creative a dynamic+ # creative and CTWA campaigns reject those.+ assert "asset_feed_spec" not in creative_data, (+ "video_id + instagram_actor_id must NOT route through asset_feed_spec; "+ "CTWA campaigns reject dynamic creatives (error_subcode 1885392)")- afs = creative_data["asset_feed_spec"]- assert afs["ad_formats"] == ["SINGLE_VIDEO"], (- "ad_formats must be SINGLE_VIDEO for video creatives with instagram_actor_id"- )- assert "videos" in afs- assert afs["videos"][0]["video_id"] == "vid_333444"- # PR-C: video metadata moved from object_story_spec.video_data to asset_feed_spec.- # instagram_user_id stays in object_story_spec (instagram_actor_id deprecated Jan 2026).assert "object_story_spec" in creative_dataoss = creative_data["object_story_spec"]- assert "video_data" not in oss- assert "link_data" not in oss+ assert oss["page_id"] == "123456789"+ # Meta deprecated instagram_actor_id in Jan 2026; we map it to instagram_user_id+ # inside object_story_spec (sibling of video_data).+ assert oss["instagram_user_id"] == "ig_555666"assert "instagram_actor_id" not in oss- assert oss == {"page_id": "123456789", "instagram_user_id": "ig_555666"}+ # video_data carries the video and its thumbnail.+ assert "video_data" in oss+ video_data = oss["video_data"]+ assert video_data["video_id"] == "vid_333444"+ assert video_data["image_url"] == "https://example.com/auto-thumb.jpg"+ # link_url is conveyed through call_to_action.value.link in video_data.+ assert "link_data" not in oss+++async def test_video_creative_with_instagram_actor_id_and_ctwa_cta():+ """Regression for the CTWA video bug: video_id + instagram_actor_id ++ WHATSAPP_MESSAGE CTA + disable_all_enhancements + optimization_type=REGULAR+ must NOT produce a dynamic creative, AND the WHATSAPP_MESSAGE CTA must NOT+ carry a value (no link). Meta v24 rejects any parameter in the+ WHATSAPP_MESSAGE call_to_action value with error_subcode 1815630."""++ with patch('meta_ads_mcp.core.ads.make_api_request') as mock_api, \+ patch('meta_ads_mcp.core.ads._discover_pages_for_account') as mock_discover:++ mock_discover.return_value = {+ "success": True,+ "page_id": "123456789",+ "page_name": "Test Page"+ }++ mock_api.side_effect = [+ {"picture": "https://example.com/auto-thumb.jpg"},+ {"id": "creative_ctwa_1"},+ {"id": "creative_ctwa_1", "name": "CTWA Video", "status": "ACTIVE"}+ ]++ result = await create_ad_creative(+ account_id="act_123456789",+ video_id="vid_ctwa_1",+ name="CTWA Video Creative",+ link_url="https://wa.me/15551234567",+ message="Message us on WhatsApp",+ headline="Contact us",+ instagram_actor_id="ig_ctwa_1",+ call_to_action_type="WHATSAPP_MESSAGE",+ disable_all_enhancements=True,+ access_token="test_token"+ )++ creative_data = mock_api.call_args_list[1][0][2]++ # The crux of the fix.+ assert "asset_feed_spec" not in creative_data+ oss = creative_data["object_story_spec"]+ assert oss["page_id"] == "123456789"+ assert oss["instagram_user_id"] == "ig_ctwa_1"+ assert oss["video_data"]["video_id"] == "vid_ctwa_1"+ assert oss["video_data"]["title"] == "Contact us"+ assert oss["video_data"]["message"] == "Message us on WhatsApp"+ assert oss["video_data"]["call_to_action"]["type"] == "WHATSAPP_MESSAGE"+ # WHATSAPP_MESSAGE must NOT carry a value — link_url is intentionally+ # dropped here. Meta derives the WhatsApp destination from the Page and+ # rejects any extra CTA parameter with error_subcode 1815630.+ assert "value" not in oss["video_data"]["call_to_action"]+ # disable_all_enhancements still adds the opt-out spec at the top level.+ assert "degrees_of_freedom_spec" in creative_data+ assert creative_data["degrees_of_freedom_spec"]["creative_features_spec"]@pytest.mark.asyncio@@ -435,11 +492,16 @@ async def test_image_creative_still_works():@pytest.mark.asyncio-async def test_video_creative_with_description():- """Test that video_id + description routes through asset_feed_spec (not video_data).-- Meta API v24 rejects 'description' inside video_data. To support descriptions- for video ads, we route to asset_feed_spec when video_id + description is given.+async def test_video_creative_with_description_drops_description_and_warns():+ """video_id + description (single, no plural params) stays on the simple+ object_story_spec.video_data path and drops `description` with a warning.++ Meta's video_data schema does not have a description field for a single+ video, and routing through asset_feed_spec to honor description silently+ turns the creative into a dynamic creative — which CTWA campaigns reject+ (error_subcode 1885392). Dropping the unrenderable field with a clear+ warning preserves the simple path; callers who actually need a description+ can pass `descriptions=[...]` (plural) to opt explicitly into asset_feed_spec."""with patch('meta_ads_mcp.core.ads.make_api_request') as mock_api, \@@ -476,35 +538,32 @@ async def test_video_creative_with_description():creative_data = mock_api.call_args_list[1][0][2]- # Should use asset_feed_spec (not simple video_data path), because- # video_data does not support description- assert "asset_feed_spec" in creative_data, (- "video + description should use asset_feed_spec so description is sent to Meta"- )-- afs = creative_data["asset_feed_spec"]-- # Description should be in asset_feed_spec.descriptions- assert "descriptions" in afs, "description should appear in asset_feed_spec.descriptions"- assert afs["descriptions"] == [{"text": "The text below the headline in feed placements"}]-- # Other fields should also be present- assert afs["bodies"] == [{"text": "Primary text for the ad"}]- assert afs["titles"] == [{"text": "Watch Now"}]- assert "videos" in afs- assert afs["videos"][0]["video_id"] == "vid_desc_test"-- # PR-C: video metadata moved from object_story_spec.video_data to asset_feed_spec.- # description is carried by asset_feed_spec.descriptions (asserted above).+ # Simple path — no asset_feed_spec.+ assert "asset_feed_spec" not in creative_dataoss = creative_data["object_story_spec"]- assert "video_data" not in oss- assert "link_data" not in oss- assert oss == {"page_id": "123456789"}+ video_data = oss["video_data"]+ assert video_data["video_id"] == "vid_desc_test"+ assert video_data["title"] == "Watch Now"+ assert video_data["message"] == "Primary text for the ad"+ # description is NOT carried — Meta's video_data has no such field.+ assert "description" not in video_data+ assert video_data["call_to_action"]["type"] == "LEARN_MORE"++ # Response should warn the caller that description was dropped.+ parsed = json.loads(result)+ warning_field = parsed.get("warning")+ # warning may be a single string or a list when several apply.+ warnings_list = warning_field if isinstance(warning_field, list) else [warning_field]+ assert any(+ w and "description" in w and "dropped" in w+ for w in warnings_list+ ), f"Expected a 'description was dropped' warning, got: {warning_field!r}"@pytest.mark.asyncio-async def test_video_creative_description_only():- """Test that video_id + description alone (no other plural params) still works."""+async def test_video_creative_description_only_drops_description():+ """video_id + description alone also stays on the simple path; description+ is dropped with a warning."""with patch('meta_ads_mcp.core.ads.make_api_request') as mock_api, \patch('meta_ads_mcp.core.ads._discover_pages_for_account') as mock_discover:@@ -537,18 +596,62 @@ async def test_video_creative_description_only():creative_data = mock_api.call_args_list[1][0][2]+ assert "asset_feed_spec" not in creative_data+ oss = creative_data["object_story_spec"]+ assert "description" not in oss["video_data"]++ parsed = json.loads(result)+ warning_field = parsed.get("warning")+ warnings_list = warning_field if isinstance(warning_field, list) else [warning_field]+ assert any(+ w and "description" in w and "dropped" in w+ for w in warnings_list+ ), f"Expected a 'description was dropped' warning, got: {warning_field!r}"+++async def test_video_creative_with_descriptions_plural_routes_to_asset_feed_spec():+ """Callers who actually need a description on a video creative can use the+ plural form to opt explicitly into asset_feed_spec. The plural form has+ always meant "I want a dynamic creative" so this path stays unchanged."""++ with patch('meta_ads_mcp.core.ads.make_api_request') as mock_api, \+ patch('meta_ads_mcp.core.ads._discover_pages_for_account') as mock_discover:++ mock_discover.return_value = {+ "success": True,+ "page_id": "123456789",+ "page_name": "Test Page"+ }++ mock_api.side_effect = [+ {"picture": "https://example.com/auto-thumb.jpg"},+ {"id": "creative_vid_descs"},+ {"id": "creative_vid_descs", "name": "Video Plural Desc", "status": "ACTIVE"}+ ]++ await create_ad_creative(+ account_id="act_123456",+ video_id="vid_plural",+ name="Video Plural Desc",+ link_url="https://example.com/",+ descriptions=["The description below the headline"],+ access_token="test_token"+ )++ creative_data = mock_api.call_args_list[1][0][2]assert "asset_feed_spec" in creative_dataafs = creative_data["asset_feed_spec"]- assert afs["descriptions"] == [{"text": "Only description, no other plural params"}]+ assert afs["descriptions"] == [{"text": "The description below the headline"}]assert "videos" in afs+ assert afs["videos"][0]["video_id"] == "vid_plural"@pytest.mark.asyncio-async def test_video_creative_instagram_actor_id_with_explicit_ad_formats():- """Test that explicitly passing ad_formats with instagram_actor_id + video_id also works.-- The caller can still explicitly pass ad_formats=["SINGLE_VIDEO"]; it should be- respected (not overridden) when both instagram_actor_id and video_id are present.+async def test_video_creative_instagram_actor_id_with_optimization_type_uses_asset_feed_spec():+ """Callers who actually want the dynamic-creative path with an Instagram+ identity can pass `optimization_type` explicitly. instagram_user_id stays+ nested in object_story_spec; videos[] + ad_formats live in asset_feed_spec."""with patch('meta_ads_mcp.core.ads.make_api_request') as mock_api, \@@ -564,29 +667,30 @@ async def test_video_creative_instagram_actor_id_with_explicit_ad_formats():# 1) Auto-fetch video thumbnail{"picture": "https://example.com/auto-thumb.jpg"},# 2) POST create creative- {"id": "creative_vid_ig_fmt"},+ {"id": "creative_vid_ig_dof"},# 3) GET creative details- {"id": "creative_vid_ig_fmt", "name": "Video IG Explicit Fmt", "status": "ACTIVE"}+ {"id": "creative_vid_ig_dof", "name": "Video IG DOF", "status": "ACTIVE"}]result = await create_ad_creative(account_id="act_123456",- video_id="vid_explicit_fmt",- name="Video IG Explicit Format",+ video_id="vid_explicit_dof",+ name="Video IG DOF",link_url="https://example.com/",instagram_actor_id="ig_777888",- ad_formats=["SINGLE_VIDEO"],+ optimization_type="DEGREES_OF_FREEDOM",+ messages=["Variant 1", "Variant 2"],access_token="test_token")creative_data = mock_api.call_args_list[1][0][2]- # Must route through asset_feed_spec with explicit ad_formats respected+ # optimization_type opts the caller into asset_feed_spec.assert "asset_feed_spec" in creative_dataafs = creative_data["asset_feed_spec"]- assert afs["ad_formats"] == ["SINGLE_VIDEO"]assert "videos" in afs- assert afs["videos"][0]["video_id"] == "vid_explicit_fmt"+ assert afs["videos"][0]["video_id"] == "vid_explicit_dof"+ # instagram_user_id stays inside object_story_spec.assert creative_data["object_story_spec"]["instagram_user_id"] == "ig_777888"