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: add get_ad_video tool to retrieve video source URL and metadata
Yves Junqueira4958af586aae
diff --git a/meta_ads_mcp/core/ads.py b/meta_ads_mcp/core/ads.pyindex 494dbc6..12980e6 100644--- a/meta_ads_mcp/core/ads.py+++ b/meta_ads_mcp/core/ads.py@@ -594,6 +594,82 @@ async def get_ad_image(ad_id: str, access_token: Optional[str] = None) -> Image:return f"Error processing image: {str(e)}"+@mcp_server.tool()+@meta_api_tool+async def get_ad_video(ad_id: str = "", video_id: str = "", access_token: Optional[str] = None) -> str:+ """+ Get video details and source URL for a Meta ad video creative. Returns the video source URL+ (direct download link), thumbnail URL, and metadata (title, description, duration).++ Provide either ad_id (to auto-extract the video from the ad creative) or video_id directly.++ Args:+ ad_id: Meta Ads ad ID (will extract video_id from the ad creative)+ video_id: Meta video ID (use this if you already have it from get_ad_creatives)+ access_token: Meta API access token (optional - will use cached token if not provided)+ """+ if not ad_id and not video_id:+ return json.dumps({"error": "Provide either ad_id or video_id"}, indent=2)++ # If only ad_id provided, extract video_id from the creative+ if not video_id:+ creative_json = await get_ad_creatives(access_token=access_token, ad_id=ad_id)+ creative_data = json.loads(creative_json)++ if "error" in creative_data:+ return json.dumps({"error": f"Could not get creatives for ad {ad_id}", "details": creative_data}, indent=2)++ # Extract video_id from creative data+ if "data" in creative_data and creative_data["data"]:+ creative = creative_data["data"][0]++ # Check object_story_spec.video_data.video_id+ oss = creative.get("object_story_spec", {})+ if "video_data" in oss:+ video_id = str(oss["video_data"].get("video_id", ""))++ # Check asset_feed_spec.videos+ if not video_id:+ afs = creative.get("asset_feed_spec", {})+ videos = afs.get("videos", [])+ if videos:+ video_id = str(videos[0].get("video_id", ""))++ if not video_id:+ return json.dumps({+ "error": "No video found in this ad creative",+ "hint": "This ad may be an image ad. Use get_ad_image instead."+ }, indent=2)++ # Fetch video details including source URL+ video_data = await make_api_request(+ video_id,+ access_token,+ {"fields": "source,title,description,length,picture,thumbnails,created_time"}+ )++ if "error" in video_data:+ return json.dumps({"error": f"Could not get video {video_id}", "details": video_data}, indent=2)++ result = {+ "video_id": video_id,+ "source_url": video_data.get("source"),+ "thumbnail_url": video_data.get("picture"),+ "title": video_data.get("title"),+ "description": video_data.get("description"),+ "duration_seconds": video_data.get("length"),+ "created_time": video_data.get("created_time"),+ }++ if ad_id:+ result["ad_id"] = ad_id++ if not result["source_url"]:+ result["warning"] = "No source URL returned. The video may have been deleted or you may lack permissions."++ return json.dumps(result, indent=2)++if ENABLE_SAVE_AD_IMAGE_LOCALLY:@mcp_server.tool()@meta_api_tooldiff --git a/tests/test_get_ad_video.py b/tests/test_get_ad_video.pynew file mode 100644index 0000000..888128f--- /dev/null+++ b/tests/test_get_ad_video.py@@ -0,0 +1,155 @@+"""Tests for get_ad_video function.++Tests video ID extraction from ad creatives (object_story_spec and asset_feed_spec)+and Meta Graph API source URL retrieval.+"""++import pytest+import json+from unittest.mock import AsyncMock, patch+from meta_ads_mcp.core.ads import get_ad_video+++class TestGetAdVideo:++ async def test_get_ad_video_with_ad_id_object_story_spec(self):+ """Extract video_id from object_story_spec.video_data and return source URL."""+ mock_creatives = {+ "data": [{+ "id": "creative_123",+ "object_story_spec": {+ "video_data": {+ "video_id": "9999",+ "image_url": "https://example.com/thumb.jpg"+ }+ }+ }]+ }++ mock_video_details = {+ "source": "https://video-xx.fbcdn.net/v/example.mp4",+ "picture": "https://example.com/thumb.jpg",+ "title": "My Ad Video",+ "description": "Test description",+ "length": 30.5,+ "created_time": "2026-03-01T12:00:00+0000",+ }++ with patch('meta_ads_mcp.core.ads.get_ad_creatives', new_callable=AsyncMock) as mock_get_creatives, \+ patch('meta_ads_mcp.core.ads.make_api_request', new_callable=AsyncMock) as mock_api:++ mock_get_creatives.return_value = json.dumps(mock_creatives)+ mock_api.return_value = mock_video_details++ result = await get_ad_video(access_token="test_token", ad_id="ad_123")+ data = json.loads(result)++ assert data["video_id"] == "9999"+ assert data["source_url"] == "https://video-xx.fbcdn.net/v/example.mp4"+ assert data["thumbnail_url"] == "https://example.com/thumb.jpg"+ assert data["duration_seconds"] == 30.5+ assert data["ad_id"] == "ad_123"++ mock_api.assert_called_once_with(+ "9999", "test_token",+ {"fields": "source,title,description,length,picture,thumbnails,created_time"}+ )++ async def test_get_ad_video_with_ad_id_asset_feed_spec(self):+ """Extract video_id from asset_feed_spec.videos when object_story_spec has no video."""+ mock_creatives = {+ "data": [{+ "id": "creative_456",+ "object_story_spec": {"link_data": {"link": "https://example.com"}},+ "asset_feed_spec": {+ "videos": [+ {"video_id": "7777", "thumbnail_url": "https://example.com/thumb2.jpg"},+ {"video_id": "8888", "thumbnail_url": "https://example.com/thumb3.jpg"},+ ]+ }+ }]+ }++ mock_video_details = {+ "source": "https://video-xx.fbcdn.net/v/flex-video.mp4",+ "picture": "https://example.com/thumb2.jpg",+ "length": 15.0,+ }++ with patch('meta_ads_mcp.core.ads.get_ad_creatives', new_callable=AsyncMock) as mock_get_creatives, \+ patch('meta_ads_mcp.core.ads.make_api_request', new_callable=AsyncMock) as mock_api:++ mock_get_creatives.return_value = json.dumps(mock_creatives)+ mock_api.return_value = mock_video_details++ result = await get_ad_video(access_token="test_token", ad_id="ad_456")+ data = json.loads(result)++ assert data["video_id"] == "7777"+ assert data["source_url"] == "https://video-xx.fbcdn.net/v/flex-video.mp4"++ async def test_get_ad_video_with_direct_video_id(self):+ """Bypass creative lookup when video_id is provided directly."""+ mock_video_details = {+ "source": "https://video-xx.fbcdn.net/v/direct.mp4",+ "picture": "https://example.com/thumb.jpg",+ "title": "Direct Video",+ "length": 60.0,+ }++ with patch('meta_ads_mcp.core.ads.make_api_request', new_callable=AsyncMock) as mock_api:+ mock_api.return_value = mock_video_details++ result = await get_ad_video(access_token="test_token", video_id="5555")+ data = json.loads(result)++ assert data["video_id"] == "5555"+ assert data["source_url"] == "https://video-xx.fbcdn.net/v/direct.mp4"+ assert "ad_id" not in data++ async def test_get_ad_video_no_video_in_creative(self):+ """Return helpful error when the ad is an image ad, not a video ad."""+ mock_creatives = {+ "data": [{+ "id": "creative_789",+ "image_hash": "abc123",+ "object_story_spec": {+ "link_data": {"image_hash": "abc123", "link": "https://example.com"}+ }+ }]+ }++ with patch('meta_ads_mcp.core.ads.get_ad_creatives', new_callable=AsyncMock) as mock_get_creatives:+ mock_get_creatives.return_value = json.dumps(mock_creatives)++ result = await get_ad_video(access_token="test_token", ad_id="ad_789")+ result_str = result if isinstance(result, str) else json.dumps(result)+ assert "No video found" in result_str+ assert "get_ad_image" in result_str++ async def test_get_ad_video_no_ids_provided(self):+ """Return error when neither ad_id nor video_id is provided."""+ result = await get_ad_video(access_token="test_token")+ result_str = result if isinstance(result, str) else json.dumps(result)+ assert "error" in result_str+ assert "ad_id" in result_str or "video_id" in result_str++ async def test_get_ad_video_api_error(self):+ """Handle Meta API errors gracefully."""+ mock_video_error = {+ "error": {+ "message": "Unsupported get request.",+ "type": "GraphMethodException",+ "code": 100+ }+ }++ with patch('meta_ads_mcp.core.ads.make_api_request', new_callable=AsyncMock) as mock_api:+ mock_api.return_value = mock_video_error++ result = await get_ad_video(access_token="test_token", video_id="invalid_id")+ data = json.loads(result)++ assert "error" in data+ assert "Could not get video" in data["error"]