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(meta-ads): get_image_by_hash tool + docs steering LLMs to it (#127)
Yves Junqueiraee92dc929098
diff --git a/meta_ads_mcp/__init__.py b/meta_ads_mcp/__init__.pyindex 3b075b7..633e0bd 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.109"+__version__ = "1.0.110"__all__ = ['get_ad_accounts',diff --git a/meta_ads_mcp/core/ads.py b/meta_ads_mcp/core/ads.pyindex 611dfca..cc8a442 100644--- a/meta_ads_mcp/core/ads.py+++ b/meta_ads_mcp/core/ads.py@@ -717,12 +717,15 @@ async def get_ad_creatives(ad_id: str, access_token: Optional[str] = None) -> st@meta_api_toolasync def get_ad_image(ad_id: str, access_token: Optional[str] = None) -> Image:"""- Get, download, and visualize a Meta ad image in one step. Useful to see the image in the LLM.-+ Get, download, and visualize the image attached to an existing Meta ad.++ Takes a Meta ad ID and returns the image the ad is currently serving.+ If all you have is an image hash (no ad), use get_image_by_hash instead.+Args:ad_id: Meta Ads ad IDaccess_token: Meta API access token (optional - will use cached token if not provided)-+Returns:The ad image ready for direct visual analysis"""@@ -859,58 +862,89 @@ async def get_ad_image(ad_id: str, access_token: Optional[str] = None) -> Image:return f"Error processing image from direct URL: {str(e)}"print(f"Found image hashes: {image_hashes}")-- # Now fetch image data using adimages endpoint with specific format++ return await _fetch_image_by_hash(account_id, image_hashes[0], access_token)+++@mcp_server.tool()+@meta_api_tool+async def get_image_by_hash(+ account_id: str,+ image_hash: str,+ access_token: Optional[str] = None,+) -> Image:+ """+ Get, download, and visualize a Meta ad image by its hash.++ Use this when you have an image_hash without an ad — e.g. the hash+ returned by upload_ad_image / bulk_upload_ad_images, or one referenced+ in a creative (object_story_spec.link_data.image_hash, asset_feed_spec+ images[].hash, etc.). To view the image of an existing ad, prefer+ get_ad_image(ad_id).++ Args:+ account_id: Meta Ads account ID (act_XXXXXXXXX or bare numeric — both accepted)+ image_hash: Meta image hash+ access_token: Meta API access token (optional - will use cached token if not provided)++ Returns:+ The image ready for direct visual analysis+ """+ if not account_id:+ return "Error: No account ID provided"+ if not image_hash:+ return "Error: No image hash provided"+ normalized_account = ensure_act_prefix(account_id).removeprefix("act_")+ return await _fetch_image_by_hash(normalized_account, image_hash, access_token)+++async def _fetch_image_by_hash(+ account_id: str,+ image_hash: str,+ access_token: Optional[str],+) -> Union[Image, str]:+ """Fetch a single image from act_{account_id}/adimages by hash and return it as a PIL Image.++ account_id is the bare numeric part (without the "act_" prefix). Returns+ an "Error: ..." string on failure so the @meta_api_tool wrapper can+ serialize it.+ """image_endpoint = f"act_{account_id}/adimages"-- # Format the hashes parameter exactly as in our successful curl test- hashes_str = f'["{image_hashes[0]}"]' # Format first hash only, as JSON string array-+ hashes_str = f'["{image_hash}"]'image_params = {"fields": "hash,url,width,height,name,status",- "hashes": hashes_str+ "hashes": hashes_str,}-+print(f"Requesting image data with params: {image_params}")image_data = await make_api_request(image_endpoint, access_token, image_params)-+if "error" in image_data:return f"Error: Failed to get image data - {json.dumps(image_data)}"-+if "data" not in image_data or not image_data["data"]:- return "Error: No image data returned from API"-- # Get the first image URL- first_image = image_data["data"][0]- image_url = first_image.get("url")-+ return (+ f"Error: No image found for hash {image_hash} in account "+ f"act_{account_id}. Confirm the hash and that the account matches "+ "the one used to upload (image hashes are scoped per ad account)."+ )++ image_url = image_data["data"][0].get("url")if not image_url:return "Error: No valid image URL found"-+print(f"Downloading image from URL: {image_url}")-- # Download the imageimage_bytes = await download_image(image_url)-if not image_bytes:return "Error: Failed to download image"-+try:- # Convert bytes to PIL Imageimg = PILImage.open(io.BytesIO(image_bytes))-- # Convert to RGB if neededif img.mode != "RGB":img = img.convert("RGB")-- # Create a byte stream of the image databyte_arr = io.BytesIO()img.save(byte_arr, format="JPEG")- img_bytes = byte_arr.getvalue()-- # Return as an Image object that LLM can directly analyze- return Image(data=img_bytes, format="jpeg")-+ return Image(data=byte_arr.getvalue(), format="jpeg")except Exception as e:return f"Error processing image: {str(e)}"@@ -1250,16 +1284,21 @@ async def upload_ad_image() -> str:"""Upload an image to use in Meta Ads creatives.-+Args:account_id: Meta Ads account ID (format: act_XXXXXXXXX)access_token: Meta API access token (optional - will use cached token if not provided)file: Data URL or raw base64 string of the image (e.g., "data:image/png;base64,iVBORw0KG...")image_url: Direct URL to an image to fetch and uploadname: Optional name for the image (default: filename)-+Returns:- JSON response with image details including hash for creative creation+ JSON object with:+ - image_hash: Pass this to create_ad_creative when building the ad,+ or to get_image_by_hash to view the image later.+ - images: List of {hash, url, width, height, name}. The url is a+ Meta CDN link you can fetch directly to view the image — no need+ to call any other tool right after upload."""# Check required parametersif not account_id:diff --git a/pyproject.toml b/pyproject.tomlindex 661771a..cb9a856 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -4,7 +4,7 @@ build-backend = "hatchling.build"[project]name = "meta-ads-mcp"-version = "1.0.109"+version = "1.0.110"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 8fcaa3f..8241973 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.109",+ "version": "1.0.110","remotes": [{"type": "streamable-http",diff --git a/tests/test_get_ad_image_regression.py b/tests/test_get_ad_image_regression.pyindex 6a87dad..0edae1d 100644--- a/tests/test_get_ad_image_regression.py+++ b/tests/test_get_ad_image_regression.py@@ -21,7 +21,7 @@ and ensure high-quality images are returned instead of thumbnails.import pytestimport jsonfrom unittest.mock import AsyncMock, patch, MagicMock-from meta_ads_mcp.core.ads import get_ad_image+from meta_ads_mcp.core.ads import get_ad_image, get_image_by_hash@pytest.mark.asyncio@@ -155,13 +155,80 @@ class TestGetAdImageRegressionFix:async def test_get_ad_image_no_ad_id(self):"""Test get_ad_image with no ad_id provided."""-+result = await get_ad_image(access_token="test_token", ad_id=None)-+# Should return error string, not throw JSON parsing errorassert isinstance(result, str)assert "Error: No ad ID provided" in result-++ async def test_get_image_by_hash_happy_path(self):+ """get_image_by_hash hits adimages directly and skips the ad/creative chain."""++ mock_image_data = {+ "data": [{+ "hash": "deadbeef00000000000000000000abcd",+ "url": "https://example.com/uploaded.jpg",+ "width": 1200,+ "height": 628,+ }]+ }++ mock_pil_image = MagicMock()+ mock_pil_image.mode = "RGB"+ mock_pil_image.convert.return_value = mock_pil_image+ mock_byte_stream = MagicMock()+ mock_byte_stream.getvalue.return_value = b"fake_jpeg_data"++ with patch('meta_ads_mcp.core.ads.make_api_request', new_callable=AsyncMock) as mock_api, \+ patch('meta_ads_mcp.core.ads.download_image', new_callable=AsyncMock) as mock_download, \+ patch('meta_ads_mcp.core.ads.PILImage.open') as mock_pil_open, \+ patch('meta_ads_mcp.core.ads.io.BytesIO') as mock_bytesio:++ mock_api.return_value = mock_image_data+ mock_download.return_value = b"fake_image_bytes"+ mock_pil_open.return_value = mock_pil_image+ mock_bytesio.return_value = mock_byte_stream++ result = await get_image_by_hash(+ access_token="test_token",+ account_id="act_111111111111111",+ image_hash="deadbeef00000000000000000000abcd",+ )++ assert mock_api.call_count == 1+ endpoint, _, params = mock_api.call_args[0]+ assert endpoint == "act_111111111111111/adimages"+ assert params["hashes"] == '["deadbeef00000000000000000000abcd"]'+ assert result is not None++ async def test_get_image_by_hash_accepts_account_without_act_prefix(self):+ """Bare numeric account_id is normalized to act_XXX before hitting Graph."""++ with patch('meta_ads_mcp.core.ads.make_api_request', new_callable=AsyncMock) as mock_api:+ mock_api.return_value = {"data": []} # triggers "no image found" branch++ result = await get_image_by_hash(+ access_token="test_token",+ account_id="111111111111111",+ image_hash="abc123",+ )++ endpoint = mock_api.call_args[0][0]+ assert endpoint == "act_111111111111111/adimages"+ assert isinstance(result, str)+ assert "No image found for hash abc123" in result++ async def test_get_image_by_hash_missing_account_id(self):+ result = await get_image_by_hash(access_token="test_token", account_id="", image_hash="abc")+ assert isinstance(result, str)+ assert "No account ID provided" in result++ async def test_get_image_by_hash_missing_hash(self):+ result = await get_image_by_hash(access_token="test_token", account_id="act_123", image_hash="")+ assert isinstance(result, str)+ assert "No image hash provided" in result+async def test_get_ad_image_parameter_order_regression(self):"""Regression test: ensure get_ad_creatives is called with correct parameter order."""