Skip to content

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.

Refactor audience size estimation to enhance interest validation

Yves Junqueira5f0f9b3e2f67
diff --git a/meta_ads_mcp/core/targeting.py b/meta_ads_mcp/core/targeting.py
index 9b63770..85283d7 100644
--- a/meta_ads_mcp/core/targeting.py
+++ b/meta_ads_mcp/core/targeting.py
@@ -147,27 +147,16 @@ async def estimate_audience_size(
}
}, indent=2)
- # Build delivery estimate request
- endpoint = f"{account_id}/delivery_estimate"
+ # Build reach estimate request (using correct Meta API endpoint)
+ endpoint = f"{account_id}/reachestimate"
params = {
- "targeting": targeting,
- "optimization_goal": optimization_goal
+ "targeting_spec": targeting
}
- # Add basic campaign parameters for estimation
- if optimization_goal == "REACH":
- params["objective"] = "REACH"
- elif optimization_goal in ["LINK_CLICKS", "LANDING_PAGE_VIEWS"]:
- params["objective"] = "TRAFFIC"
- elif optimization_goal == "CONVERSIONS":
- params["objective"] = "CONVERSIONS"
- elif optimization_goal == "APP_INSTALLS":
- params["objective"] = "APP_INSTALLS"
- else:
- params["objective"] = "REACH" # Default fallback
+ # Note: reachestimate endpoint doesn't support optimization_goal or objective parameters
try:
- data = await make_api_request(endpoint, access_token, params, method="POST")
+ data = await make_api_request(endpoint, access_token, params, method="GET")
# Format the response for easier consumption
if "data" in data and len(data["data"]) > 0:
@@ -191,14 +180,69 @@ async def estimate_audience_size(
else:
return json.dumps({
"error": "No estimation data returned from Meta API",
- "raw_response": data
+ "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)
except Exception as e:
- return json.dumps({
- "error": f"Failed to get audience estimation: {str(e)}",
- "details": "Check targeting parameters and account permissions"
- }, indent=2)
+ # Check if this is the specific Business Manager system user permission error
+ error_str = str(e)
+ if "100" in error_str and "33" in error_str:
+ # Try to provide fallback estimation using individual interests if available
+ interests_found = []
+ if targeting and "interests" in targeting:
+ interests_found.extend([interest.get("id") for interest in targeting["interests"] if interest.get("id")])
+ elif targeting and "flexible_spec" in targeting:
+ for spec in targeting["flexible_spec"]:
+ if "interests" in spec:
+ interests_found.extend([interest.get("id") for interest in spec["interests"] if interest.get("id")])
+
+ if interests_found:
+ # Attempt to get individual interest data as fallback
+ try:
+ fallback_result = await estimate_audience_size(
+ access_token=access_token,
+ interest_fbid_list=interests_found
+ )
+ fallback_data = json.loads(fallback_result)
+
+ return json.dumps({
+ "comprehensive_targeting_failed": True,
+ "error_code": "100-33",
+ "fallback_used": True,
+ "details": {
+ "issue": "reachestimate endpoint returned error - possibly due to targeting parameters or account limitations",
+ "solution": "Individual interest validation used as fallback - comprehensive targeting may have specific requirements",
+ "endpoint_used": f"{account_id}/reachestimate"
+ },
+ "individual_interest_data": fallback_data,
+ "note": "Individual interest audience sizes provided as fallback. Comprehensive targeting via reachestimate endpoint failed."
+ }, indent=2)
+ except:
+ pass
+
+ return json.dumps({
+ "error": "reachestimate endpoint returned error (previously was incorrectly using delivery_estimate)",
+ "error_code": "100-33",
+ "details": {
+ "issue": "The endpoint returned an error, possibly due to targeting parameters or account limitations",
+ "endpoint_used": f"{account_id}/reachestimate",
+ "previous_issue": "Code was previously using non-existent delivery_estimate endpoint - now fixed",
+ "available_alternative": "Use interest_list or interest_fbid_list parameters for individual interest validation"
+ },
+ "raw_error": error_str
+ }, indent=2)
+ else:
+ return json.dumps({
+ "error": f"Failed to get audience estimation from reachestimate endpoint: {str(e)}",
+ "details": "Check targeting parameters and account permissions",
+ "error_type": "general_api_error",
+ "endpoint_used": f"{account_id}/reachestimate"
+ }, indent=2)
@mcp_server.tool()
diff --git a/tests/test_estimate_audience_size.py b/tests/test_estimate_audience_size.py
index 288f8ce..4562772 100644
--- a/tests/test_estimate_audience_size.py
+++ b/tests/test_estimate_audience_size.py
@@ -3,7 +3,7 @@
Unit tests for estimate_audience_size functionality in Meta Ads MCP.
This module tests the new estimate_audience_size function that replaces validate_interests
-and provides comprehensive audience estimation using Meta's delivery_estimate API.
+and provides comprehensive audience estimation using Meta's reachestimate API.
"""
import pytest
@@ -58,14 +58,12 @@ class TestEstimateAudienceSize:
# Verify API call
mock_api.assert_called_once_with(
- "act_123456789/delivery_estimate",
+ "act_123456789/reachestimate",
"test_token",
{
- "targeting": targeting_spec,
- "optimization_goal": "REACH",
- "objective": "REACH"
+ "targeting_spec": targeting_spec
},
- method="POST"
+ method="GET"
)
# Verify response format
@@ -80,7 +78,7 @@ class TestEstimateAudienceSize:
@pytest.mark.asyncio
async def test_different_optimization_goals(self):
- """Test audience estimation with different optimization goals"""
+ """Test audience estimation with different optimization goals (parameter is preserved in response)"""
mock_response = {
"data": [
{
@@ -98,19 +96,13 @@ class TestEstimateAudienceSize:
"geo_locations": {"countries": ["US"]}
}
- test_cases = [
- ("REACH", "REACH"),
- ("LINK_CLICKS", "TRAFFIC"),
- ("LANDING_PAGE_VIEWS", "TRAFFIC"),
- ("CONVERSIONS", "CONVERSIONS"),
- ("APP_INSTALLS", "APP_INSTALLS"),
- ("UNKNOWN_GOAL", "REACH") # Should fallback to REACH
- ]
+ # Test different optimization goals - they should all use the same reachestimate endpoint
+ test_goals = ["REACH", "LINK_CLICKS", "LANDING_PAGE_VIEWS", "CONVERSIONS", "APP_INSTALLS"]
with patch('meta_ads_mcp.core.targeting.make_api_request', new_callable=AsyncMock) as mock_api:
mock_api.return_value = mock_response
- for optimization_goal, expected_objective in test_cases:
+ for optimization_goal in test_goals:
mock_api.reset_mock()
result = await estimate_audience_size(
@@ -120,16 +112,14 @@ class TestEstimateAudienceSize:
optimization_goal=optimization_goal
)
- # Verify correct objective mapping
+ # Verify API call uses reachestimate endpoint with simplified parameters
mock_api.assert_called_once_with(
- "act_123456789/delivery_estimate",
+ "act_123456789/reachestimate",
"test_token",
{
- "targeting": targeting_spec,
- "optimization_goal": optimization_goal,
- "objective": expected_objective
+ "targeting_spec": targeting_spec
},
- method="POST"
+ method="GET"
)
result_data = json.loads(result)
@@ -316,7 +306,7 @@ class TestEstimateAudienceSize:
@pytest.mark.asyncio
async def test_api_error_handling(self):
- """Test handling of API errors from delivery_estimate"""
+ """Test handling of API errors from reachestimate"""
targeting_spec = {
"age_min": 25,
"age_max": 65,
@@ -338,12 +328,12 @@ class TestEstimateAudienceSize:
assert "data" in result_data
nested_data = json.loads(result_data["data"])
assert "error" in nested_data
- assert "Failed to get audience estimation" in nested_data["error"]
+ assert "Failed to get audience estimation from reachestimate endpoint" in nested_data["error"]
assert "details" in nested_data
@pytest.mark.asyncio
async def test_empty_api_response(self):
- """Test handling of empty response from delivery_estimate API"""
+ """Test handling of empty response from reachestimate API"""
targeting_spec = {
"age_min": 25,
"age_max": 65,
diff --git a/tests/test_estimate_audience_size_e2e.py b/tests/test_estimate_audience_size_e2e.py
index 7223ff6..f5a16be 100644
--- a/tests/test_estimate_audience_size_e2e.py
+++ b/tests/test_estimate_audience_size_e2e.py
@@ -614,7 +614,7 @@ class AudienceEstimationTester:
print(f"\n✅ Audience estimation tests: SUCCESS ({passed_tests}/{total_tests} passed)")
print(" • Comprehensive audience estimation is working")
print(" • Backwards compatibility is maintained")
- print(" • Meta delivery_estimate API integration is functional")
+ print(" • Meta reachestimate API integration is functional")
return True
else:
print(f"\n❌ Audience estimation tests: FAILED ({passed_tests}/{total_tests} passed)")