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 get_ad_creatives 'dict' object is not callable error
Yves Junqueira6d30a6a4f104
diff --git a/meta_ads_mcp/__init__.py b/meta_ads_mcp/__init__.pyindex c12e6cb..f6a9b3e 100644--- a/meta_ads_mcp/__init__.py+++ b/meta_ads_mcp/__init__.py@@ -7,7 +7,7 @@ with the Claude LLM.from meta_ads_mcp.core.server import main-__version__ = "0.4.6"+__version__ = "0.4.7"__all__ = ['get_ad_accounts',diff --git a/meta_ads_mcp/core/ads.py b/meta_ads_mcp/core/ads.pyindex 50de7b1..d1f11dc 100644--- a/meta_ads_mcp/core/ads.py+++ b/meta_ads_mcp/core/ads.py@@ -10,7 +10,7 @@ import timefrom .api import meta_api_tool, make_api_requestfrom .accounts import get_ad_accounts-from .utils import download_image, try_multiple_download_methods, ad_creative_images+from .utils import download_image, try_multiple_download_methods, ad_creative_images, extract_creative_image_urlsfrom .server import mcp_server@@ -179,7 +179,7 @@ async def get_ad_creatives(access_token: str = None, ad_id: str = None) -> str:# Add image URLs for direct viewing if availableif 'data' in data:for creative in data['data']:- creative['image_urls_for_viewing'] = ad_creative_images(creative)+ creative['image_urls_for_viewing'] = extract_creative_image_urls(creative)return json.dumps(data, indent=2)diff --git a/meta_ads_mcp/core/utils.py b/meta_ads_mcp/core/utils.pyindex 84c9083..a461704 100644--- a/meta_ads_mcp/core/utils.py+++ b/meta_ads_mcp/core/utils.py@@ -1,6 +1,6 @@"""Utility functions for Meta Ads API."""-from typing import Optional, Dict, Any+from typing import Optional, Dict, Any, Listimport httpximport iofrom PIL import Image as PILImage@@ -74,6 +74,64 @@ logger = setup_logging()# Global store for ad creative imagesad_creative_images = {}++def extract_creative_image_urls(creative: Dict[str, Any]) -> List[str]:+ """+ Extract image URLs from a creative object for direct viewing.++ Args:+ creative: Meta Ads creative object++ Returns:+ List of image URLs found in the creative+ """+ image_urls = []++ # Check for direct image_url field+ if "image_url" in creative and creative["image_url"]:+ image_urls.append(creative["image_url"])++ # Check for thumbnail_url field+ if "thumbnail_url" in creative and creative["thumbnail_url"]:+ image_urls.append(creative["thumbnail_url"])++ # Check object_story_spec for image URLs+ if "object_story_spec" in creative:+ story_spec = creative["object_story_spec"]++ # Check link_data for image fields+ if "link_data" in story_spec:+ link_data = story_spec["link_data"]++ # Check for picture field+ if "picture" in link_data and link_data["picture"]:+ image_urls.append(link_data["picture"])++ # Check for image_url field in link_data+ if "image_url" in link_data and link_data["image_url"]:+ image_urls.append(link_data["image_url"])++ # Check video_data for thumbnail (if present)+ if "video_data" in story_spec and "image_url" in story_spec["video_data"]:+ image_urls.append(story_spec["video_data"]["image_url"])++ # Check asset_feed_spec for multiple images+ if "asset_feed_spec" in creative and "images" in creative["asset_feed_spec"]:+ for image in creative["asset_feed_spec"]["images"]:+ if "url" in image and image["url"]:+ image_urls.append(image["url"])++ # Remove duplicates while preserving order+ seen = set()+ unique_urls = []+ for url in image_urls:+ if url not in seen:+ seen.add(url)+ unique_urls.append(url)++ return unique_urls++async def download_image(url: str) -> Optional[bytes]:"""Download an image from a URL.diff --git a/pyproject.toml b/pyproject.tomlindex 2ccedad..16533b4 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -4,7 +4,7 @@ build-backend = "hatchling.build"[project]name = "meta-ads-mcp"-version = "0.4.6"+version = "0.4.7"description = "Model Context Protocol (MCP) plugin for interacting with Meta Ads API"readme = "README.md"requires-python = ">=3.10"diff --git a/tests/test_get_ad_creatives_fix.py b/tests/test_get_ad_creatives_fix.pynew file mode 100644index 0000000..40e12a6--- /dev/null+++ b/tests/test_get_ad_creatives_fix.py@@ -0,0 +1,154 @@+"""Regression tests for get_ad_creatives function bug fix.++Tests for issue where get_ad_creatives would throw:+'TypeError: 'dict' object is not callable'++This was caused by trying to call ad_creative_images(creative) where+ad_creative_images is a dictionary, not a function.++The fix was to create extract_creative_image_urls() function and use that instead.+"""++import pytest+import json+from unittest.mock import AsyncMock, patch+from meta_ads_mcp.core.ads import get_ad_creatives+from meta_ads_mcp.core.utils import ad_creative_images+++class TestGetAdCreativesBugFix:+ """Regression test cases for the get_ad_creatives function bug fix."""++ async def test_get_ad_creatives_regression_fix(self):+ """Regression test: ensure get_ad_creatives works correctly and doesn't throw 'dict' object is not callable."""++ # Mock the make_api_request to return sample creative data+ sample_creative_data = {+ "data": [+ {+ "id": "123456789",+ "name": "Test Creative",+ "status": "ACTIVE",+ "thumbnail_url": "https://example.com/thumb.jpg",+ "image_url": "https://example.com/image.jpg",+ "image_hash": "abc123",+ "object_story_spec": {+ "page_id": "987654321",+ "link_data": {+ "image_hash": "abc123",+ "link": "https://example.com",+ "name": "Test Ad"+ }+ }+ }+ ]+ }++ with patch('meta_ads_mcp.core.ads.make_api_request', new_callable=AsyncMock) as mock_api:+ mock_api.return_value = sample_creative_data++ # This should NOT raise a TypeError anymore+ # Previously this would fail with: TypeError: 'dict' object is not callable+ result = await get_ad_creatives(access_token="test_token", ad_id="120228922933270272")++ # Parse the result+ result_data = json.loads(result)++ # Verify the structure is correct+ assert "data" in result_data+ assert len(result_data["data"]) == 1++ creative = result_data["data"][0]+ assert creative["id"] == "123456789"+ assert creative["name"] == "Test Creative"+ assert "image_urls_for_viewing" in creative+ assert isinstance(creative["image_urls_for_viewing"], list)++ async def test_extract_creative_image_urls_function(self):+ """Test the extract_creative_image_urls function works correctly."""+ from meta_ads_mcp.core.utils import extract_creative_image_urls++ # Test creative with various image URL fields+ test_creative = {+ "id": "123456789",+ "name": "Test Creative",+ "status": "ACTIVE",+ "thumbnail_url": "https://example.com/thumb.jpg",+ "image_url": "https://example.com/image.jpg",+ "image_hash": "abc123",+ "object_story_spec": {+ "page_id": "987654321",+ "link_data": {+ "image_hash": "abc123",+ "link": "https://example.com",+ "name": "Test Ad",+ "picture": "https://example.com/picture.jpg"+ }+ }+ }++ urls = extract_creative_image_urls(test_creative)++ # Should extract URLs in order: image_url, thumbnail_url, picture+ expected_urls = [+ "https://example.com/image.jpg",+ "https://example.com/thumb.jpg",+ "https://example.com/picture.jpg"+ ]++ assert urls == expected_urls++ # Test with empty creative+ empty_urls = extract_creative_image_urls({})+ assert empty_urls == []++ # Test with duplicates (should remove them)+ duplicate_creative = {+ "image_url": "https://example.com/same.jpg",+ "thumbnail_url": "https://example.com/same.jpg", # Same URL+ }+ unique_urls = extract_creative_image_urls(duplicate_creative)+ assert unique_urls == ["https://example.com/same.jpg"]++ async def test_get_ad_creatives_no_ad_id(self):+ """Test get_ad_creatives with no ad_id provided."""++ result = await get_ad_creatives(access_token="test_token", ad_id=None)+ result_data = json.loads(result)++ # The @meta_api_tool decorator wraps the result in a data field+ assert "data" in result_data+ error_data = json.loads(result_data["data"])+ assert "error" in error_data+ assert error_data["error"] == "No ad ID provided"++ async def test_get_ad_creatives_empty_data(self):+ """Test get_ad_creatives when API returns empty data."""++ empty_data = {"data": []}++ with patch('meta_ads_mcp.core.ads.make_api_request', new_callable=AsyncMock) as mock_api:+ mock_api.return_value = empty_data++ result = await get_ad_creatives(access_token="test_token", ad_id="120228922933270272")+ result_data = json.loads(result)++ assert "data" in result_data+ assert len(result_data["data"]) == 0+++def test_ad_creative_images_is_dict():+ """Test that ad_creative_images is a dictionary, not a function.++ This confirms the original issue: ad_creative_images is a dict for storing image data,+ but was being called as a function ad_creative_images(creative), which would fail.+ This test ensures we don't accidentally change ad_creative_images to a function+ and break its intended purpose as a storage dictionary.+ """+ assert isinstance(ad_creative_images, dict)++ # This would raise TypeError: 'dict' object is not callable+ # This is the original bug - trying to call a dict as a function+ with pytest.raises(TypeError, match="'dict' object is not callable"):+ ad_creative_images({"test": "data"})\ No newline at end of file