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 interest validation to estimate audience size

Yves Junqueira220b2996d39b
diff --git a/meta_ads_mcp/__init__.py b/meta_ads_mcp/__init__.py
index 4675573..a3c1657 100644
--- a/meta_ads_mcp/__init__.py
+++ b/meta_ads_mcp/__init__.py
@@ -29,7 +29,7 @@ __all__ = [
'main',
'search_interests',
'get_interest_suggestions',
- 'validate_interests',
+ 'estimate_audience_size',
'search_behaviors',
'search_demographics',
'search_geo_locations'
@@ -56,7 +56,7 @@ from .core import (
main,
search_interests,
get_interest_suggestions,
- validate_interests,
+ estimate_audience_size,
search_behaviors,
search_demographics,
search_geo_locations
diff --git a/meta_ads_mcp/core/__init__.py b/meta_ads_mcp/core/__init__.py
index f288f58..ea27552 100644
--- a/meta_ads_mcp/core/__init__.py
+++ b/meta_ads_mcp/core/__init__.py
@@ -11,7 +11,7 @@ from .server import login_cli, main
from .auth import login
from . import ads_library # Import module to register conditional tools
from .budget_schedules import create_budget_schedule
-from .targeting import search_interests, get_interest_suggestions, validate_interests, search_behaviors, search_demographics, search_geo_locations
+from .targeting import search_interests, get_interest_suggestions, estimate_audience_size, search_behaviors, search_demographics, search_geo_locations
from . import reports # Import module to register conditional tools
from . import duplication # Import module to register conditional duplication tools
from .openai_deep_research import search, fetch # OpenAI MCP Deep Research tools
@@ -39,7 +39,7 @@ __all__ = [
'create_budget_schedule',
'search_interests',
'get_interest_suggestions',
- 'validate_interests',
+ 'estimate_audience_size',
'search_behaviors',
'search_demographics',
'search_geo_locations',
diff --git a/meta_ads_mcp/core/targeting.py b/meta_ads_mcp/core/targeting.py
index 135fd2b..9b63770 100644
--- a/meta_ads_mcp/core/targeting.py
+++ b/meta_ads_mcp/core/targeting.py
@@ -66,36 +66,139 @@ async def get_interest_suggestions(access_token: str = None, interest_list: List
@mcp_server.tool()
@meta_api_tool
-async def validate_interests(access_token: str = None, interest_list: List[str] = None,
- interest_fbid_list: List[str] = None) -> str:
+async def estimate_audience_size(
+ access_token: str = None,
+ account_id: str = None,
+ targeting: Dict[str, Any] = None,
+ optimization_goal: str = "REACH",
+ # Backwards compatibility for simple interest validation
+ interest_list: List[str] = None,
+ interest_fbid_list: List[str] = None
+) -> str:
"""
- Validate interest names or IDs for targeting.
+ Estimate audience size for targeting specifications using Meta's delivery_estimate API.
+
+ This function provides comprehensive audience estimation for complex targeting combinations
+ including demographics, geography, interests, and behaviors. It also maintains backwards
+ compatibility for simple interest validation.
Args:
access_token: Meta API access token (optional - will use cached token if not provided)
- interest_list: List of interest names to validate (e.g., ["Japan", "Basketball"])
- interest_fbid_list: List of interest IDs to validate (e.g., ["6003700426513"])
+ account_id: Meta Ads account ID (format: act_XXXXXXXXX) - required for comprehensive estimation
+ targeting: Complete targeting specification including demographics, geography, interests, etc.
+ Example: {
+ "age_min": 25,
+ "age_max": 65,
+ "geo_locations": {"countries": ["PL"]},
+ "flexible_spec": [
+ {"interests": [{"id": "6003371567474"}]},
+ {"interests": [{"id": "6003462346642"}]}
+ ]
+ }
+ optimization_goal: Optimization goal for estimation (default: "REACH").
+ Options: "REACH", "LINK_CLICKS", "IMPRESSIONS", "CONVERSIONS", etc.
+ interest_list: [DEPRECATED - for backwards compatibility] List of interest names to validate
+ interest_fbid_list: [DEPRECATED - for backwards compatibility] List of interest IDs to validate
Returns:
- JSON string with validation results showing valid status and audience_size for each interest
+ JSON string with audience estimation results including estimated_audience_size,
+ reach_estimate, and targeting validation
"""
- if not interest_list and not interest_fbid_list:
- return json.dumps({"error": "No interest list or FBID list provided"}, indent=2)
+ # Handle backwards compatibility - simple interest validation
+ # Check if we're in backwards compatibility mode (interest params provided OR no comprehensive params)
+ is_backwards_compatible_call = (interest_list or interest_fbid_list) or (not account_id and not targeting)
- endpoint = "search"
+ if is_backwards_compatible_call and not targeting:
+ if not interest_list and not interest_fbid_list:
+ return json.dumps({"error": "No interest list or FBID list provided"}, indent=2)
+
+ endpoint = "search"
+ params = {
+ "type": "adinterestvalid"
+ }
+
+ if interest_list:
+ params["interest_list"] = json.dumps(interest_list)
+
+ if interest_fbid_list:
+ params["interest_fbid_list"] = json.dumps(interest_fbid_list)
+
+ data = await make_api_request(endpoint, access_token, params)
+
+ return json.dumps(data, indent=2)
+
+ # Comprehensive audience estimation using delivery_estimate API
+ if not account_id:
+ return json.dumps({
+ "error": "account_id is required for comprehensive audience estimation",
+ "details": "For simple interest validation, use interest_list or interest_fbid_list parameters"
+ }, indent=2)
+
+ if not targeting:
+ return json.dumps({
+ "error": "targeting specification is required for comprehensive audience estimation",
+ "example": {
+ "age_min": 25,
+ "age_max": 65,
+ "geo_locations": {"countries": ["US"]},
+ "flexible_spec": [
+ {"interests": [{"id": "6003371567474"}]}
+ ]
+ }
+ }, indent=2)
+
+ # Build delivery estimate request
+ endpoint = f"{account_id}/delivery_estimate"
params = {
- "type": "adinterestvalid"
+ "targeting": targeting,
+ "optimization_goal": optimization_goal
}
- if interest_list:
- params["interest_list"] = json.dumps(interest_list)
-
- if interest_fbid_list:
- params["interest_fbid_list"] = json.dumps(interest_fbid_list)
+ # 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
- data = await make_api_request(endpoint, access_token, params)
+ try:
+ data = await make_api_request(endpoint, access_token, params, method="POST")
+
+ # 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)
+ else:
+ return json.dumps({
+ "error": "No estimation data returned from Meta API",
+ "raw_response": data
+ }, indent=2)
- return json.dumps(data, 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)
@mcp_server.tool()
diff --git a/tests/test_estimate_audience_size.py b/tests/test_estimate_audience_size.py
new file mode 100644
index 0000000..288f8ce
--- /dev/null
+++ b/tests/test_estimate_audience_size.py
@@ -0,0 +1,482 @@
+#!/usr/bin/env python3
+"""
+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.
+"""
+
+import pytest
+import json
+from unittest.mock import AsyncMock, patch
+
+from meta_ads_mcp.core.targeting import estimate_audience_size
+
+
+class TestEstimateAudienceSize:
+ """Test cases for estimate_audience_size function"""
+
+ @pytest.mark.asyncio
+ async def test_comprehensive_audience_estimation_success(self):
+ """Test successful comprehensive audience estimation with complex targeting"""
+ mock_response = {
+ "data": [
+ {
+ "estimate_mau": 1500000,
+ "estimate_dau": [
+ {"min_reach": 100000, "max_reach": 150000, "bid": 100},
+ {"min_reach": 200000, "max_reach": 250000, "bid": 200}
+ ],
+ "bid_estimates": {
+ "median": 150,
+ "min": 50,
+ "max": 300
+ },
+ "unsupported_targeting": []
+ }
+ ]
+ }
+
+ targeting_spec = {
+ "age_min": 25,
+ "age_max": 65,
+ "geo_locations": {"countries": ["US"]},
+ "flexible_spec": [
+ {"interests": [{"id": "6003371567474"}]}
+ ]
+ }
+
+ with patch('meta_ads_mcp.core.targeting.make_api_request', new_callable=AsyncMock) as mock_api:
+ mock_api.return_value = mock_response
+
+ result = await estimate_audience_size(
+ access_token="test_token",
+ account_id="act_123456789",
+ targeting=targeting_spec,
+ optimization_goal="REACH"
+ )
+
+ # Verify API call
+ mock_api.assert_called_once_with(
+ "act_123456789/delivery_estimate",
+ "test_token",
+ {
+ "targeting": targeting_spec,
+ "optimization_goal": "REACH",
+ "objective": "REACH"
+ },
+ method="POST"
+ )
+
+ # Verify response format
+ result_data = json.loads(result)
+ assert result_data["success"] is True
+ assert result_data["account_id"] == "act_123456789"
+ assert result_data["targeting"] == targeting_spec
+ assert result_data["optimization_goal"] == "REACH"
+ assert result_data["estimated_audience_size"] == 1500000
+ assert "estimate_details" in result_data
+ assert result_data["estimate_details"]["monthly_active_users"] == 1500000
+
+ @pytest.mark.asyncio
+ async def test_different_optimization_goals(self):
+ """Test audience estimation with different optimization goals"""
+ mock_response = {
+ "data": [
+ {
+ "estimate_mau": 800000,
+ "estimate_dau": [],
+ "bid_estimates": {},
+ "unsupported_targeting": []
+ }
+ ]
+ }
+
+ targeting_spec = {
+ "age_min": 18,
+ "age_max": 45,
+ "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
+ ]
+
+ 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:
+ mock_api.reset_mock()
+
+ result = await estimate_audience_size(
+ access_token="test_token",
+ account_id="act_123456789",
+ targeting=targeting_spec,
+ optimization_goal=optimization_goal
+ )
+
+ # Verify correct objective mapping
+ mock_api.assert_called_once_with(
+ "act_123456789/delivery_estimate",
+ "test_token",
+ {
+ "targeting": targeting_spec,
+ "optimization_goal": optimization_goal,
+ "objective": expected_objective
+ },
+ method="POST"
+ )
+
+ result_data = json.loads(result)
+ assert result_data["success"] is True
+ assert result_data["optimization_goal"] == optimization_goal
+
+ @pytest.mark.asyncio
+ async def test_backwards_compatibility_interest_names(self):
+ """Test backwards compatibility with interest name validation"""
+ mock_response = {
+ "data": [
+ {
+ "name": "Japan",
+ "valid": True,
+ "id": 6003700426513,
+ "audience_size": 68310258
+ },
+ {
+ "name": "invalidinterest",
+ "valid": False
+ }
+ ]
+ }
+
+ with patch('meta_ads_mcp.core.targeting.make_api_request', new_callable=AsyncMock) as mock_api:
+ mock_api.return_value = mock_response
+
+ result = await estimate_audience_size(
+ access_token="test_token",
+ interest_list=["Japan", "invalidinterest"]
+ )
+
+ # Verify it uses the old validation API
+ mock_api.assert_called_once_with(
+ "search",
+ "test_token",
+ {
+ "type": "adinterestvalid",
+ "interest_list": '["Japan", "invalidinterest"]'
+ }
+ )
+
+ # Verify response matches old format
+ result_data = json.loads(result)
+ assert result_data == mock_response
+ assert result_data["data"][0]["valid"] is True
+ assert result_data["data"][1]["valid"] is False
+
+ @pytest.mark.asyncio
+ async def test_backwards_compatibility_interest_fbids(self):
+ """Test backwards compatibility with interest FBID validation"""
+ mock_response = {
+ "data": [
+ {
+ "id": "6003700426513",
+ "valid": True,
+ "audience_size": 68310258
+ }
+ ]
+ }
+
+ with patch('meta_ads_mcp.core.targeting.make_api_request', new_callable=AsyncMock) as mock_api:
+ mock_api.return_value = mock_response
+
+ result = await estimate_audience_size(
+ access_token="test_token",
+ interest_fbid_list=["6003700426513"]
+ )
+
+ # Verify it uses the old validation API
+ mock_api.assert_called_once_with(
+ "search",
+ "test_token",
+ {
+ "type": "adinterestvalid",
+ "interest_fbid_list": '["6003700426513"]'
+ }
+ )
+
+ # Verify response matches old format
+ result_data = json.loads(result)
+ assert result_data == mock_response
+ assert result_data["data"][0]["valid"] is True
+
+ @pytest.mark.asyncio
+ async def test_backwards_compatibility_both_interest_params(self):
+ """Test backwards compatibility with both interest names and FBIDs"""
+ mock_response = {
+ "data": [
+ {"name": "Japan", "valid": True, "id": 6003700426513, "audience_size": 68310258},
+ {"id": "6003397425735", "valid": True, "audience_size": 12345678}
+ ]
+ }
+
+ with patch('meta_ads_mcp.core.targeting.make_api_request', new_callable=AsyncMock) as mock_api:
+ mock_api.return_value = mock_response
+
+ result = await estimate_audience_size(
+ access_token="test_token",
+ interest_list=["Japan"],
+ interest_fbid_list=["6003397425735"]
+ )
+
+ # Verify both parameters are passed
+ mock_api.assert_called_once_with(
+ "search",
+ "test_token",
+ {
+ "type": "adinterestvalid",
+ "interest_list": '["Japan"]',
+ "interest_fbid_list": '["6003397425735"]'
+ }
+ )
+
+ result_data = json.loads(result)
+ assert result_data == mock_response
+
+ @pytest.mark.asyncio
+ async def test_error_no_account_id_for_comprehensive(self):
+ """Test error when account_id missing for comprehensive estimation"""
+ targeting_spec = {
+ "age_min": 25,
+ "age_max": 65,
+ "geo_locations": {"countries": ["US"]}
+ }
+
+ result = await estimate_audience_size(
+ access_token="test_token",
+ targeting=targeting_spec
+ )
+
+ result_data = json.loads(result)
+ # The @meta_api_tool decorator wraps errors in a 'data' field
+ assert "data" in result_data
+ nested_data = json.loads(result_data["data"])
+ assert "error" in nested_data
+ assert "account_id is required" in nested_data["error"]
+ assert "details" in nested_data
+
+ @pytest.mark.asyncio
+ async def test_error_no_targeting_for_comprehensive(self):
+ """Test error when targeting missing for comprehensive estimation"""
+ result = await estimate_audience_size(
+ access_token="test_token",
+ account_id="act_123456789"
+ )
+
+ result_data = json.loads(result)
+ # The @meta_api_tool decorator wraps errors in a 'data' field
+ assert "data" in result_data
+ nested_data = json.loads(result_data["data"])
+ assert "error" in nested_data
+ assert "targeting specification is required" in nested_data["error"]
+ assert "example" in nested_data
+
+ @pytest.mark.asyncio
+ async def test_error_no_parameters(self):
+ """Test error when no parameters provided"""
+ # Since we're using the @meta_api_tool decorator, we need to simulate
+ # its behavior for error handling
+ with patch('meta_ads_mcp.core.api.get_current_access_token') as mock_auth:
+ mock_auth.return_value = "test_token"
+
+ result = await estimate_audience_size()
+
+ result_data = json.loads(result)
+ # The @meta_api_tool decorator wraps errors in a 'data' field
+ assert "data" in result_data
+ nested_data = json.loads(result_data["data"])
+ assert "error" in nested_data
+
+ @pytest.mark.asyncio
+ async def test_error_backwards_compatibility_no_interests(self):
+ """Test error in backwards compatibility mode with no interest parameters"""
+ result = await estimate_audience_size(
+ access_token="test_token"
+ )
+
+ result_data = json.loads(result)
+ # The @meta_api_tool decorator wraps errors in a 'data' field
+ assert "data" in result_data
+ nested_data = json.loads(result_data["data"])
+ assert "error" in nested_data
+
+ @pytest.mark.asyncio
+ async def test_api_error_handling(self):
+ """Test handling of API errors from delivery_estimate"""
+ targeting_spec = {
+ "age_min": 25,
+ "age_max": 65,
+ "geo_locations": {"countries": ["US"]}
+ }
+
+ # Simulate API exception
+ with patch('meta_ads_mcp.core.targeting.make_api_request', new_callable=AsyncMock) as mock_api:
+ mock_api.side_effect = Exception("API connection failed")
+
+ result = await estimate_audience_size(
+ access_token="test_token",
+ account_id="act_123456789",
+ targeting=targeting_spec
+ )
+
+ result_data = json.loads(result)
+ # The @meta_api_tool decorator wraps errors in a 'data' field
+ 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 "details" in nested_data
+
+ @pytest.mark.asyncio
+ async def test_empty_api_response(self):
+ """Test handling of empty response from delivery_estimate API"""
+ targeting_spec = {
+ "age_min": 25,
+ "age_max": 65,
+ "geo_locations": {"countries": ["US"]}
+ }
+
+ # Simulate empty API response
+ mock_response = {"data": []}
+
+ with patch('meta_ads_mcp.core.targeting.make_api_request', new_callable=AsyncMock) as mock_api:
+ mock_api.return_value = mock_response
+
+ result = await estimate_audience_size(
+ access_token="test_token",
+ account_id="act_123456789",
+ targeting=targeting_spec
+ )
+
+ result_data = json.loads(result)
+ # The @meta_api_tool decorator wraps errors in a 'data' field
+ assert "data" in result_data
+ nested_data = json.loads(result_data["data"])
+ assert "error" in nested_data
+ assert "No estimation data returned" in nested_data["error"]
+ assert "raw_response" in nested_data
+
+ @pytest.mark.asyncio
+ async def test_comprehensive_estimation_with_minimal_targeting(self):
+ """Test comprehensive estimation with minimal targeting requirements"""
+ mock_response = {
+ "data": [
+ {
+ "estimate_mau": 500000,
+ "estimate_dau": [],
+ "bid_estimates": {},
+ "unsupported_targeting": []
+ }
+ ]
+ }
+
+ minimal_targeting = {
+ "age_min": 18,
+ "age_max": 65,
+ "geo_locations": {"countries": ["US"]}
+ }
+
+ with patch('meta_ads_mcp.core.targeting.make_api_request', new_callable=AsyncMock) as mock_api:
+ mock_api.return_value = mock_response
+
+ result = await estimate_audience_size(
+ access_token="test_token",
+ account_id="act_123456789",
+ targeting=minimal_targeting
+ )
+
+ result_data = json.loads(result)
+ assert result_data["success"] is True
+ assert result_data["estimated_audience_size"] == 500000
+ assert result_data["targeting"] == minimal_targeting
+
+ @pytest.mark.asyncio
+ async def test_estimate_details_structure(self):
+ """Test that estimate_details contains expected structure"""
+ mock_response = {
+ "data": [
+ {
+ "estimate_mau": 2000000,
+ "estimate_dau": [
+ {"min_reach": 150000, "max_reach": 200000, "bid": 120}
+ ],
+ "bid_estimates": {
+ "median": 180,
+ "min": 80,
+ "max": 350
+ },
+ "unsupported_targeting": ["custom_audiences"]
+ }
+ ]
+ }
+
+ targeting_spec = {
+ "age_min": 25,
+ "age_max": 45,
+ "geo_locations": {"countries": ["US"]},
+ "flexible_spec": [
+ {"interests": [{"id": "6003371567474"}, {"id": "6003462346642"}]}
+ ]
+ }
+
+ with patch('meta_ads_mcp.core.targeting.make_api_request', new_callable=AsyncMock) as mock_api:
+ mock_api.return_value = mock_response
+
+ result = await estimate_audience_size(
+ access_token="test_token",
+ account_id="act_123456789",
+ targeting=targeting_spec,
+ optimization_goal="CONVERSIONS"
+ )
+
+ result_data = json.loads(result)
+ assert result_data["success"] is True
+
+ # Check estimate_details structure
+ details = result_data["estimate_details"]
+ assert "monthly_active_users" in details
+ assert "daily_outcomes_curve" in details
+ assert "bid_estimate" in details
+ assert "unsupported_targeting" in details
+
+ assert details["monthly_active_users"] == 2000000
+ assert len(details["daily_outcomes_curve"]) == 1
+ assert details["bid_estimate"]["median"] == 180
+ assert "custom_audiences" in details["unsupported_targeting"]
+
+ @pytest.mark.asyncio
+ async def test_function_registration(self):
+ """Test that the function is properly registered as an MCP tool"""
+ # This test verifies the function has the correct decorators
+ assert hasattr(estimate_audience_size, '__wrapped__') # From @meta_api_tool
+
+ # Verify function signature
+ import inspect
+ sig = inspect.signature(estimate_audience_size)
+
+ expected_params = [
+ 'access_token', 'account_id', 'targeting', 'optimization_goal',
+ 'interest_list', 'interest_fbid_list'
+ ]
+
+ for param in expected_params:
+ assert param in sig.parameters
+
+ # Verify default values
+ assert sig.parameters['optimization_goal'].default == "REACH"
+ assert sig.parameters['access_token'].default is None
+ assert sig.parameters['targeting'].default is None
\ No newline at end of file
diff --git a/tests/test_estimate_audience_size_e2e.py b/tests/test_estimate_audience_size_e2e.py
new file mode 100644
index 0000000..821cca8
--- /dev/null
+++ b/tests/test_estimate_audience_size_e2e.py
@@ -0,0 +1,524 @@
+#!/usr/bin/env python3
+"""
+End-to-End Audience Estimation Test for Meta Ads MCP
+
+This test validates that the new estimate_audience_size function correctly provides
+comprehensive audience estimation and backwards compatibility for interest validation
+through a pre-authenticated MCP server.
+
+Test scenarios:
+1. Comprehensive audience estimation with complex targeting
+2. Backwards compatibility with simple interest validation
+3. Error handling for invalid parameters
+4. Different optimization goals
+"""
+
+import requests
+import json
+import os
+import sys
+from typing import Dict, Any, List
+
+# Load environment variables from .env file
+try:
+ from dotenv import load_dotenv
+ load_dotenv()
+ print("✅ Loaded environment variables from .env file")
+except ImportError:
+ print("⚠️ python-dotenv not installed, using system environment variables only")
+
+class AudienceEstimationTester:
+ """Test suite focused on audience estimation functionality"""
+
+ 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 ID from workspace rules
+ self.account_id = "act_701351919139047"
+
+ # Test targeting specifications
+ self.test_targeting_specs = {
+ "simple_demographics": {
+ "age_min": 25,
+ "age_max": 65,
+ "geo_locations": {"countries": ["US"]}
+ },
+ "demographics_with_interests": {
+ "age_min": 18,
+ "age_max": 35,
+ "geo_locations": {"countries": ["PL"]},
+ "flexible_spec": [
+ {"interests": [{"id": "6003371567474"}]} # Business interest
+ ]
+ },
+ "complex_targeting": {
+ "age_min": 25,
+ "age_max": 55,
+ "geo_locations": {"countries": ["US"], "regions": [{"key": "3847"}]}, # California
+ "flexible_spec": [
+ {"interests": [{"id": "6003371567474"}, {"id": "6003462346642"}]}, # Business + Technology
+ {"behaviors": [{"id": "6007101597783"}]} # Business travelers
+ ]
+ },
+ "mobile_app_targeting": {
+ "age_min": 18,
+ "age_max": 45,
+ "geo_locations": {"countries": ["US"]},
+ "user_device": ["mobile"],
+ "user_os": ["iOS", "Android"],
+ "flexible_spec": [
+ {"interests": [{"id": "6003139266461"}]} # Mobile games
+ ]
+ }
+ }
+
+ # Test interest lists for backwards compatibility
+ self.test_interests = {
+ "valid_names": ["Japan", "Basketball", "Technology"],
+ "mixed_validity": ["Japan", "invalidinterestname12345", "Basketball"],
+ "valid_fbids": ["6003700426513", "6003397425735"], # Japan, Tennis
+ "invalid_fbids": ["999999999999", "000000000000"]
+ }
+
+ def _make_request(self, method: str, params: Dict[str, Any] = None,
+ headers: Dict[str, str] = None) -> Dict[str, Any]:
+ """Make a JSON-RPC request to the MCP server"""
+
+ default_headers = {
+ "Content-Type": "application/json",
+ "Accept": "application/json, text/event-stream",
+ "User-Agent": "Audience-Estimation-Test-Client/1.0"
+ }
+
+ if headers:
+ default_headers.update(headers)
+
+ payload = {
+ "jsonrpc": "2.0",
+ "method": method,
+ "id": self.request_id
+ }
+
+ if params:
+ payload["params"] = params
+
+ try:
+ response = requests.post(
+ self.endpoint,
+ headers=default_headers,
+ json=payload,
+ timeout=20 # Increased timeout for delivery estimates
+ )
+
+ self.request_id += 1
+
+ return {
+ "status_code": response.status_code,
+ "headers": dict(response.headers),
+ "json": response.json() if response.status_code == 200 else None,
+ "text": response.text,
+ "success": response.status_code == 200
+ }
+
+ except requests.exceptions.RequestException as e:
+ return {
+ "status_code": 0,
+ "headers": {},
+ "json": None,
+ "text": str(e),
+ "success": False,
+ "error": str(e)
+ }
+
+ def test_comprehensive_audience_estimation(self) -> Dict[str, Any]:
+ """Test comprehensive audience estimation with complex targeting"""
+
+ print(f"\n🎯 Testing Comprehensive Audience Estimation")
+ results = {}
+
+ for spec_name, targeting_spec in self.test_targeting_specs.items():
+ print(f" 📊 Testing targeting: '{spec_name}'")
+
+ result = self._make_request("tools/call", {
+ "name": "estimate_audience_size",
+ "arguments": {
+ "account_id": self.account_id,
+ "targeting": targeting_spec,
+ "optimization_goal": "REACH"
+ }
+ })
+
+ if not result["success"]:
+ results[spec_name] = {
+ "success": False,
+ "error": result.get("text", "Unknown error")
+ }
+ print(f" ❌ Failed: {result.get('text', 'Unknown error')}")
+ continue
+
+ # Parse response
+ response_data = result["json"]["result"]
+ content = response_data.get("content", [{}])[0].get("text", "")
+
+ try:
+ parsed_content = json.loads(content)
+
+ if "error" in parsed_content:
+ results[spec_name] = {
+ "success": False,
+ "error": parsed_content["error"]
+ }
+ print(f" ❌ API Error: {parsed_content['error']}")
+ continue
+
+ # Check for expected fields in comprehensive estimation
+ has_success = parsed_content.get("success", False)
+ has_estimate = "estimated_audience_size" in parsed_content
+ has_details = "estimate_details" in parsed_content
+
+ results[spec_name] = {
+ "success": has_success and has_estimate,
+ "has_estimate": has_estimate,
+ "has_details": has_details,
+ "estimated_size": parsed_content.get("estimated_audience_size", 0),
+ "optimization_goal": parsed_content.get("optimization_goal"),
+ "raw_response": parsed_content
+ }
+
+ if has_success and has_estimate:
+ estimate_size = parsed_content.get("estimated_audience_size", 0)
+ print(f" ✅ Estimated audience: {estimate_size:,} people")
+ else:
+ print(f" ⚠️ Incomplete response: success={has_success}, estimate={has_estimate}")
+
+ except json.JSONDecodeError:
+ results[spec_name] = {
+ "success": False,
+ "error": "Invalid JSON response",
+ "raw_content": content
+ }
+ print(f" ❌ Invalid JSON: {content[:100]}...")
+
+ return results
+
+ def test_backwards_compatibility_interest_validation(self) -> Dict[str, Any]:
+ """Test backwards compatibility with simple interest validation"""
+
+ print(f"\n🔄 Testing Backwards Compatibility (Interest Validation)")
+ results = {}
+
+ # Test with interest names
+ print(f" 📝 Testing interest name validation")
+
+ result = self._make_request("tools/call", {
+ "name": "estimate_audience_size",
+ "arguments": {
+ "interest_list": self.test_interests["mixed_validity"]
+ }
+ })
+
+ if result["success"]:
+ response_data = result["json"]["result"]
+ content = response_data.get("content", [{}])[0].get("text", "")
+
+ try:
+ parsed_content = json.loads(content)
+
+ if "data" in parsed_content:
+ validations = parsed_content["data"]
+ results["interest_names"] = {
+ "success": True,
+ "count": len(validations),
+ "has_valid": any(v.get("valid", False) for v in validations),
+ "has_invalid": any(not v.get("valid", True) for v in validations),
+ "validations": validations
+ }
+ print(f" ✅ Validated {len(validations)} interests")
+ for validation in validations:
+ status = "✅" if validation.get("valid") else "❌"
+ print(f" {status} {validation.get('name', 'N/A')}")
+ else:
+ results["interest_names"] = {"success": False, "error": "No validation data"}
+ print(f" ❌ No validation data returned")
+
+ except json.JSONDecodeError:
+ results["interest_names"] = {"success": False, "error": "Invalid JSON"}
+ print(f" ❌ Invalid JSON response")
+ else:
+ results["interest_names"] = {"success": False, "error": result.get("text", "Request failed")}
+ print(f" ❌ Request failed: {result.get('text', 'Unknown error')}")
+
+ # Test with interest FBIDs
+ print(f" 🔢 Testing interest FBID validation")
+
+ result = self._make_request("tools/call", {
+ "name": "estimate_audience_size",
+ "arguments": {
+ "interest_fbid_list": self.test_interests["valid_fbids"]
+ }
+ })
+
+ if result["success"]:
+ response_data = result["json"]["result"]
+ content = response_data.get("content", [{}])[0].get("text", "")
+
+ try:
+ parsed_content = json.loads(content)
+
+ if "data" in parsed_content:
+ validations = parsed_content["data"]
+ results["interest_fbids"] = {
+ "success": True,
+ "count": len(validations),
+ "all_valid": all(v.get("valid", False) for v in validations),
+ "validations": validations
+ }
+ print(f" ✅ Validated {len(validations)} FBID interests")
+ for validation in validations:
+ status = "✅" if validation.get("valid") else "❌"
+ print(f" {status} FBID: {validation.get('id', 'N/A')}")
+ else:
+ results["interest_fbids"] = {"success": False, "error": "No validation data"}
+ print(f" ❌ No validation data returned")
+
+ except json.JSONDecodeError:
+ results["interest_fbids"] = {"success": False, "error": "Invalid JSON"}
+ print(f" ❌ Invalid JSON response")
+ else:
+ results["interest_fbids"] = {"success": False, "error": result.get("text", "Request failed")}
+ print(f" ❌ Request failed: {result.get('text', 'Unknown error')}")
+
+ return results
+
+ def test_different_optimization_goals(self) -> Dict[str, Any]:
+ """Test audience estimation with different optimization goals"""
+
+ print(f"\n🎯 Testing Different Optimization Goals")
+ results = {}
+
+ optimization_goals = ["REACH", "LINK_CLICKS", "CONVERSIONS", "APP_INSTALLS"]
+ base_targeting = self.test_targeting_specs["simple_demographics"]
+
+ for goal in optimization_goals:
+ print(f" 🎯 Testing optimization goal: '{goal}'")
+
+ result = self._make_request("tools/call", {
+ "name": "estimate_audience_size",
+ "arguments": {
+ "account_id": self.account_id,
+ "targeting": base_targeting,
+ "optimization_goal": goal
+ }
+ })
+
+ if result["success"]:
+ response_data = result["json"]["result"]
+ content = response_data.get("content", [{}])[0].get("text", "")
+
+ try:
+ parsed_content = json.loads(content)
+
+ if parsed_content.get("success", False):
+ results[goal] = {
+ "success": True,
+ "estimated_size": parsed_content.get("estimated_audience_size", 0),
+ "goal_used": parsed_content.get("optimization_goal")
+ }
+ estimate_size = parsed_content.get("estimated_audience_size", 0)
+ print(f" ✅ {goal}: {estimate_size:,} people")
+ else:
+ results[goal] = {
+ "success": False,
+ "error": parsed_content.get("error", "Unknown error")
+ }
+ print(f" ❌ {goal}: {parsed_content.get('error', 'Unknown error')}")
+
+ except json.JSONDecodeError:
+ results[goal] = {"success": False, "error": "Invalid JSON"}
+ print(f" ❌ {goal}: Invalid JSON response")
+ else:
+ results[goal] = {"success": False, "error": result.get("text", "Request failed")}
+ print(f" ❌ {goal}: Request failed")
+
+ return results
+
+ def test_error_handling(self) -> Dict[str, Any]:
+ """Test error handling for invalid parameters"""
+
+ print(f"\n⚠️ Testing Error Handling")
+ results = {}
+
+ # Test 1: No parameters
+ print(f" 🚫 Testing with no parameters")
+ result = self._make_request("tools/call", {
+ "name": "estimate_audience_size",
+ "arguments": {}
+ })
+
+ results["no_params"] = self._parse_error_response(result, "Should require targeting or interest validation")
+
+ # Test 2: Account ID without targeting
+ print(f" 🚫 Testing account ID without targeting")
+ result = self._make_request("tools/call", {
+ "name": "estimate_audience_size",
+ "arguments": {
+ "account_id": self.account_id
+ }
+ })
+
+ results["no_targeting"] = self._parse_error_response(result, "Should require targeting specification")
+
+ # Test 3: Invalid targeting structure
+ print(f" 🚫 Testing invalid targeting structure")
+ result = self._make_request("tools/call", {
+ "name": "estimate_audience_size",
+ "arguments": {
+ "account_id": self.account_id,
+ "targeting": {"invalid": "structure"}
+ }
+ })
+
+ results["invalid_targeting"] = self._parse_error_response(result, "Should handle invalid targeting")
+
+ return results
+
+ def _parse_error_response(self, result: Dict[str, Any], description: str) -> Dict[str, Any]:
+ """Helper to parse and validate error responses"""
+
+ if not result["success"]:
+ print(f" ✅ {description}: Request failed as expected")
+ return {"success": True, "error_type": "request_failure"}
+
+ response_data = result["json"]["result"]
+ content = response_data.get("content", [{}])[0].get("text", "")
+
+ try:
+ parsed_content = json.loads(content)
+
+ if "error" in parsed_content:
+ print(f" ✅ {description}: {parsed_content['error']}")
+ return {"success": True, "error_message": parsed_content["error"]}
+ else:
+ print(f" ❌ {description}: No error returned when expected")
+ return {"success": False, "unexpected_success": True}
+
+ except json.JSONDecodeError:
+ print(f" ❌ {description}: Invalid JSON response")
+ return {"success": False, "error": "Invalid JSON"}
+
+ def run_audience_estimation_tests(self) -> bool:
+ """Run comprehensive audience estimation tests"""
+
+ print("🚀 Meta Ads Audience Estimation End-to-End Test Suite")
+ print("="*70)
+
+ # Check server availability
+ try:
+ response = requests.get(f"{self.base_url}/", timeout=5)
+ server_running = response.status_code in [200, 404]
+ except:
+ server_running = False
+
+ if not server_running:
+ print("❌ Server is not running at", self.base_url)
+ print(" Please start the server with:")
+ print(" python3 -m meta_ads_mcp --transport streamable-http --port 8080")
+ return False
+
+ print("✅ Server is running")
+ print("🔐 Using implicit authentication from server")
+ print(f"🏢 Using account ID: {self.account_id}")
+
+ # Test 1: Comprehensive Audience Estimation
+ print("\n" + "="*70)
+ print("📋 PHASE 1: Testing Comprehensive Audience Estimation")
+ print("="*70)
+
+ comprehensive_results = self.test_comprehensive_audience_estimation()
+ comprehensive_success = any(
+ result.get("success") and result.get("estimated_size", 0) > 0
+ for result in comprehensive_results.values()
+ )
+
+ # Test 2: Backwards Compatibility
+ print("\n" + "="*70)
+ print("📋 PHASE 2: Testing Backwards Compatibility")
+ print("="*70)
+
+ compat_results = self.test_backwards_compatibility_interest_validation()
+ compat_success = (
+ compat_results.get("interest_names", {}).get("success", False) and
+ compat_results.get("interest_fbids", {}).get("success", False)
+ )
+
+ # Test 3: Different Optimization Goals
+ print("\n" + "="*70)
+ print("📋 PHASE 3: Testing Different Optimization Goals")
+ print("="*70)
+
+ goals_results = self.test_different_optimization_goals()
+ goals_success = any(
+ result.get("success") and result.get("estimated_size", 0) > 0
+ for result in goals_results.values()
+ )
+
+ # Test 4: Error Handling
+ print("\n" + "="*70)
+ print("📋 PHASE 4: Testing Error Handling")
+ print("="*70)
+
+ error_results = self.test_error_handling()
+ error_success = all(
+ result.get("success", False) for result in error_results.values()
+ )
+
+ # Final assessment
+ print("\n" + "="*70)
+ print("📊 FINAL RESULTS")
+ print("="*70)
+
+ all_tests = [
+ ("Comprehensive Estimation", comprehensive_success),
+ ("Backwards Compatibility", compat_success),
+ ("Optimization Goals", goals_success),
+ ("Error Handling", error_success)
+ ]
+
+ passed_tests = sum(1 for _, success in all_tests if success)
+ total_tests = len(all_tests)
+
+ for test_name, success in all_tests:
+ status = "✅ PASSED" if success else "❌ FAILED"
+ print(f" • {test_name}: {status}")
+
+ overall_success = passed_tests >= 3 # At least 3 out of 4 tests should pass
+
+ if overall_success:
+ 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")
+ return True
+ else:
+ print(f"\n❌ Audience estimation tests: FAILED ({passed_tests}/{total_tests} passed)")
+ print(" • Some audience estimation features are not working properly")
+ return False
+
+
+def main():
+ """Main test execution"""
+ tester = AudienceEstimationTester()
+ success = tester.run_audience_estimation_tests()
+
+ if success:
+ print("\n🎉 All audience estimation tests passed!")
+ else:
+ print("\n⚠️ Some audience estimation tests failed - see details above")
+
+ sys.exit(0 if success else 1)
+
+
+if __name__ == "__main__":
+ main()
\ No newline at end of file
diff --git a/tests/test_targeting.py b/tests/test_targeting.py
index 72526c5..e862aa2 100644
--- a/tests/test_targeting.py
+++ b/tests/test_targeting.py
@@ -10,7 +10,7 @@ from unittest.mock import AsyncMock, patch
from meta_ads_mcp.core.targeting import (
search_interests,
get_interest_suggestions,
- validate_interests,
+ estimate_audience_size,
search_behaviors,
search_demographics,
search_geo_locations
@@ -166,8 +166,8 @@ class TestGetInterestSuggestions:
assert nested_data["error"] == "No interest list provided"
-class TestValidateInterests:
- """Test cases for validate_interests function"""
+class TestEstimateAudienceSizeBackwardsCompatibility:
+ """Test cases for estimate_audience_size function backwards compatibility"""
@pytest.mark.asyncio
async def test_validate_interests_by_name_success(self):
@@ -190,7 +190,7 @@ class TestValidateInterests:
with patch('meta_ads_mcp.core.targeting.make_api_request', new_callable=AsyncMock) as mock_api:
mock_api.return_value = mock_response
- result = await validate_interests(
+ result = await estimate_audience_size(
access_token="test_token",
interest_list=["Japan", "nonexistantkeyword"]
)
@@ -227,7 +227,7 @@ class TestValidateInterests:
with patch('meta_ads_mcp.core.targeting.make_api_request', new_callable=AsyncMock) as mock_api:
mock_api.return_value = mock_response
- result = await validate_interests(
+ result = await estimate_audience_size(
access_token="test_token",
interest_fbid_list=["6003700426513"]
)
@@ -248,8 +248,8 @@ class TestValidateInterests:
@pytest.mark.asyncio
async def test_validate_interests_no_input(self):
- """Test validate_interests with no input lists"""
- result = await validate_interests(access_token="test_token")
+ """Test estimate_audience_size with no input lists (backwards compatibility)"""
+ result = await estimate_audience_size(access_token="test_token")
result_data = json.loads(result)
# The @meta_api_tool decorator wraps errors in a 'data' field