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.

fix(ads): translate placement_groups rules for videos[] path (#87)

Yves Junqueira4907aa624f53
diff --git a/meta_ads_mcp/core/ads.py b/meta_ads_mcp/core/ads.py
index 4ad626d..b78d944 100644
--- a/meta_ads_mcp/core/ads.py
+++ b/meta_ads_mcp/core/ads.py
@@ -184,6 +184,121 @@ _ALL_ENHANCEMENT_KEYS: tuple[str, ...] = (
)
+def _translate_video_customization_rules(
+ rules: List[Dict[str, Any]],
+ videos_array: List[Dict[str, Any]],
+) -> tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:
+ """
+ Translate user-friendly placement_groups format to Meta API format for videos[].
+
+ Parallels `_translate_asset_customization_rules` (which handles the images[] path).
+ When callers pass `videos=[...]` with placement_groups-style rules, the rules and
+ videos_array need to be rewritten into the shape Meta expects:
+
+ Our user-facing format:
+ videos_array = [{"video_id": "A"}, {"video_id": "B"}]
+ rules = [
+ {"placement_groups": ["FEED"], "customization_spec": {"video_ids": ["A"]}},
+ {"placement_groups": ["STORY"], "customization_spec": {"video_ids": ["B"]}}
+ ]
+
+ Meta API format:
+ videos_array = [
+ {"video_id": "A", "adlabels": [{"name": "PBOARD_VID_0"}]},
+ {"video_id": "B", "adlabels": [{"name": "PBOARD_VID_1"}]}
+ ]
+ rules = [
+ {"customization_spec": {"publisher_platforms": [...], "facebook_positions": [...]},
+ "video_label": {"name": "PBOARD_VID_0"}},
+ ...
+ ]
+
+ Also tolerates `customization_spec.video_label: "str"` (string) by hoisting it to
+ `video_label: {"name": "str"}` at the rule level. Existing adlabels on
+ videos_array entries (e.g., user-supplied via `videos[].label`) are preserved.
+
+ Rules that do NOT contain placement_groups are passed through unchanged.
+ """
+ if not rules or not any("placement_groups" in r for r in rules):
+ return rules, videos_array
+
+ vid_to_label: Dict[str, str] = {}
+ label_counter = 0
+ translated_rules: List[Dict[str, Any]] = []
+
+ for rule in rules:
+ if "placement_groups" not in rule:
+ translated_rules.append(rule)
+ continue
+
+ placement_groups = rule.get("placement_groups", [])
+ cspec_input = rule.get("customization_spec", {})
+
+ # Build Meta-format customization_spec from placement_groups
+ publisher_platforms: set = set()
+ facebook_positions: set = set()
+ instagram_positions: set = set()
+ audience_network_positions: set = set()
+
+ for pg in placement_groups:
+ mapping = _PLACEMENT_GROUP_TO_POSITIONS.get(pg, {})
+ publisher_platforms.update(mapping.get("publisher_platforms", []))
+ facebook_positions.update(mapping.get("facebook_positions", []))
+ instagram_positions.update(mapping.get("instagram_positions", []))
+ audience_network_positions.update(mapping.get("audience_network_positions", []))
+
+ meta_cspec: Dict[str, Any] = {}
+ if publisher_platforms:
+ meta_cspec["publisher_platforms"] = sorted(publisher_platforms)
+ if facebook_positions:
+ meta_cspec["facebook_positions"] = sorted(facebook_positions)
+ if instagram_positions:
+ meta_cspec["instagram_positions"] = sorted(instagram_positions)
+ if audience_network_positions:
+ meta_cspec["audience_network_positions"] = sorted(audience_network_positions)
+
+ # Carry over text overrides into customization_spec
+ for text_field in ("bodies", "titles", "descriptions", "link_urls", "call_to_action_types"):
+ if text_field in cspec_input:
+ meta_cspec[text_field] = cspec_input[text_field]
+
+ translated_rule: Dict[str, Any] = {"customization_spec": meta_cspec}
+
+ # Assign video_label at the rule level. Precedence:
+ # 1) customization_spec.video_ids: [id] — map id → generated label
+ # 2) customization_spec.video_label: "str" — coerce string to {"name": str}
+ # 3) customization_spec.video_label: {"name": "str"} — pass through
+ vid_ids = cspec_input.get("video_ids", [])
+ raw_video_label = cspec_input.get("video_label")
+ if vid_ids:
+ v = vid_ids[0]
+ if v not in vid_to_label:
+ vid_to_label[v] = f"PBOARD_VID_{label_counter}"
+ label_counter += 1
+ translated_rule["video_label"] = {"name": vid_to_label[v]}
+ elif isinstance(raw_video_label, str):
+ translated_rule["video_label"] = {"name": raw_video_label}
+ elif isinstance(raw_video_label, dict):
+ translated_rule["video_label"] = raw_video_label
+
+ translated_rules.append(translated_rule)
+
+ # Add adlabels to videos_array for referenced video_ids. Preserve any adlabels
+ # the caller already set (via `videos[].label` in create_ad_creative), so explicit
+ # labels win over auto-generated ones.
+ updated_videos: List[Dict[str, Any]] = []
+ for v in videos_array:
+ vid_id = str(v.get("video_id", ""))
+ if vid_id in vid_to_label and "adlabels" not in v:
+ updated = dict(v)
+ updated["adlabels"] = [{"name": vid_to_label[vid_id]}]
+ updated_videos.append(updated)
+ else:
+ updated_videos.append(v)
+
+ return translated_rules, updated_videos
+
+
def _translate_video_customization_rules_for_existing_post(
rules: List[Dict[str, Any]],
) -> tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:
@@ -1949,10 +2064,15 @@ async def create_ad_creative(
# facebook_positions, instagram_positions) and image_label/video_label at the
# rule level for asset selection. Assets also need adlabels assigned.
# Rules in raw Meta API format (without placement_groups) are passed through unchanged.
- if asset_customization_rules and images_array:
- asset_customization_rules, images_array = _translate_asset_customization_rules(
- asset_customization_rules, images_array
- )
+ if asset_customization_rules:
+ if images_array:
+ asset_customization_rules, images_array = _translate_asset_customization_rules(
+ asset_customization_rules, images_array
+ )
+ elif videos_array:
+ asset_customization_rules, videos_array = _translate_video_customization_rules(
+ asset_customization_rules, videos_array
+ )
# ------------------------------------------------------------------
# Build asset_feed_spec base: DOF vs non-DOF use different patterns.
diff --git a/tests/test_video_creatives.py b/tests/test_video_creatives.py
index 982bc3b..7deccd1 100644
--- a/tests/test_video_creatives.py
+++ b/tests/test_video_creatives.py
@@ -3,7 +3,10 @@
import pytest
import json
from unittest.mock import AsyncMock, patch
-from meta_ads_mcp.core.ads import create_ad_creative
+from meta_ads_mcp.core.ads import (
+ create_ad_creative,
+ _translate_video_customization_rules,
+)
def parse_error_result(result: str) -> dict:
@@ -686,3 +689,230 @@ async def test_videos_array_does_not_trigger_thumbnail_fetch_with_none():
f"(args={call.args!r}); the singular-video thumbnail auto-fetch "
f"should be skipped when only videos=[...] is provided"
)
+
+
+# ---------------------------------------------------------------------------
+# Unit tests for _translate_video_customization_rules (videos[] path)
+# ---------------------------------------------------------------------------
+
+def test_translate_video_rules_placement_groups_format():
+ """placement_groups + customization_spec.video_ids translates to Meta API format.
+
+ Expected Meta format:
+ - rule has customization_spec.publisher_platforms and facebook/instagram_positions
+ - rule has video_label: {"name": "..."} at the rule level
+ - rule has NO `placement_groups` key
+ - videos_array entries get `adlabels` assigned matching their rule
+ """
+ videos_array = [
+ {"video_id": "vidA"},
+ {"video_id": "vidB"},
+ ]
+ rules = [
+ {
+ "placement_groups": ["FEED"],
+ "customization_spec": {"video_ids": ["vidA"]},
+ },
+ {
+ "placement_groups": ["STORY"],
+ "customization_spec": {"video_ids": ["vidB"]},
+ },
+ ]
+
+ translated, updated_videos = _translate_video_customization_rules(rules, videos_array)
+
+ # Both rules translated
+ assert len(translated) == 2
+
+ # FEED rule
+ feed_rule = translated[0]
+ assert "placement_groups" not in feed_rule
+ feed_cspec = feed_rule["customization_spec"]
+ assert "facebook" in feed_cspec["publisher_platforms"]
+ assert "instagram" in feed_cspec["publisher_platforms"]
+ assert "feed" in feed_cspec["facebook_positions"]
+ assert feed_rule["video_label"] == {"name": "PBOARD_VID_0"}
+
+ # STORY rule
+ story_rule = translated[1]
+ assert "placement_groups" not in story_rule
+ story_cspec = story_rule["customization_spec"]
+ assert "story" in story_cspec["facebook_positions"]
+ assert "story" in story_cspec["instagram_positions"]
+ assert story_rule["video_label"] == {"name": "PBOARD_VID_1"}
+
+ # videos_array gets adlabels
+ assert len(updated_videos) == 2
+ assert updated_videos[0]["video_id"] == "vidA"
+ assert updated_videos[0]["adlabels"] == [{"name": "PBOARD_VID_0"}]
+ assert updated_videos[1]["video_id"] == "vidB"
+ assert updated_videos[1]["adlabels"] == [{"name": "PBOARD_VID_1"}]
+
+
+def test_translate_video_rules_passthrough_raw_format():
+ """Rules already in Meta API format (no placement_groups) pass through unchanged."""
+ videos_array = [
+ {"video_id": "vidA", "adlabels": [{"name": "labelfb"}]},
+ ]
+ raw_rules = [
+ {
+ "customization_spec": {
+ "publisher_platforms": ["facebook"],
+ "facebook_positions": ["feed"],
+ },
+ "video_label": {"name": "labelfb"},
+ },
+ ]
+
+ translated, updated_videos = _translate_video_customization_rules(raw_rules, videos_array)
+
+ # Rules passed through unchanged
+ assert translated == raw_rules
+ # videos_array passed through unchanged
+ assert updated_videos == videos_array
+
+
+def test_translate_video_rules_preserves_existing_adlabels():
+ """If videos_array entries already have adlabels, do not override them."""
+ # User-supplied labels via videos[{"label": "my_label"}]
+ videos_array = [
+ {"video_id": "vidA", "adlabels": [{"name": "user_label"}]},
+ ]
+ rules = [
+ {
+ "placement_groups": ["FEED"],
+ "customization_spec": {"video_ids": ["vidA"]},
+ },
+ ]
+
+ translated, updated_videos = _translate_video_customization_rules(rules, videos_array)
+
+ # video_label at rule level uses auto-generated name
+ assert translated[0]["video_label"] == {"name": "PBOARD_VID_0"}
+ # ...but the existing adlabels on the video are preserved (not overridden)
+ assert updated_videos[0]["adlabels"] == [{"name": "user_label"}]
+
+
+def test_translate_video_rules_string_video_label_coerced():
+ """Caller passes customization_spec.video_label: 'str' — coerce to {"name": 'str'}.
+
+ This handles TEST 3 from matt's test cases: string video_label inside
+ customization_spec should be lifted to the rule level as an object.
+ """
+ videos_array = [
+ {"video_id": "vidA", "adlabels": [{"name": "vert"}]},
+ ]
+ rules = [
+ {
+ "placement_groups": ["STORY"],
+ "customization_spec": {"video_label": "vert"},
+ },
+ ]
+
+ translated, updated_videos = _translate_video_customization_rules(rules, videos_array)
+
+ assert len(translated) == 1
+ rule = translated[0]
+ assert "placement_groups" not in rule
+ # video_label coerced from string to object, hoisted to rule level
+ assert rule["video_label"] == {"name": "vert"}
+ # customization_spec does not carry video_label (it's moved to rule level)
+ assert "video_label" not in rule["customization_spec"]
+ # videos_array untouched because we didn't generate any labels
+ assert updated_videos == videos_array
+
+
+async def test_create_ad_creative_videos_with_placement_rules_sends_correct_payload():
+ """End-to-end: videos[] + asset_customization_rules with placement_groups.
+
+ Mirrors matt's TEST 6 payload. The resulting Meta API payload must have:
+ - asset_feed_spec.videos with adlabels
+ - asset_feed_spec.asset_customization_rules in Meta format
+ (publisher_platforms, facebook/instagram_positions, video_label)
+ - NO `placement_groups` key anywhere
+ - NO raw `video_ids` inside customization_spec in the outgoing rules
+ """
+ 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 = [
+ # 1) POST create creative
+ {"id": "creative_vid_rules"},
+ # 2) GET creative details
+ {"id": "creative_vid_rules", "name": "Video Placement Rules", "status": "ACTIVE"},
+ ]
+
+ result = await create_ad_creative(
+ account_id="act_123456",
+ videos=[
+ {"video_id": "vidA"},
+ {"video_id": "vidB"},
+ ],
+ asset_customization_rules=[
+ {
+ "placement_groups": ["FEED"],
+ "customization_spec": {"video_ids": ["vidA"]},
+ },
+ {
+ "placement_groups": ["STORY"],
+ "customization_spec": {"video_ids": ["vidB"]},
+ },
+ ],
+ name="Video Placement Rules",
+ link_url="https://example.com/",
+ message="Check it out",
+ headline="Watch Now",
+ call_to_action_type="LEARN_MORE",
+ access_token="test_token",
+ )
+
+ # No thumbnail auto-fetch (no singular video_id)
+ assert mock_api.call_count == 2
+ creative_data = mock_api.call_args_list[0][0][2]
+
+ assert "asset_feed_spec" in creative_data
+ afs = creative_data["asset_feed_spec"]
+
+ # videos[] entries must have adlabels
+ assert "videos" in afs
+ videos_out = afs["videos"]
+ assert len(videos_out) == 2
+ assert videos_out[0]["video_id"] == "vidA"
+ assert videos_out[0]["adlabels"] == [{"name": "PBOARD_VID_0"}]
+ assert videos_out[1]["video_id"] == "vidB"
+ assert videos_out[1]["adlabels"] == [{"name": "PBOARD_VID_1"}]
+
+ # Rules must be in Meta API format
+ assert "asset_customization_rules" in afs
+ rules_out = afs["asset_customization_rules"]
+ assert len(rules_out) == 2
+
+ # No user-facing placement_groups anywhere in outgoing payload
+ for r in rules_out:
+ assert "placement_groups" not in r, (
+ f"placement_groups must not ship to Meta: {r!r}"
+ )
+ # video_ids inside customization_spec should have been converted to
+ # video_label at the rule level; raw video_ids must not ship to Meta
+ cspec = r.get("customization_spec", {})
+ assert "video_ids" not in cspec, (
+ f"customization_spec.video_ids must not ship to Meta: {r!r}"
+ )
+
+ # FEED rule has feed positions and video_label
+ feed_rule = rules_out[0]
+ assert "feed" in feed_rule["customization_spec"]["facebook_positions"]
+ assert feed_rule["video_label"] == {"name": "PBOARD_VID_0"}
+
+ # STORY rule has story positions and video_label
+ story_rule = rules_out[1]
+ assert "story" in story_rule["customization_spec"]["facebook_positions"]
+ assert "story" in story_rule["customization_spec"]["instagram_positions"]
+ assert story_rule["video_label"] == {"name": "PBOARD_VID_1"}