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: image_crops valid keys + new compute_image_crops tool (#67)
Yves Junqueira0a03921b01b6
diff --git a/meta_ads_mcp/core/ads.py b/meta_ads_mcp/core/ads.pyindex 735997a..374903f 100644--- a/meta_ads_mcp/core/ads.py+++ b/meta_ads_mcp/core/ads.py@@ -1132,6 +1132,114 @@ async def upload_ad_image(}, indent=2)+# Valid image_crops keys accepted by Meta's API and their aspect ratios (width/height).+_VALID_CROP_KEYS: list[tuple[str, int, int]] = [+ ("100x100", 100, 100), # 1:1 square — Feed, Marketplace, Search+ ("100x72", 100, 72), # ~1.39:1 horizontal — Marketplace, some placements+ ("400x500", 400, 500), # 4:5 portrait — Feed on mobile, Stories fallback+ ("400x150", 400, 150), # ~2.67:1 wide banner — Audience Network+ ("600x360", 600, 360), # ~1.67:1 horizontal — Right column, some placements+ ("90x160", 90, 160), # 9:16 tall portrait — Stories+]+_VALID_CROP_KEY_NAMES = [k for k, _, _ in _VALID_CROP_KEYS]+++def _compute_crop_box(+ src_w: int, src_h: int, kw: int, kh: int+) -> list[list[int]]:+ """+ Compute the largest centered crop box that fits within src_w×src_h+ while matching the aspect ratio kw:kh.++ Returns [[x1, y1], [x2, y2]] in pixel coordinates.+ """+ # Scale to fill the full height; check if it fits within width.+ crop_w_from_h = src_h * kw / kh+ if crop_w_from_h <= src_w:+ # Use full height; crop width centered.+ crop_w = round(crop_w_from_h)+ crop_h = src_h+ else:+ # Use full width; crop height centered.+ crop_w = src_w+ crop_h = round(src_w * kh / kw)++ x1 = (src_w - crop_w) // 2+ y1 = (src_h - crop_h) // 2+ return [[x1, y1], [x1 + crop_w, y1 + crop_h]]+++@mcp_server.tool()+async def compute_image_crops(+ image_width: int,+ image_height: int,+ crop_keys: Optional[List[str]] = None,+) -> str:+ """+ Compute image_crops coordinates for a source image of the given dimensions.++ Returns the image_crops dict ready to pass directly to create_ad_creative+ or bulk_create_ad_creatives. For each crop key the result is the largest+ centered region that fits within the source image while matching the key's+ aspect ratio — equivalent to "Original" crop (no content is cut off beyond+ what the ratio requires).++ Args:+ image_width: Width of the source image in pixels (e.g. 1080).+ image_height: Height of the source image in pixels (e.g. 1080).+ crop_keys: Optional list of specific crop keys to compute. Defaults to+ all 6 keys accepted by Meta's API:+ "100x100" — 1:1 square (Feed, Marketplace, Search)+ "100x72" — ~1.39:1 horizontal (Marketplace, some placements)+ "400x500" — 4:5 portrait (Feed on mobile, Stories fallback)+ "400x150" — ~2.67:1 wide banner (Audience Network)+ "600x360" — ~1.67:1 horizontal (Right column, some placements)+ "90x160" — 9:16 tall portrait (Stories)++ Returns:+ JSON with the image_crops dict (ready for copy-paste into create_ad_creative),+ plus validation notes for any invalid keys requested.+ """+ if image_width <= 0 or image_height <= 0:+ return json.dumps({+ "error": "image_width and image_height must be positive integers."+ }, indent=2)++ # Resolve which keys to compute.+ if crop_keys:+ requested = crop_keys+ else:+ requested = _VALID_CROP_KEY_NAMES++ crops: dict[str, list[list[int]]] = {}+ warnings: list[str] = []++ key_map = {k: (kw, kh) for k, kw, kh in _VALID_CROP_KEYS}++ for key in requested:+ if key not in key_map:+ warnings.append(+ f"'{key}' is not a valid Meta API crop key and was skipped. "+ f"Valid keys: {', '.join(_VALID_CROP_KEY_NAMES)}."+ )+ continue+ kw, kh = key_map[key]+ crops[key] = _compute_crop_box(image_width, image_height, kw, kh)++ result: dict = {+ "image_crops": crops,+ "usage": (+ "Pass image_crops directly to create_ad_creative or as the image_crops "+ "field inside each element of bulk_create_ad_creatives."+ ),+ "source_dimensions": {"width": image_width, "height": image_height},+ }+ if warnings:+ result["warnings"] = warnings++ return json.dumps(result, indent=2)++@mcp_server.tool()@meta_api_toolasync def create_ad_creative(@@ -1235,9 +1343,26 @@ async def create_ad_creative(caption field in link_data. If not provided, Meta auto-generates itfrom the destination URL. Only applies to image (link_data) creatives.image_crops: Crop coordinates for different aspect ratios. Applied in link_data for- image creatives. Format: {"100x100": [[x1,y1],[x2,y2]], "191x100": [[x1,y1],[x2,y2]]}.- Coordinates specify top-left and bottom-right corners of the crop rectangle- in the original image's pixel space. Omit to let Meta auto-crop.+ image creatives.++ Use the compute_image_crops tool first to get the correct coordinates+ for your specific image dimensions — it computes centered crop boxes+ for any source size automatically.++ Valid crop keys (only these 6 are accepted by Meta's API):+ "100x100" — 1:1 square (Feed, Marketplace, Search)+ "100x72" — ~1.39:1 horizontal (Marketplace, some placements)+ "400x500" — 4:5 portrait (Feed on mobile, Stories fallback)+ "400x150" — ~2.67:1 wide banner (Audience Network)+ "600x360" — ~1.67:1 horizontal (Right column, some placements)+ "90x160" — 9:16 tall portrait (Stories)++ Format: {"100x100": [[x1,y1],[x2,y2]], "400x500": [[x1,y1],[x2,y2]]}+ Coordinates are pixel-based (top-left and bottom-right corners).+ The bounding box aspect ratio must match the key ratio as closely as possible.+ Image origin (0,0) is the upper-left corner.++ Omit to let Meta auto-crop (default for horizontal is 1.91:1 recommended).asset_customization_rules: Lets you assign different images or videos to specific placement groups(e.g., feed vs. stories). Only valid with image_hashes or plural asset params.Each rule uses a user-friendly format that is automatically translated todiff --git a/tests/test_compute_image_crops.py b/tests/test_compute_image_crops.pynew file mode 100644index 0000000..ef8c0b0--- /dev/null+++ b/tests/test_compute_image_crops.py@@ -0,0 +1,220 @@+"""+Tests for the compute_image_crops tool.++This tool is pure computation (no API calls) and should return correct+centered crop boxes for any source image dimensions.+"""+import json+import math+import pytest+from meta_ads_mcp.core.ads import compute_image_crops, _compute_crop_box+++# ---------------------------------------------------------------------------+# _compute_crop_box — unit tests for the math+# ---------------------------------------------------------------------------++class TestComputeCropBox:+ """Verify the crop box geometry for various source/target ratio combos."""++ def _check_ratio(self, box, kw, kh, tolerance=0.02):+ """Assert the box has the right aspect ratio within tolerance."""+ x1, y1 = box[0]+ x2, y2 = box[1]+ width = x2 - x1+ height = y2 - y1+ actual = width / height+ expected = kw / kh+ assert abs(actual - expected) <= tolerance, (+ f"Ratio {actual:.4f} != expected {expected:.4f} for {kw}x{kh} on box {box}"+ )++ def _check_centered(self, box, src_w, src_h):+ """Assert the box is centered in the source image."""+ x1, y1 = box[0]+ x2, y2 = box[1]+ width = x2 - x1+ height = y2 - y1+ # Check symmetry: offsets on each side should differ by at most 1 pixel.+ left_pad = x1+ right_pad = src_w - x2+ top_pad = y1+ bottom_pad = src_h - y2+ assert abs(left_pad - right_pad) <= 1, f"Not horizontally centered: {box}"+ assert abs(top_pad - bottom_pad) <= 1, f"Not vertically centered: {box}"++ def _check_fits(self, box, src_w, src_h):+ """Assert the box fits within the source image."""+ x1, y1 = box[0]+ x2, y2 = box[1]+ assert x1 >= 0 and y1 >= 0, f"Box starts outside image: {box}"+ assert x2 <= src_w and y2 <= src_h, f"Box ends outside image: {box}"++ def test_square_source_100x100_key(self):+ """1080x1080 source + 100x100 key → full image."""+ box = _compute_crop_box(1080, 1080, 100, 100)+ assert box == [[0, 0], [1080, 1080]]++ def test_square_source_400x500_key(self):+ """1080x1080 source + 400x500 (4:5 portrait) → width cropped, full height."""+ box = _compute_crop_box(1080, 1080, 400, 500)+ x1, y1 = box[0]+ x2, y2 = box[1]+ assert y1 == 0 and y2 == 1080, "Should use full height"+ assert x1 > 0, "Should crop width"+ self._check_ratio(box, 400, 500)+ self._check_centered(box, 1080, 1080)+ self._check_fits(box, 1080, 1080)++ def test_square_source_600x360_key(self):+ """1080x1080 source + 600x360 (~1.67:1 landscape) → height cropped, full width."""+ box = _compute_crop_box(1080, 1080, 600, 360)+ x1, y1 = box[0]+ x2, y2 = box[1]+ assert x1 == 0 and x2 == 1080, "Should use full width"+ assert y1 > 0, "Should crop height"+ self._check_ratio(box, 600, 360)+ self._check_centered(box, 1080, 1080)+ self._check_fits(box, 1080, 1080)++ def test_wide_source_400x500_key(self):+ """Wide source (1920x1080) + 4:5 portrait key."""+ box = _compute_crop_box(1920, 1080, 400, 500)+ self._check_ratio(box, 400, 500)+ self._check_centered(box, 1920, 1080)+ self._check_fits(box, 1920, 1080)+ # Height should be capped at 1080+ assert box[1][1] == 1080++ def test_tall_source_600x360_key(self):+ """Tall source (1080x1920) + 600x360 landscape key."""+ box = _compute_crop_box(1080, 1920, 600, 360)+ self._check_ratio(box, 600, 360)+ self._check_centered(box, 1080, 1920)+ self._check_fits(box, 1080, 1920)+ # Width should be capped at 1080+ assert box[1][0] == 1080++ def test_all_valid_keys_on_square_source(self):+ """All 6 valid keys should produce valid boxes for a 1080x1080 source."""+ from meta_ads_mcp.core.ads import _VALID_CROP_KEYS+ for key, kw, kh in _VALID_CROP_KEYS:+ box = _compute_crop_box(1080, 1080, kw, kh)+ self._check_ratio(box, kw, kh)+ self._check_centered(box, 1080, 1080)+ self._check_fits(box, 1080, 1080)++ def test_non_square_source_100x100_key(self):+ """1200x628 (landscape) + 100x100 → height-limited square."""+ box = _compute_crop_box(1200, 628, 100, 100)+ x1, y1 = box[0]+ x2, y2 = box[1]+ assert y2 - y1 == 628, "Should use full height for square crop on landscape"+ assert x2 - x1 == 628+ self._check_centered(box, 1200, 628)+++# ---------------------------------------------------------------------------+# compute_image_crops — integration tests for the MCP tool+# ---------------------------------------------------------------------------++async def test_default_keys_1080x1080():+ """Default call returns all 6 keys for 1080x1080."""+ result_str = await compute_image_crops(image_width=1080, image_height=1080)+ result = json.loads(result_str)++ crops = result["image_crops"]+ assert set(crops.keys()) == {"100x100", "100x72", "400x500", "400x150", "600x360", "90x160"}++ # Spot-check the classic 1080x1080 values+ assert crops["100x100"] == [[0, 0], [1080, 1080]]+ # 400x500: width should be ~864, centered → x1=108+ x1, y1 = crops["400x500"][0]+ x2, y2 = crops["400x500"][1]+ assert y1 == 0 and y2 == 1080+ assert abs((x2 - x1) / (y2 - y1) - 400 / 500) < 0.02+++async def test_specific_keys():+ """Can request a subset of keys."""+ result_str = await compute_image_crops(+ image_width=1080, image_height=1080, crop_keys=["100x100", "600x360"]+ )+ result = json.loads(result_str)+ assert set(result["image_crops"].keys()) == {"100x100", "600x360"}+++async def test_invalid_key_produces_warning():+ """Requesting 191x100 (invalid) returns a warning and skips the key."""+ result_str = await compute_image_crops(+ image_width=1080, image_height=1080, crop_keys=["100x100", "191x100"]+ )+ result = json.loads(result_str)+ # 191x100 should be absent+ assert "191x100" not in result["image_crops"]+ # 100x100 should be present+ assert "100x100" in result["image_crops"]+ # Warning should mention 191x100+ assert "warnings" in result+ assert any("191x100" in w for w in result["warnings"])+++async def test_landscape_source_1200x628():+ """1200x628 (typical landscape) produces valid boxes."""+ result_str = await compute_image_crops(image_width=1200, image_height=628)+ result = json.loads(result_str)+ crops = result["image_crops"]++ # All boxes must fit within the source+ for key, box in crops.items():+ x1, y1 = box[0]+ x2, y2 = box[1]+ assert x1 >= 0 and y1 >= 0+ assert x2 <= 1200 and y2 <= 628, f"{key}: box {box} exceeds source"+++async def test_portrait_source_1080x1920():+ """1080x1920 (stories) produces valid boxes."""+ result_str = await compute_image_crops(image_width=1080, image_height=1920)+ result = json.loads(result_str)+ crops = result["image_crops"]++ for key, box in crops.items():+ x1, y1 = box[0]+ x2, y2 = box[1]+ assert x1 >= 0 and y1 >= 0+ assert x2 <= 1080 and y2 <= 1920, f"{key}: box {box} exceeds source"+++async def test_invalid_dimensions():+ """Negative or zero dimensions return an error."""+ result_str = await compute_image_crops(image_width=0, image_height=1080)+ result = json.loads(result_str)+ assert "error" in result++ result_str = await compute_image_crops(image_width=1080, image_height=-5)+ result = json.loads(result_str)+ assert "error" in result+++async def test_result_includes_usage_hint():+ """Result always includes a usage hint."""+ result_str = await compute_image_crops(image_width=1080, image_height=1080)+ result = json.loads(result_str)+ assert "usage" in result+ assert "create_ad_creative" in result["usage"]+++async def test_source_dimensions_echoed():+ """Result echoes the source dimensions for confirmation."""+ result_str = await compute_image_crops(image_width=1200, image_height=628)+ result = json.loads(result_str)+ assert result["source_dimensions"] == {"width": 1200, "height": 628}