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: Implement DSA beneficiary functionality for compliance with European regulations
Yves Junqueira1421d662c93b
diff --git a/meta_ads_mcp/core/accounts.py b/meta_ads_mcp/core/accounts.pyindex 35f99e3..c146947 100644--- a/meta_ads_mcp/core/accounts.py+++ b/meta_ads_mcp/core/accounts.py@@ -59,4 +59,14 @@ async def get_account_info(access_token: str = None, account_id: str = None) ->data = await make_api_request(endpoint, access_token, params)+ # Add DSA requirement detection+ if "business_country_code" in data:+ european_countries = ["DE", "FR", "IT", "ES", "NL", "BE", "AT", "IE", "DK", "SE", "FI", "NO"]+ if data["business_country_code"] in european_countries:+ data["dsa_required"] = True+ data["dsa_compliance_note"] = "This account is subject to European DSA (Digital Services Act) requirements"+ else:+ data["dsa_required"] = False+ data["dsa_compliance_note"] = "This account is not subject to European DSA requirements"+return json.dumps(data, indent=2)\ No newline at end of filediff --git a/meta_ads_mcp/core/adsets.py b/meta_ads_mcp/core/adsets.pyindex ea5bbc7..e37d843 100644--- a/meta_ads_mcp/core/adsets.py+++ b/meta_ads_mcp/core/adsets.py@@ -73,7 +73,7 @@ async def get_adset_details(access_token: str = None, adset_id: str = None) -> sendpoint = f"{adset_id}"# Explicitly prioritize frequency_control_specs in the fields requestparams = {- "fields": "id,name,campaign_id,status,frequency_control_specs{event,interval_days,max_frequency},daily_budget,lifetime_budget,targeting,bid_amount,bid_strategy,optimization_goal,billing_event,start_time,end_time,created_time,updated_time,attribution_spec,destination_type,promoted_object,pacing_type,budget_remaining"+ "fields": "id,name,campaign_id,status,frequency_control_specs{event,interval_days,max_frequency},daily_budget,lifetime_budget,targeting,bid_amount,bid_strategy,optimization_goal,billing_event,start_time,end_time,created_time,updated_time,attribution_spec,destination_type,promoted_object,pacing_type,budget_remaining,dsa_beneficiary"}data = await make_api_request(endpoint, access_token, params)@@ -103,6 +103,7 @@ async def create_adset(bid_strategy: str = None,start_time: str = None,end_time: str = None,+ dsa_beneficiary: str = None,access_token: str = None) -> str:"""@@ -123,6 +124,7 @@ async def create_adset(bid_strategy: Bid strategy (e.g., 'LOWEST_COST', 'LOWEST_COST_WITH_BID_CAP')start_time: Start time in ISO 8601 format (e.g., '2023-12-01T12:00:00-0800')end_time: End time in ISO 8601 format+ dsa_beneficiary: DSA beneficiary (person/organization benefiting from ads) for European complianceaccess_token: Meta API access token (optional - will use cached token if not provided)"""# Check required parameters@@ -181,16 +183,44 @@ async def create_adset(if end_time:params["end_time"] = end_time+ # Add DSA beneficiary if provided+ if dsa_beneficiary:+ params["dsa_beneficiary"] = dsa_beneficiary+try:data = await make_api_request(endpoint, access_token, params, method="POST")return json.dumps(data, indent=2)except Exception as e:error_msg = str(e)- return json.dumps({- "error": "Failed to create ad set",- "details": error_msg,- "params_sent": params- }, indent=2)++ # Enhanced error handling for DSA beneficiary issues+ if "permission" in error_msg.lower() or "insufficient" in error_msg.lower():+ return json.dumps({+ "error": "Insufficient permissions to set DSA beneficiary. Please ensure you have business_management permissions.",+ "details": error_msg,+ "params_sent": params,+ "permission_required": True+ }, indent=2)+ elif "dsa_beneficiary" in error_msg.lower() and ("not supported" in error_msg.lower() or "parameter" in error_msg.lower()):+ return json.dumps({+ "error": "DSA beneficiary parameter not supported in this API version. Please set DSA beneficiary manually in Facebook Ads Manager.",+ "details": error_msg,+ "params_sent": params,+ "manual_setup_required": True+ }, indent=2)+ elif "benefits from ads" in error_msg or "DSA beneficiary" in error_msg:+ return json.dumps({+ "error": "DSA beneficiary required for European compliance. Please provide the person or organization that benefits from ads in this ad set.",+ "details": error_msg,+ "params_sent": params,+ "dsa_required": True+ }, indent=2)+ else:+ return json.dumps({+ "error": "Failed to create ad set",+ "details": error_msg,+ "params_sent": params+ }, indent=2)@mcp_server.tool()diff --git a/tests/test_dsa_beneficiary.py b/tests/test_dsa_beneficiary.pynew file mode 100644index 0000000..c62d3ae--- /dev/null+++ b/tests/test_dsa_beneficiary.py@@ -0,0 +1,597 @@+#!/usr/bin/env python3+"""+Unit tests for DSA (Digital Services Act) beneficiary functionality in Meta Ads MCP.++This module tests the implementation of DSA beneficiary field support for ad set creation,+including detection of DSA requirements, parameter validation, and error handling.+"""++import pytest+import json+from unittest.mock import AsyncMock, patch, MagicMock++from meta_ads_mcp.core.adsets import create_adset, get_adset_details+from meta_ads_mcp.core.accounts import get_account_info+++class TestDSABeneficiaryDetection:+ """Test cases for detecting DSA beneficiary requirements"""++ @pytest.mark.asyncio+ async def test_dsa_requirement_detection_business_account(self):+ """Test detection of DSA requirements for business accounts"""+ mock_account_response = {+ "id": "act_701351919139047",+ "name": "Test Business Account",+ "account_status": 1,+ "business_country_code": "DE", # Germany - DSA compliant+ "business_city": "Berlin",+ "currency": "EUR"+ }++ with patch('meta_ads_mcp.core.accounts.make_api_request', new_callable=AsyncMock) as mock_api:+ with patch('meta_ads_mcp.core.api.get_current_access_token', new_callable=AsyncMock) as mock_auth:+ mock_auth.return_value = "test_access_token"+ mock_api.return_value = mock_account_response++ result = await get_account_info(account_id="act_701351919139047")+ result_data = json.loads(result)++ # Verify account info is retrieved+ assert result_data["id"] == "act_701351919139047"+ assert result_data["business_country_code"] == "DE"++ # Verify DSA requirement detection+ assert "dsa_required" in result_data or "business_country_code" in result_data++ @pytest.mark.asyncio+ async def test_dsa_requirement_detection_non_dsa_region(self):+ """Test detection for non-DSA compliant regions"""+ mock_account_response = {+ "id": "act_123456789",+ "name": "Test US Account",+ "account_status": 1,+ "business_country_code": "US", # US - not DSA compliant+ "business_city": "New York",+ "currency": "USD"+ }++ with patch('meta_ads_mcp.core.accounts.make_api_request', new_callable=AsyncMock) as mock_api:+ with patch('meta_ads_mcp.core.api.get_current_access_token', new_callable=AsyncMock) as mock_auth:+ mock_auth.return_value = "test_access_token"+ mock_api.return_value = mock_account_response++ result = await get_account_info(account_id="act_123456789")+ result_data = json.loads(result)++ # Verify no DSA requirement for US accounts+ assert result_data["business_country_code"] == "US"++ @pytest.mark.asyncio+ async def test_dsa_requirement_detection_error_handling(self):+ """Test error handling when account info cannot be retrieved"""+ with patch('meta_ads_mcp.core.accounts.make_api_request', new_callable=AsyncMock) as mock_api:+ with patch('meta_ads_mcp.core.api.get_current_access_token', new_callable=AsyncMock) as mock_auth:+ mock_auth.return_value = "test_access_token"+ mock_api.side_effect = Exception("API Error")++ result = await get_account_info(account_id="act_invalid")++ # Handle response format - could be dict or JSON string+ if isinstance(result, dict):+ result_data = result+ else:+ result_data = json.loads(result)++ # Verify error is properly handled+ assert "error" in result_data+++class TestDSABeneficiaryParameter:+ """Test cases for DSA beneficiary parameter support"""++ @pytest.mark.asyncio+ async def test_create_adset_with_dsa_beneficiary_success(self):+ """Test successful ad set creation with DSA beneficiary parameter"""+ mock_response = {+ "id": "23842588888640185",+ "name": "Test Ad Set with DSA",+ "status": "PAUSED",+ "dsa_beneficiary": "Test Organization GmbH"+ }++ with patch('meta_ads_mcp.core.adsets.make_api_request', new_callable=AsyncMock) as mock_api:+ with patch('meta_ads_mcp.core.api.get_current_access_token', new_callable=AsyncMock) as mock_auth:+ mock_auth.return_value = "test_access_token"+ mock_api.return_value = mock_response++ result = await create_adset(+ account_id="act_701351919139047",+ campaign_id="23842588888640184",+ name="Test Ad Set with DSA",+ optimization_goal="LINK_CLICKS",+ billing_event="IMPRESSIONS",+ dsa_beneficiary="Test Organization GmbH"+ )++ # Verify the API was called with DSA beneficiary parameter+ mock_api.assert_called_once()+ call_args = mock_api.call_args+ assert "dsa_beneficiary" in str(call_args)++ # Verify response contains ad set ID+ result_data = json.loads(result)+ assert "id" in result_data++ @pytest.mark.asyncio+ async def test_create_adset_with_dsa_beneficiary_validation_error(self):+ """Test error handling when DSA beneficiary parameter is invalid"""+ mock_error_response = {+ "error": {+ "message": "DSA beneficiary required for European compliance",+ "type": "OAuthException",+ "code": 100+ }+ }++ with patch('meta_ads_mcp.core.adsets.make_api_request', new_callable=AsyncMock) as mock_api:+ with patch('meta_ads_mcp.core.api.get_current_access_token', new_callable=AsyncMock) as mock_auth:+ mock_auth.return_value = "test_access_token"+ mock_api.side_effect = Exception("DSA beneficiary required for European compliance")++ result = await create_adset(+ account_id="act_701351919139047",+ campaign_id="23842588888640184",+ name="Test Ad Set",+ optimization_goal="LINK_CLICKS",+ billing_event="IMPRESSIONS"+ # No DSA beneficiary provided+ )++ # Verify error message is clear and actionable+ result_data = json.loads(result)++ # Handle response wrapped in 'data' field by meta_api_tool decorator+ if "data" in result_data:+ actual_data = json.loads(result_data["data"])+ else:+ actual_data = result_data++ assert "DSA beneficiary required" in actual_data.get("error", "")++ @pytest.mark.asyncio+ async def test_create_adset_without_dsa_beneficiary_dsa_required(self):+ """Test error when DSA beneficiary is required but not provided"""+ with patch('meta_ads_mcp.core.adsets.make_api_request', new_callable=AsyncMock) as mock_api:+ with patch('meta_ads_mcp.core.api.get_current_access_token', new_callable=AsyncMock) as mock_auth:+ mock_auth.return_value = "test_access_token"+ mock_api.side_effect = Exception("Enter the person or organization that benefits from ads in this ad set")++ result = await create_adset(+ account_id="act_701351919139047",+ campaign_id="23842588888640184",+ name="Test Ad Set",+ optimization_goal="LINK_CLICKS",+ billing_event="IMPRESSIONS"+ # No DSA beneficiary provided+ )++ # Verify error message is clear and actionable+ result_data = json.loads(result)++ # Handle response wrapped in 'data' field by meta_api_tool decorator+ if "data" in result_data:+ actual_data = json.loads(result_data["data"])+ else:+ actual_data = result_data++ assert "benefits from ads" in actual_data.get("error", "")++ @pytest.mark.asyncio+ async def test_create_adset_dsa_beneficiary_in_targeting(self):+ """Test that DSA beneficiary is not added to targeting spec"""+ with patch('meta_ads_mcp.core.adsets.make_api_request', new_callable=AsyncMock) as mock_api:+ with patch('meta_ads_mcp.core.api.get_current_access_token', new_callable=AsyncMock) as mock_auth:+ mock_auth.return_value = "test_access_token"+ mock_api.return_value = {"id": "23842588888640185"}++ result = await create_adset(+ account_id="act_701351919139047",+ campaign_id="23842588888640184",+ name="Test Ad Set",+ optimization_goal="LINK_CLICKS",+ billing_event="IMPRESSIONS",+ targeting={"geo_locations": {"countries": ["DE"]}},+ dsa_beneficiary="Test Organization GmbH"+ )++ # Verify the API was called+ mock_api.assert_called_once()+ call_args = mock_api.call_args++ # Verify DSA beneficiary is sent as separate parameter, not in targeting+ call_str = str(call_args)+ assert "dsa_beneficiary" in call_str+ assert "Test Organization GmbH" in call_str++ @pytest.mark.asyncio+ async def test_create_adset_dsa_beneficiary_parameter_formats(self):+ """Test different formats for DSA beneficiary parameter"""+ test_cases = [+ "Simple Organization",+ "Organization with Special Chars: GmbH & Co. KG",+ "Organization with Numbers: Test123 Inc.",+ "Very Long Organization Name That Exceeds Normal Limits But Should Still Work"+ ]++ for beneficiary_name in test_cases:+ with patch('meta_ads_mcp.core.adsets.make_api_request', new_callable=AsyncMock) as mock_api:+ with patch('meta_ads_mcp.core.api.get_current_access_token', new_callable=AsyncMock) as mock_auth:+ mock_auth.return_value = "test_access_token"+ mock_api.return_value = {"id": "23842588888640185"}++ result = await create_adset(+ account_id="act_701351919139047",+ campaign_id="23842588888640184",+ name="Test Ad Set",+ optimization_goal="LINK_CLICKS",+ billing_event="IMPRESSIONS",+ dsa_beneficiary=beneficiary_name+ )++ # Verify the API was called with the beneficiary name+ mock_api.assert_called_once()+ call_args = mock_api.call_args+ assert beneficiary_name in str(call_args)+++class TestDSAPermissionHandling:+ """Test cases for permission-related DSA beneficiary issues"""++ @pytest.mark.asyncio+ async def test_dsa_beneficiary_missing_business_management_permission(self):+ """Test error handling when business_management permissions are missing"""+ with patch('meta_ads_mcp.core.adsets.make_api_request', new_callable=AsyncMock) as mock_api:+ with patch('meta_ads_mcp.core.api.get_current_access_token', new_callable=AsyncMock) as mock_auth:+ mock_auth.return_value = "test_access_token"+ mock_api.side_effect = Exception("Permission denied: business_management permission required")++ result = await create_adset(+ account_id="act_701351919139047",+ campaign_id="23842588888640184",+ name="Test Ad Set",+ optimization_goal="LINK_CLICKS",+ billing_event="IMPRESSIONS",+ dsa_beneficiary="Test Organization GmbH"+ )++ # Verify permission error is handled+ result_data = json.loads(result)++ # Handle response wrapped in 'data' field by meta_api_tool decorator+ if "data" in result_data:+ actual_data = json.loads(result_data["data"])+ else:+ actual_data = result_data++ assert "permission" in actual_data.get("error", "").lower()++ @pytest.mark.asyncio+ async def test_dsa_beneficiary_api_limitation_handling(self):+ """Test handling when API doesn't support dsa_beneficiary parameter"""+ with patch('meta_ads_mcp.core.adsets.make_api_request', new_callable=AsyncMock) as mock_api:+ with patch('meta_ads_mcp.core.api.get_current_access_token', new_callable=AsyncMock) as mock_auth:+ mock_auth.return_value = "test_access_token"+ mock_api.side_effect = Exception("Parameter dsa_beneficiary is not supported")++ result = await create_adset(+ account_id="act_701351919139047",+ campaign_id="23842588888640184",+ name="Test Ad Set",+ optimization_goal="LINK_CLICKS",+ billing_event="IMPRESSIONS",+ dsa_beneficiary="Test Organization GmbH"+ )++ # Verify API limitation error is handled+ result_data = json.loads(result)++ # Handle response wrapped in 'data' field by meta_api_tool decorator+ if "data" in result_data:+ actual_data = json.loads(result_data["data"])+ else:+ actual_data = result_data++ assert "not supported" in actual_data.get("error", "").lower()+++class TestDSARegionalCompliance:+ """Test cases for regional DSA compliance"""++ @pytest.mark.asyncio+ async def test_dsa_compliance_european_regions(self):+ """Test DSA compliance for European regions"""+ european_countries = ["DE", "FR", "IT", "ES", "NL", "BE", "AT", "IE", "DK", "SE", "FI", "NO"]++ for country_code in european_countries:+ mock_account_response = {+ "id": f"act_{country_code.lower()}",+ "name": f"Test {country_code} Account",+ "account_status": 1,+ "business_country_code": country_code,+ "currency": "EUR"+ }++ with patch('meta_ads_mcp.core.accounts.make_api_request', new_callable=AsyncMock) as mock_api:+ with patch('meta_ads_mcp.core.api.get_current_access_token', new_callable=AsyncMock) as mock_auth:+ mock_auth.return_value = "test_access_token"+ mock_api.return_value = mock_account_response++ result = await get_account_info(account_id=f"act_{country_code.lower()}")+ result_data = json.loads(result)++ # Verify European countries are detected as DSA compliant+ assert result_data["business_country_code"] == country_code++ @pytest.mark.asyncio+ async def test_dsa_compliance_non_european_regions(self):+ """Test DSA compliance for non-European regions"""+ non_european_countries = ["US", "CA", "AU", "JP", "BR", "IN"]++ for country_code in non_european_countries:+ mock_account_response = {+ "id": f"act_{country_code.lower()}",+ "name": f"Test {country_code} Account",+ "account_status": 1,+ "business_country_code": country_code,+ "currency": "USD"+ }++ with patch('meta_ads_mcp.core.accounts.make_api_request', new_callable=AsyncMock) as mock_api:+ with patch('meta_ads_mcp.core.api.get_current_access_token', new_callable=AsyncMock) as mock_auth:+ mock_auth.return_value = "test_access_token"+ mock_api.return_value = mock_account_response++ result = await get_account_info(account_id=f"act_{country_code.lower()}")+ result_data = json.loads(result)++ # Verify non-European countries are not DSA compliant+ assert result_data["business_country_code"] == country_code++ @pytest.mark.asyncio+ async def test_dsa_beneficiary_validation_by_region(self):+ """Test DSA beneficiary validation based on region"""+ # Test European account (should require DSA beneficiary)+ european_mock_response = {+ "id": "act_de",+ "name": "German Account",+ "business_country_code": "DE"+ }++ # Test US account (should not require DSA beneficiary)+ us_mock_response = {+ "id": "act_us",+ "name": "US Account",+ "business_country_code": "US"+ }++ # Test European account+ with patch('meta_ads_mcp.core.accounts.make_api_request', new_callable=AsyncMock) as mock_api:+ with patch('meta_ads_mcp.core.api.get_current_access_token', new_callable=AsyncMock) as mock_auth:+ mock_auth.return_value = "test_access_token"+ mock_api.return_value = european_mock_response++ result = await get_account_info(account_id="act_de")+ result_data = json.loads(result)++ assert result_data["business_country_code"] == "DE"++ # Test US account+ with patch('meta_ads_mcp.core.accounts.make_api_request', new_callable=AsyncMock) as mock_api:+ with patch('meta_ads_mcp.core.api.get_current_access_token', new_callable=AsyncMock) as mock_auth:+ mock_auth.return_value = "test_access_token"+ mock_api.return_value = us_mock_response++ result = await get_account_info(account_id="act_us")+ result_data = json.loads(result)++ assert result_data["business_country_code"] == "US"+++class TestDSAErrorHandling:+ """Test cases for comprehensive DSA error handling"""++ @pytest.mark.asyncio+ async def test_dsa_beneficiary_clear_error_message(self):+ """Test that DSA-related errors provide clear, actionable messages"""+ error_scenarios = [+ ("DSA beneficiary required for European compliance", "DSA beneficiary"),+ ("Enter the person or organization that benefits from ads", "benefits from ads"),+ ("Permission denied: business_management required", "permission"),+ ("Parameter dsa_beneficiary is not supported", "not supported")+ ]++ for error_message, expected_keyword in error_scenarios:+ with patch('meta_ads_mcp.core.adsets.make_api_request', new_callable=AsyncMock) as mock_api:+ with patch('meta_ads_mcp.core.api.get_current_access_token', new_callable=AsyncMock) as mock_auth:+ mock_auth.return_value = "test_access_token"+ mock_api.side_effect = Exception(error_message)++ result = await create_adset(+ account_id="act_701351919139047",+ campaign_id="23842588888640184",+ name="Test Ad Set",+ optimization_goal="LINK_CLICKS",+ billing_event="IMPRESSIONS"+ )++ # Verify error message contains expected keyword+ result_data = json.loads(result)++ # Handle response wrapped in 'data' field by meta_api_tool decorator+ if "data" in result_data:+ actual_data = json.loads(result_data["data"])+ else:+ actual_data = result_data++ assert expected_keyword.lower() in actual_data.get("error", "").lower()++ @pytest.mark.asyncio+ async def test_dsa_beneficiary_fallback_behavior(self):+ """Test fallback behavior for unexpected DSA-related errors"""+ with patch('meta_ads_mcp.core.adsets.make_api_request', new_callable=AsyncMock) as mock_api:+ with patch('meta_ads_mcp.core.api.get_current_access_token', new_callable=AsyncMock) as mock_auth:+ mock_auth.return_value = "test_access_token"+ mock_api.side_effect = Exception("Unexpected DSA-related error")++ result = await create_adset(+ account_id="act_701351919139047",+ campaign_id="23842588888640184",+ name="Test Ad Set",+ optimization_goal="LINK_CLICKS",+ billing_event="IMPRESSIONS"+ )++ # Verify fallback error handling+ result_data = json.loads(result)++ # Handle response wrapped in 'data' field by meta_api_tool decorator+ if "data" in result_data:+ actual_data = json.loads(result_data["data"])+ else:+ actual_data = result_data++ assert "error" in actual_data+++class TestDSABeneficiaryRetrieval:+ """Test cases for retrieving DSA beneficiary information from ad sets"""++ @pytest.mark.asyncio+ async def test_get_adset_details_with_dsa_beneficiary(self):+ """Test retrieving ad set details that include DSA beneficiary field"""+ mock_adset_response = {+ "id": "120229746629010183",+ "name": "Test Ad Set with DSA",+ "campaign_id": "120229656904980183",+ "status": "PAUSED",+ "daily_budget": "1000",+ "targeting": {+ "geo_locations": {"countries": ["US"]},+ "age_min": 25,+ "age_max": 65+ },+ "bid_amount": 200,+ "optimization_goal": "LINK_CLICKS",+ "billing_event": "IMPRESSIONS",+ "dsa_beneficiary": "Test Organization Inc"+ }++ with patch('meta_ads_mcp.core.adsets.make_api_request', new_callable=AsyncMock) as mock_api:+ with patch('meta_ads_mcp.core.api.get_current_access_token', new_callable=AsyncMock) as mock_auth:+ mock_auth.return_value = "test_access_token"+ mock_api.return_value = mock_adset_response++ result = await get_adset_details(adset_id="120229746629010183")+ result_data = json.loads(result)++ # Verify DSA beneficiary field is present and correct+ assert "dsa_beneficiary" in result_data+ assert result_data["dsa_beneficiary"] == "Test Organization Inc"+ assert result_data["id"] == "120229746629010183"++ @pytest.mark.asyncio+ async def test_get_adset_details_without_dsa_beneficiary(self):+ """Test retrieving ad set details that don't have DSA beneficiary field"""+ mock_adset_response = {+ "id": "120229746624860183",+ "name": "Test Ad Set without DSA",+ "campaign_id": "120229656904980183",+ "status": "PAUSED",+ "daily_budget": "1000",+ "targeting": {+ "geo_locations": {"countries": ["US"]},+ "age_min": 25,+ "age_max": 65+ },+ "bid_amount": 200,+ "optimization_goal": "LINK_CLICKS",+ "billing_event": "IMPRESSIONS"+ # No dsa_beneficiary field+ }++ with patch('meta_ads_mcp.core.adsets.make_api_request', new_callable=AsyncMock) as mock_api:+ with patch('meta_ads_mcp.core.api.get_current_access_token', new_callable=AsyncMock) as mock_auth:+ mock_auth.return_value = "test_access_token"+ mock_api.return_value = mock_adset_response++ result = await get_adset_details(adset_id="120229746624860183")+ result_data = json.loads(result)++ # Verify ad set details are retrieved correctly+ assert result_data["id"] == "120229746624860183"+ assert "dsa_beneficiary" not in result_data # Should not be present++ @pytest.mark.asyncio+ async def test_get_adset_details_empty_dsa_beneficiary(self):+ """Test retrieving ad set details with empty DSA beneficiary field"""+ mock_adset_response = {+ "id": "120229746629010183",+ "name": "Test Ad Set with Empty DSA",+ "campaign_id": "120229656904980183",+ "status": "PAUSED",+ "daily_budget": "1000",+ "targeting": {+ "geo_locations": {"countries": ["US"]}+ },+ "bid_amount": 200,+ "optimization_goal": "LINK_CLICKS",+ "billing_event": "IMPRESSIONS",+ "dsa_beneficiary": "" # Empty string+ }++ with patch('meta_ads_mcp.core.adsets.make_api_request', new_callable=AsyncMock) as mock_api:+ with patch('meta_ads_mcp.core.api.get_current_access_token', new_callable=AsyncMock) as mock_auth:+ mock_auth.return_value = "test_access_token"+ mock_api.return_value = mock_adset_response++ result = await get_adset_details(adset_id="120229746629010183")+ result_data = json.loads(result)++ # Verify empty DSA beneficiary field is handled correctly+ assert "dsa_beneficiary" in result_data+ assert result_data["dsa_beneficiary"] == ""++ @pytest.mark.asyncio+ async def test_get_adset_details_dsa_beneficiary_field_requested(self):+ """Test that the API request includes dsa_beneficiary in the fields parameter"""+ with patch('meta_ads_mcp.core.adsets.make_api_request', new_callable=AsyncMock) as mock_api:+ with patch('meta_ads_mcp.core.api.get_current_access_token', new_callable=AsyncMock) as mock_auth:+ mock_auth.return_value = "test_access_token"+ mock_api.return_value = {"id": "120229746629010183"}++ result = await get_adset_details(adset_id="120229746629010183")++ # Verify the API was called with dsa_beneficiary in fields+ mock_api.assert_called_once()+ call_args = mock_api.call_args+ assert "dsa_beneficiary" in str(call_args)++ @pytest.mark.asyncio+ async def test_get_adset_details_error_handling(self):+ """Test error handling when retrieving ad set details fails"""+ with patch('meta_ads_mcp.core.adsets.make_api_request', new_callable=AsyncMock) as mock_api:+ with patch('meta_ads_mcp.core.api.get_current_access_token', new_callable=AsyncMock) as mock_auth:+ mock_auth.return_value = "test_access_token"+ mock_api.side_effect = Exception("Ad set not found")++ result = await get_adset_details(adset_id="invalid_adset_id")++ # Handle response format - could be dict or JSON string+ if isinstance(result, dict):+ result_data = result+ else:+ result_data = json.loads(result)++ # Verify error is properly handled+ assert "error" in result_data\ No newline at end of filediff --git a/tests/test_dsa_integration.py b/tests/test_dsa_integration.pynew file mode 100644index 0000000..3dd4f7f--- /dev/null+++ b/tests/test_dsa_integration.py@@ -0,0 +1,380 @@+#!/usr/bin/env python3+"""+Integration test for DSA beneficiary functionality.++This test demonstrates the complete DSA beneficiary implementation working end-to-end,+including detection, parameter support, and error handling.+"""++import pytest+import json+from unittest.mock import AsyncMock, patch++from meta_ads_mcp.core.adsets import create_adset, get_adset_details+from meta_ads_mcp.core.accounts import get_account_info+++class TestDSAIntegration:+ """Integration tests for DSA beneficiary functionality"""++ @pytest.mark.asyncio+ async def test_dsa_beneficiary_complete_workflow(self):+ """Test complete DSA beneficiary workflow from detection to creation"""++ # Step 1: Detect DSA requirements for European account+ mock_account_response = {+ "id": "act_701351919139047",+ "name": "Test European Business Account",+ "account_status": 1,+ "business_country_code": "DE", # Germany - DSA compliant+ "business_city": "Berlin",+ "currency": "EUR"+ }++ with patch('meta_ads_mcp.core.accounts.make_api_request', new_callable=AsyncMock) as mock_account_api:+ with patch('meta_ads_mcp.core.api.get_current_access_token', new_callable=AsyncMock) as mock_auth:+ mock_auth.return_value = "test_access_token"+ mock_account_api.return_value = mock_account_response++ # Get account info and verify DSA detection+ result = await get_account_info(account_id="act_701351919139047")+ result_data = json.loads(result)++ # Verify DSA requirement is detected+ assert result_data["business_country_code"] == "DE"+ assert result_data["dsa_required"] == True+ assert "DSA (Digital Services Act)" in result_data["dsa_compliance_note"]++ # Step 2: Create ad set with DSA beneficiary+ mock_adset_response = {+ "id": "23842588888640185",+ "name": "Test European Ad Set",+ "status": "PAUSED",+ "dsa_beneficiary": "Test Organization GmbH"+ }++ with patch('meta_ads_mcp.core.adsets.make_api_request', new_callable=AsyncMock) as mock_adset_api:+ with patch('meta_ads_mcp.core.api.get_current_access_token', new_callable=AsyncMock) as mock_auth:+ mock_auth.return_value = "test_access_token"+ mock_adset_api.return_value = mock_adset_response++ # Create ad set with DSA beneficiary+ result = await create_adset(+ account_id="act_701351919139047",+ campaign_id="23842588888640184",+ name="Test European Ad Set",+ optimization_goal="LINK_CLICKS",+ billing_event="IMPRESSIONS",+ dsa_beneficiary="Test Organization GmbH"+ )++ result_data = json.loads(result)++ # Verify successful creation with DSA beneficiary+ assert result_data["id"] == "23842588888640185"+ assert result_data["dsa_beneficiary"] == "Test Organization GmbH"++ # Verify API call included DSA beneficiary parameter+ mock_adset_api.assert_called_once()+ call_args = mock_adset_api.call_args+ params = call_args[0][2] # Third argument is params+ assert "dsa_beneficiary" in params+ assert params["dsa_beneficiary"] == "Test Organization GmbH"++ @pytest.mark.asyncio+ async def test_dsa_beneficiary_error_handling_integration(self):+ """Test DSA beneficiary error handling in real-world scenarios"""++ # Test 1: Missing DSA beneficiary for European account+ mock_error_response = {+ "error": {+ "message": "Enter the person or organization that benefits from ads in this ad set",+ "type": "OAuthException",+ "code": 100+ }+ }++ with patch('meta_ads_mcp.core.adsets.make_api_request', new_callable=AsyncMock) as mock_api:+ with patch('meta_ads_mcp.core.api.get_current_access_token', new_callable=AsyncMock) as mock_auth:+ mock_auth.return_value = "test_access_token"+ mock_api.side_effect = Exception(json.dumps(mock_error_response))++ result = await create_adset(+ account_id="act_701351919139047",+ campaign_id="23842588888640184",+ name="Test European Ad Set",+ optimization_goal="LINK_CLICKS",+ billing_event="IMPRESSIONS"+ # No DSA beneficiary provided+ )++ result_data = json.loads(result)++ # Handle response wrapped in 'data' field by meta_api_tool decorator+ if "data" in result_data:+ actual_data = json.loads(result_data["data"])+ else:+ actual_data = result_data++ # Verify error is properly handled+ assert "error" in actual_data+ assert "benefits from ads" in actual_data["error"]++ # Test 2: Permission error for DSA beneficiary+ with patch('meta_ads_mcp.core.adsets.make_api_request', new_callable=AsyncMock) as mock_api:+ with patch('meta_ads_mcp.core.api.get_current_access_token', new_callable=AsyncMock) as mock_auth:+ mock_auth.return_value = "test_access_token"+ mock_api.side_effect = Exception("Permission denied: business_management permission required")++ result = await create_adset(+ account_id="act_701351919139047",+ campaign_id="23842588888640184",+ name="Test European Ad Set",+ optimization_goal="LINK_CLICKS",+ billing_event="IMPRESSIONS",+ dsa_beneficiary="Test Organization GmbH"+ )++ result_data = json.loads(result)++ # Handle response wrapped in 'data' field by meta_api_tool decorator+ if "data" in result_data:+ actual_data = json.loads(result_data["data"])+ else:+ actual_data = result_data++ # Verify permission error is handled+ assert "error" in actual_data+ assert "permission" in actual_data["error"].lower()++ @pytest.mark.asyncio+ async def test_dsa_beneficiary_regional_compliance_integration(self):+ """Test DSA beneficiary compliance across different regions"""++ # Test European account (DSA required)+ european_account_response = {+ "id": "act_de",+ "name": "German Business Account",+ "business_country_code": "DE",+ "account_status": 1+ }++ with patch('meta_ads_mcp.core.accounts.make_api_request', new_callable=AsyncMock) as mock_api:+ with patch('meta_ads_mcp.core.api.get_current_access_token', new_callable=AsyncMock) as mock_auth:+ mock_auth.return_value = "test_access_token"+ mock_api.return_value = european_account_response++ result = await get_account_info(account_id="act_de")+ result_data = json.loads(result)++ # Verify European account requires DSA+ assert result_data["business_country_code"] == "DE"+ assert result_data["dsa_required"] == True++ # Test US account (DSA not required)+ us_account_response = {+ "id": "act_us",+ "name": "US Business Account",+ "business_country_code": "US",+ "account_status": 1+ }++ with patch('meta_ads_mcp.core.accounts.make_api_request', new_callable=AsyncMock) as mock_api:+ with patch('meta_ads_mcp.core.api.get_current_access_token', new_callable=AsyncMock) as mock_auth:+ mock_auth.return_value = "test_access_token"+ mock_api.return_value = us_account_response++ result = await get_account_info(account_id="act_us")+ result_data = json.loads(result)++ # Verify US account doesn't require DSA+ assert result_data["business_country_code"] == "US"+ assert result_data["dsa_required"] == False++ @pytest.mark.asyncio+ async def test_dsa_beneficiary_parameter_formats_integration(self):+ """Test different DSA beneficiary parameter formats in real scenarios"""++ test_cases = [+ "Test Organization GmbH",+ "Test Organization, Inc.",+ "Test Organization Ltd.",+ "Test Organization AG",+ "Test Organization BV",+ "Test Organization SARL"+ ]++ for beneficiary_name in test_cases:+ mock_response = {+ "id": "23842588888640185",+ "name": "Test Ad Set",+ "status": "PAUSED",+ "dsa_beneficiary": beneficiary_name+ }++ with patch('meta_ads_mcp.core.adsets.make_api_request', new_callable=AsyncMock) as mock_api:+ with patch('meta_ads_mcp.core.api.get_current_access_token', new_callable=AsyncMock) as mock_auth:+ mock_auth.return_value = "test_access_token"+ mock_api.return_value = mock_response++ result = await create_adset(+ account_id="act_701351919139047",+ campaign_id="23842588888640184",+ name="Test Ad Set",+ optimization_goal="LINK_CLICKS",+ billing_event="IMPRESSIONS",+ dsa_beneficiary=beneficiary_name+ )++ result_data = json.loads(result)++ # Verify successful creation with different formats+ assert result_data["id"] == "23842588888640185"+ assert result_data["dsa_beneficiary"] == beneficiary_name++ @pytest.mark.asyncio+ async def test_dsa_beneficiary_retrieval_integration(self):+ """Test complete workflow including retrieving DSA beneficiary information"""++ # Step 1: Create ad set with DSA beneficiary+ mock_create_response = {+ "id": "120229746629010183",+ "name": "Test Ad Set with DSA",+ "status": "PAUSED"+ }++ with patch('meta_ads_mcp.core.adsets.make_api_request', new_callable=AsyncMock) as mock_api:+ with patch('meta_ads_mcp.core.api.get_current_access_token', new_callable=AsyncMock) as mock_auth:+ mock_auth.return_value = "test_access_token"+ mock_api.return_value = mock_create_response++ # Create ad set+ result = await create_adset(+ account_id="act_701351919139047",+ campaign_id="120229656904980183",+ name="Test Ad Set with DSA",+ optimization_goal="LINK_CLICKS",+ billing_event="IMPRESSIONS",+ dsa_beneficiary="Test Organization Inc"+ )++ result_data = json.loads(result)+ adset_id = result_data["id"]++ # Verify creation was successful+ assert adset_id == "120229746629010183"++ # Step 2: Retrieve ad set details including DSA beneficiary+ mock_details_response = {+ "id": "120229746629010183",+ "name": "Test Ad Set with DSA",+ "campaign_id": "120229656904980183",+ "status": "PAUSED",+ "daily_budget": "1000",+ "targeting": {+ "geo_locations": {"countries": ["US"]},+ "age_min": 25,+ "age_max": 65+ },+ "bid_amount": 200,+ "optimization_goal": "LINK_CLICKS",+ "billing_event": "IMPRESSIONS",+ "dsa_beneficiary": "Test Organization Inc"+ }++ with patch('meta_ads_mcp.core.adsets.make_api_request', new_callable=AsyncMock) as mock_api:+ with patch('meta_ads_mcp.core.api.get_current_access_token', new_callable=AsyncMock) as mock_auth:+ mock_auth.return_value = "test_access_token"+ mock_api.return_value = mock_details_response++ # Retrieve ad set details+ result = await get_adset_details(adset_id=adset_id)+ result_data = json.loads(result)++ # Verify DSA beneficiary field is retrieved correctly+ assert result_data["id"] == "120229746629010183"+ assert "dsa_beneficiary" in result_data+ assert result_data["dsa_beneficiary"] == "Test Organization Inc"++ # Verify API call included dsa_beneficiary in fields+ mock_api.assert_called_once()+ call_args = mock_api.call_args+ assert "dsa_beneficiary" in str(call_args)++ @pytest.mark.asyncio+ async def test_dsa_beneficiary_us_account_integration(self):+ """Test DSA beneficiary behavior for US accounts (optional parameter)"""++ # Step 1: Verify US account doesn't require DSA+ mock_us_account_response = {+ "id": "act_701351919139047",+ "name": "US Business Account",+ "business_country_code": "US",+ "account_status": 1+ }++ with patch('meta_ads_mcp.core.accounts.make_api_request', new_callable=AsyncMock) as mock_api:+ with patch('meta_ads_mcp.core.api.get_current_access_token', new_callable=AsyncMock) as mock_auth:+ mock_auth.return_value = "test_access_token"+ mock_api.return_value = mock_us_account_response++ result = await get_account_info(account_id="act_701351919139047")+ result_data = json.loads(result)++ # Verify US account doesn't require DSA+ assert result_data["business_country_code"] == "US"+ assert result_data["dsa_required"] == False++ # Step 2: Create ad set without DSA beneficiary (should work for US)+ mock_create_response = {+ "id": "120229746624860183",+ "name": "Test US Ad Set",+ "status": "PAUSED"+ }++ with patch('meta_ads_mcp.core.adsets.make_api_request', new_callable=AsyncMock) as mock_api:+ with patch('meta_ads_mcp.core.api.get_current_access_token', new_callable=AsyncMock) as mock_auth:+ mock_auth.return_value = "test_access_token"+ mock_api.return_value = mock_create_response++ result = await create_adset(+ account_id="act_701351919139047",+ campaign_id="120229656904980183",+ name="Test US Ad Set",+ optimization_goal="LINK_CLICKS",+ billing_event="IMPRESSIONS"+ # No DSA beneficiary provided+ )++ result_data = json.loads(result)++ # Verify creation was successful without DSA beneficiary+ assert result_data["id"] == "120229746624860183"++ # Step 3: Retrieve ad set details (should not have dsa_beneficiary field)+ mock_details_response = {+ "id": "120229746624860183",+ "name": "Test US Ad Set",+ "campaign_id": "120229656904980183",+ "status": "PAUSED",+ "daily_budget": "1000",+ "targeting": {+ "geo_locations": {"countries": ["US"]}+ },+ "bid_amount": 200,+ "optimization_goal": "LINK_CLICKS",+ "billing_event": "IMPRESSIONS"+ # No dsa_beneficiary field+ }++ with patch('meta_ads_mcp.core.adsets.make_api_request', new_callable=AsyncMock) as mock_api:+ with patch('meta_ads_mcp.core.api.get_current_access_token', new_callable=AsyncMock) as mock_auth:+ mock_auth.return_value = "test_access_token"+ mock_api.return_value = mock_details_response++ result = await get_adset_details(adset_id="120229746624860183")+ result_data = json.loads(result)++ # Verify ad set details are retrieved correctly+ assert result_data["id"] == "120229746624860183"+ assert "dsa_beneficiary" not in result_data # Should not be present for US accounts\ No newline at end of file