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
Enhance audience estimation functionality by adding preflight validation for targeting specifications. Implemented error handling for missing location or custom audience in the estimate_audience_size function, and introduced a fallback mechanism to delivery_estimate when reachestimate fails. Updated tests to cover new validation scenarios and ensure comprehensive error handling.
Yves Junqueira358f3a45076b
diff --git a/meta_ads_mcp/core/api.py b/meta_ads_mcp/core/api.pyindex 8ff12b8..c2be79a 100644--- a/meta_ads_mcp/core/api.py+++ b/meta_ads_mcp/core/api.py@@ -87,7 +87,14 @@ async def make_api_request(async with httpx.AsyncClient() as client:try:if method == "GET":- response = await client.get(url, params=request_params, headers=headers, timeout=30.0)+ # For GET, JSON-encode dict/list params (e.g., targeting_spec) to proper strings+ encoded_params = {}+ for key, value in request_params.items():+ if isinstance(value, (dict, list)):+ encoded_params[key] = json.dumps(value)+ else:+ encoded_params[key] = value+ response = await client.get(url, params=encoded_params, headers=headers, timeout=30.0)elif method == "POST":# For Meta API, POST requests need data, not JSONif 'targeting' in request_params and isinstance(request_params['targeting'], dict):diff --git a/meta_ads_mcp/core/targeting.py b/meta_ads_mcp/core/targeting.pyindex b50391e..9fd21a9 100644--- a/meta_ads_mcp/core/targeting.py+++ b/meta_ads_mcp/core/targeting.py@@ -2,6 +2,7 @@import jsonfrom typing import Optional, List, Dict, Any+import osfrom .api import meta_api_tool, make_api_requestfrom .server import mcp_server@@ -147,6 +148,49 @@ async def estimate_audience_size(}}, indent=2)+ # Preflight validation: require at least one location OR a custom audience+ def _has_location_or_custom_audience(t: Dict[str, Any]) -> bool:+ if not isinstance(t, dict):+ return False+ geo = t.get("geo_locations") or {}+ if isinstance(geo, dict):+ for key in [+ "countries",+ "regions",+ "cities",+ "zips",+ "geo_markets",+ "country_groups"+ ]:+ val = geo.get(key)+ if isinstance(val, list) and len(val) > 0:+ return True+ # Top-level custom audiences+ ca = t.get("custom_audiences")+ if isinstance(ca, list) and len(ca) > 0:+ return True+ # Custom audiences within flexible_spec+ flex = t.get("flexible_spec")+ if isinstance(flex, list):+ for spec in flex:+ if isinstance(spec, dict):+ ca_spec = spec.get("custom_audiences")+ if isinstance(ca_spec, list) and len(ca_spec) > 0:+ return True+ return False++ if not _has_location_or_custom_audience(targeting):+ return json.dumps({+ "error": "Missing target audience location",+ "details": "Select at least one location in targeting.geo_locations or include a custom audience.",+ "action_required": "Add geo_locations with countries/regions/cities/zips or include custom_audiences.",+ "example": {+ "geo_locations": {"countries": ["US"]},+ "age_min": 25,+ "age_max": 65+ }+ }, indent=2)+# Build reach estimate request (using correct Meta API endpoint)endpoint = f"{account_id}/reachestimate"params = {@@ -158,25 +202,153 @@ async def estimate_audience_size(try:data = await make_api_request(endpoint, access_token, params, method="GET")+ # Surface Graph API errors directly for better diagnostics.+ # If reachestimate fails, optionally attempt a fallback using delivery_estimate.+ if isinstance(data, dict) and "error" in data:+ # Special handling for Missing Target Audience Location error (subcode 1885364)+ try:+ err_wrapper = data.get("error", {})+ details_obj = err_wrapper.get("details", {})+ raw_err = details_obj.get("error", {}) if isinstance(details_obj, dict) else {}+ if (+ isinstance(raw_err, dict) and (+ raw_err.get("error_subcode") == 1885364 or+ raw_err.get("error_user_title") == "Missing Target Audience Location"+ )+ ):+ return json.dumps({+ "error": "Missing target audience location",+ "details": raw_err.get("error_user_msg") or "Select at least one location, or choose a custom audience.",+ "endpoint_used": f"{account_id}/reachestimate",+ "action_required": "Add geo_locations with at least one of countries/regions/cities/zips or include custom_audiences.",+ "blame_field_specs": raw_err.get("error_data", {}).get("blame_field_specs") if isinstance(raw_err.get("error_data"), dict) else None+ }, indent=2)+ except Exception:+ pass+ # Allow disabling fallback via environment variable+ # Default: fallback disabled unless explicitly enabled by setting DISABLE flag to "0"+ disable_fallback = os.environ.get("META_MCP_DISABLE_DELIVERY_FALLBACK", "1") == "1"+ if disable_fallback:+ return json.dumps({+ "error": "Graph API returned an error for reachestimate",+ "details": data.get("error"),+ "endpoint_used": f"{account_id}/reachestimate",+ "request_params": {+ "has_targeting_spec": bool(targeting),+ },+ "note": "delivery_estimate fallback disabled via META_MCP_DISABLE_DELIVERY_FALLBACK"+ }, indent=2)++ # Try fallback to delivery_estimate endpoint+ try:+ fallback_endpoint = f"{account_id}/delivery_estimate"+ fallback_params = {+ "targeting_spec": json.dumps(targeting),+ # Some API versions accept optimization_goal here+ "optimization_goal": optimization_goal+ }+ fallback_data = await make_api_request(fallback_endpoint, access_token, fallback_params, method="GET")++ # If fallback returns usable data, format similarly+ if isinstance(fallback_data, dict) and "data" in fallback_data and len(fallback_data["data"]) > 0:+ estimate_data = fallback_data["data"][0]+ formatted_response = {+ "success": True,+ "account_id": account_id,+ "targeting": targeting,+ "optimization_goal": optimization_goal,+ "estimated_audience_size": estimate_data.get("estimate_mau", 0),+ "estimate_details": {+ "monthly_active_users": estimate_data.get("estimate_mau", 0),+ "daily_outcomes_curve": estimate_data.get("estimate_dau", []),+ "bid_estimate": estimate_data.get("bid_estimates", {}),+ "unsupported_targeting": estimate_data.get("unsupported_targeting", [])+ },+ "raw_response": fallback_data,+ "fallback_endpoint_used": "delivery_estimate"+ }+ return json.dumps(formatted_response, indent=2)++ # Fallback returned but not in expected format+ return json.dumps({+ "error": "Graph API returned an error for reachestimate; delivery_estimate fallback did not return usable data",+ "reachestimate_error": data.get("error"),+ "fallback_endpoint_used": "delivery_estimate",+ "fallback_raw_response": fallback_data,+ "endpoint_used": f"{account_id}/reachestimate",+ "request_params": {+ "has_targeting_spec": bool(targeting)+ }+ }, indent=2)+ except Exception as _fallback_exc:+ return json.dumps({+ "error": "Graph API returned an error for reachestimate; delivery_estimate fallback also failed",+ "reachestimate_error": data.get("error"),+ "fallback_endpoint_used": "delivery_estimate",+ "fallback_exception": str(_fallback_exc),+ "endpoint_used": f"{account_id}/reachestimate",+ "request_params": {+ "has_targeting_spec": bool(targeting)+ }+ }, indent=2)+# Format the response for easier consumption- if "data" in data and len(data["data"]) > 0:- estimate_data = data["data"][0]- formatted_response = {- "success": True,- "account_id": account_id,- "targeting": targeting,- "optimization_goal": optimization_goal,- "estimated_audience_size": estimate_data.get("estimate_mau", 0),- "estimate_details": {- "monthly_active_users": estimate_data.get("estimate_mau", 0),- "daily_outcomes_curve": estimate_data.get("estimate_dau", []),- "bid_estimate": estimate_data.get("bid_estimates", {}),- "unsupported_targeting": estimate_data.get("unsupported_targeting", [])- },- "raw_response": data- }-- return json.dumps(formatted_response, indent=2)+ if "data" in data:+ response_data = data["data"]+ # Case 1: delivery_estimate-like list structure+ if isinstance(response_data, list) and len(response_data) > 0:+ estimate_data = response_data[0]+ formatted_response = {+ "success": True,+ "account_id": account_id,+ "targeting": targeting,+ "optimization_goal": optimization_goal,+ "estimated_audience_size": estimate_data.get("estimate_mau", 0),+ "estimate_details": {+ "monthly_active_users": estimate_data.get("estimate_mau", 0),+ "daily_outcomes_curve": estimate_data.get("estimate_dau", []),+ "bid_estimate": estimate_data.get("bid_estimates", {}),+ "unsupported_targeting": estimate_data.get("unsupported_targeting", [])+ },+ "raw_response": data+ }+ return json.dumps(formatted_response, indent=2)+ # Case 1b: explicit handling for empty list responses+ if isinstance(response_data, list) and len(response_data) == 0:+ return json.dumps({+ "error": "No estimation data returned from Meta API",+ "raw_response": data,+ "debug_info": {+ "response_keys": list(data.keys()) if isinstance(data, dict) else "not_a_dict",+ "response_type": str(type(data)),+ "endpoint_used": f"{account_id}/reachestimate"+ }+ }, indent=2)+ # Case 2: reachestimate dict structure with bounds+ if isinstance(response_data, dict):+ lower = response_data.get("users_lower_bound", response_data.get("estimate_mau_lower_bound"))+ upper = response_data.get("users_upper_bound", response_data.get("estimate_mau_upper_bound"))+ estimate_ready = response_data.get("estimate_ready")+ midpoint = None+ try:+ if isinstance(lower, (int, float)) and isinstance(upper, (int, float)):+ midpoint = int((lower + upper) / 2)+ except Exception:+ midpoint = None+ formatted_response = {+ "success": True,+ "account_id": account_id,+ "targeting": targeting,+ "optimization_goal": optimization_goal,+ "estimated_audience_size": midpoint if midpoint is not None else 0,+ "estimate_details": {+ "users_lower_bound": lower,+ "users_upper_bound": upper,+ "estimate_ready": estimate_ready+ },+ "raw_response": data+ }+ return json.dumps(formatted_response, indent=2)else:return json.dumps({"error": "No estimation data returned from Meta API",@@ -189,6 +361,40 @@ async def estimate_audience_size(}, indent=2)except Exception as e:+ # Try fallback to delivery_estimate first when an exception occurs (unless disabled)+ # Default: fallback disabled unless explicitly enabled by setting DISABLE flag to "0"+ disable_fallback = os.environ.get("META_MCP_DISABLE_DELIVERY_FALLBACK", "1") == "1"+ if not disable_fallback:+ try:+ fallback_endpoint = f"{account_id}/delivery_estimate"+ fallback_params = {+ "targeting_spec": json.dumps(targeting) if isinstance(targeting, dict) else targeting,+ "optimization_goal": optimization_goal+ }+ fallback_data = await make_api_request(fallback_endpoint, access_token, fallback_params, method="GET")++ if isinstance(fallback_data, dict) and "data" in fallback_data and len(fallback_data["data"]) > 0:+ estimate_data = fallback_data["data"][0]+ formatted_response = {+ "success": True,+ "account_id": account_id,+ "targeting": targeting,+ "optimization_goal": optimization_goal,+ "estimated_audience_size": estimate_data.get("estimate_mau", 0),+ "estimate_details": {+ "monthly_active_users": estimate_data.get("estimate_mau", 0),+ "daily_outcomes_curve": estimate_data.get("estimate_dau", []),+ "bid_estimate": estimate_data.get("bid_estimates", {}),+ "unsupported_targeting": estimate_data.get("unsupported_targeting", [])+ },+ "raw_response": fallback_data,+ "fallback_endpoint_used": "delivery_estimate"+ }+ return json.dumps(formatted_response, indent=2)+ except Exception as _fallback_exc:+ # If fallback also fails, proceed to detailed error handling below+ pass+# Check if this is the specific Business Manager system user permission errorerror_str = str(e)if "100" in error_str and "33" in error_str:diff --git a/tests/test_estimate_audience_size_e2e.py b/tests/test_estimate_audience_size_e2e.pyindex f5a16be..ec0758f 100644--- a/tests/test_estimate_audience_size_e2e.py+++ b/tests/test_estimate_audience_size_e2e.py@@ -207,6 +207,82 @@ class AudienceEstimationTester:return None+ def test_pl_only_reachestimate_bounds(self) -> Dict[str, Any]:+ """Verify PL-only reachestimate returns expected bounds and midpoint.++ Prerequisite: Start server with fallback disabled so reachestimate is used directly.+ Example:+ export META_MCP_DISABLE_DELIVERY_FALLBACK=1+ uv run python -m meta_ads_mcp --transport streamable-http --port 8080+ """+ print(f"\n🇵🇱 Testing PL-only reachestimate bounds (fallback disabled)")+ local_account_id = "act_3182643988557192"+ targeting_spec = {"geo_locations": {"countries": ["PL"]}}+ expected_lower = 18600000+ expected_upper = 21900000+ expected_midpoint = 20250000++ result = self._make_request("tools/call", {+ "name": "estimate_audience_size",+ "arguments": {+ "account_id": local_account_id,+ "targeting": targeting_spec,+ "optimization_goal": "REACH"+ }+ })++ if not result["success"]:+ print(f" ❌ Request failed: {result.get('text', 'Unknown error')}")+ return {"success": False, "error": result.get("text", "Unknown error")}++ response_data = result["json"]["result"]+ content = response_data.get("content", [{}])[0].get("text", "")+ try:+ parsed_content = json.loads(content)+ except json.JSONDecodeError:+ print(f" ❌ Invalid JSON response")+ return {"success": False, "error": "Invalid JSON"}++ error_info = self._check_for_errors(parsed_content)+ if error_info["has_error"]:+ print(f" ❌ API Error: {error_info['error_message']}")+ return {"success": False, "error": error_info["error_message"], "error_format": error_info["format"]}++ if not parsed_content.get("success", False):+ print(f" ❌ Response indicates failure but no error message found")+ return {"success": False, "error": "Unexpected failure"}++ details = parsed_content.get("estimate_details", {}) or {}+ lower = details.get("users_lower_bound")+ upper = details.get("users_upper_bound")+ midpoint = parsed_content.get("estimated_audience_size")+ fallback_used = parsed_content.get("fallback_endpoint_used")++ ok = (+ lower == expected_lower and+ upper == expected_upper and+ midpoint == expected_midpoint and+ (fallback_used is None)+ )++ if ok:+ print(f" ✅ Bounds: {lower:,}–{upper:,}; midpoint: {midpoint:,}")+ return {+ "success": True,+ "users_lower_bound": lower,+ "users_upper_bound": upper,+ "midpoint": midpoint+ }+ else:+ print(f" ❌ Unexpected values: lower={lower}, upper={upper}, midpoint={midpoint}, fallback={fallback_used}")+ return {+ "success": False,+ "users_lower_bound": lower,+ "users_upper_bound": upper,+ "midpoint": midpoint,+ "fallback_endpoint_used": fallback_used+ }+def test_comprehensive_audience_estimation(self) -> Dict[str, Any]:"""Test comprehensive audience estimation with complex targeting"""@@ -491,6 +567,24 @@ class AudienceEstimationTester:results["invalid_targeting"] = self._parse_error_response(result, "Should handle invalid targeting")+ # Test 4: Missing location in targeting (no geo_locations or custom audiences)+ print(f" 🚫 Testing missing location in targeting")+ result = self._make_request("tools/call", {+ "name": "estimate_audience_size",+ "arguments": {+ "account_id": self.account_id,+ # Interests present but no geo_locations and no custom_audiences+ "targeting": {+ "age_min": 18,+ "age_max": 35,+ "flexible_spec": [+ {"interests": [{"id": "6003371567474"}]}+ ]+ }+ }+ })+ results["missing_location"] = self._parse_error_response(result, "Should require a location or custom audience")+return resultsdef _parse_error_response(self, result: Dict[str, Any], description: str) -> Dict[str, Any]:@@ -546,6 +640,13 @@ class AudienceEstimationTester:print("🔐 Using implicit authentication from server")print(f"🏢 Using account ID: {self.account_id}")+ # Test 0: PL-only reachestimate bounds verification+ print("\n" + "="*70)+ print("📋 PHASE 0: PL-only reachestimate bounds verification (fallback disabled)")+ print("="*70)+ pl_only_results = self.test_pl_only_reachestimate_bounds()+ pl_only_success = pl_only_results.get("success", False)+# Test 1: Comprehensive Audience Estimationprint("\n" + "="*70)print("📋 PHASE 1: Testing Comprehensive Audience Estimation")@@ -595,6 +696,7 @@ class AudienceEstimationTester:print("="*70)all_tests = [+ ("PL-only Reachestimate Bounds", pl_only_success),("Comprehensive Estimation", comprehensive_success),("Backwards Compatibility", compat_success),("Optimization Goals", goals_success),diff --git a/tests/test_insights_actions_and_values.py b/tests/test_insights_actions_and_values_e2e.pysimilarity index 79%rename from tests/test_insights_actions_and_values.pyrename to tests/test_insights_actions_and_values_e2e.pyindex df5ce93..7348579 100644--- a/tests/test_insights_actions_and_values.py+++ b/tests/test_insights_actions_and_values_e2e.py@@ -16,6 +16,7 @@ Test cases cover:import pytestimport jsonimport asyncio+import requestsfrom unittest.mock import AsyncMock, patch, MagicMockfrom typing import Dict, Any, List@@ -385,24 +386,108 @@ class TestInsightsActionsAndValues:assert 'lead' in action_value_types, "Lead action_value type not found"-class TestInsightsActionsAndValuesIntegration:- """Integration tests for actions and action_values functionality"""[email protected](reason="E2E test - run manually only")+class TestInsightsActionsAndValuesE2E:+ """E2E tests for actions and action_values via MCP HTTP server"""- @pytest.mark.asyncio- async def test_actions_workflow(self):- """Test complete workflow with actions and action_values"""-- # This test would require actual API credentials and would be skipped in CI- # It's included for manual testing with real data- pytest.skip("Integration test requires real API credentials")-- # Example workflow:- # 1. Get campaign insights with actions and action_values- # 2. Verify the data structure- # 3. Check that purchase data is present in actions and action_values- # 4. Validate the values make sense-- pass+ def __init__(self, base_url: str = "http://localhost:8080"):+ self.base_url = base_url.rstrip('/')+ self.endpoint = f"{self.base_url}/mcp/"+ self.request_id = 1+ # Default account from workspace rules+ self.account_id = "act_701351919139047"++ def _make_request(self, method: str, params: Dict[str, Any] = None) -> Dict[str, Any]:+ headers = {+ "Content-Type": "application/json",+ "Accept": "application/json, text/event-stream",+ "User-Agent": "Insights-E2E-Test-Client/1.0"+ }+ payload = {+ "jsonrpc": "2.0",+ "method": method,+ "id": self.request_id+ }+ if params:+ payload["params"] = params+ try:+ resp = requests.post(self.endpoint, headers=headers, json=payload, timeout=30)+ self.request_id += 1+ return {+ "status_code": resp.status_code,+ "json": resp.json() if resp.status_code == 200 else None,+ "text": resp.text,+ "success": resp.status_code == 200+ }+ except requests.exceptions.RequestException as e:+ return {"status_code": 0, "json": None, "text": str(e), "success": False, "error": str(e)}++ def _check_for_errors(self, parsed_content: Dict[str, Any]) -> Dict[str, Any]:+ if "data" in parsed_content:+ data = parsed_content["data"]+ if isinstance(data, dict) and 'error' in data:+ return {"has_error": True, "error_message": data['error'], "format": "wrapped_dict"}+ if isinstance(data, str):+ try:+ error_data = json.loads(data)+ if 'error' in error_data:+ return {"has_error": True, "error_message": error_data['error'], "format": "wrapped_json"}+ except json.JSONDecodeError:+ pass+ if 'error' in parsed_content:+ return {"has_error": True, "error_message": parsed_content['error'], "format": "direct"}+ return {"has_error": False}++ def test_tool_exists_and_has_required_fields(self):+ result = self._make_request("tools/list", {})+ assert result["success"], f"tools/list failed: {result.get('text', '')}"+ tools = result["json"]["result"].get("tools", [])+ tool = next((t for t in tools if t["name"] == "get_insights"), None)+ assert tool is not None, "get_insights tool not found"+ props = tool.get("inputSchema", {}).get("properties", {})+ for req in ["object_id", "time_range", "breakdown", "level"]:+ assert req in props, f"Missing parameter in schema: {req}"++ def test_get_insights_account_level(self):+ params = {+ "name": "get_insights",+ "arguments": {+ "object_id": self.account_id,+ "time_range": "last_30d",+ "level": "account"+ }+ }+ result = self._make_request("tools/call", params)+ assert result["success"], f"tools/call failed: {result.get('text', '')}"+ response_data = result["json"]["result"]+ content = response_data.get("content", [{}])[0].get("text", "")+ parsed = json.loads(content)+ err = self._check_for_errors(parsed)+ # Don't fail if auth or permissions block; just assert structure is parsable+ if err["has_error"]:+ assert isinstance(err["error_message"], (str, dict))+ else:+ # Expect data list on success+ data = parsed.get("data") if isinstance(parsed, dict) else None+ assert data is not None++def main():+ tester = TestInsightsActionsAndValuesE2E()+ print("🚀 Insights Actions E2E (manual)")+ # Basic smoke run+ try:+ tester.test_tool_exists_and_has_required_fields()+ print("✅ Tool schema ok")+ tester.test_get_insights_account_level()+ print("✅ Account-level insights request executed")+ except AssertionError as e:+ print(f"❌ Assertion failed: {e}")+ except Exception as e:+ print(f"❌ Error: {e}")++if __name__ == "__main__":+ main()def extract_purchase_data(insights_data):