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.

Enhance create_adset function for mobile app campaigns

Yves Junqueira73c79d1348ea
diff --git a/meta_ads_mcp/core/adsets.py b/meta_ads_mcp/core/adsets.py
index e37d843..e021808 100644
--- a/meta_ads_mcp/core/adsets.py
+++ b/meta_ads_mcp/core/adsets.py
@@ -104,6 +104,8 @@ async def create_adset(
start_time: str = None,
end_time: str = None,
dsa_beneficiary: str = None,
+ promoted_object: Dict[str, Any] = None,
+ destination_type: str = None,
access_token: str = None
) -> str:
"""
@@ -118,13 +120,18 @@ async def create_adset(
lifetime_budget: Lifetime budget in account currency (in cents) as a string
targeting: Targeting specifications including age, location, interests, etc.
Use targeting_automation.advantage_audience=1 for automatic audience finding
- optimization_goal: Conversion optimization goal (e.g., 'LINK_CLICKS', 'REACH', 'CONVERSIONS')
+ optimization_goal: Conversion optimization goal (e.g., 'LINK_CLICKS', 'REACH', 'CONVERSIONS', 'APP_INSTALLS')
billing_event: How you're charged (e.g., 'IMPRESSIONS', 'LINK_CLICKS')
bid_amount: Bid amount in account currency (in cents)
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 compliance
+ promoted_object: Mobile app configuration for APP_INSTALLS campaigns. Required fields: application_id, object_store_url.
+ Optional fields: custom_event_type, pixel_id, page_id.
+ Example: {"application_id": "123456789012345", "object_store_url": "https://apps.apple.com/app/id123456789"}
+ destination_type: Where users are directed after clicking the ad (e.g., 'APP_STORE', 'DEEPLINK', 'APP_INSTALL').
+ Required for mobile app campaigns.
access_token: Meta API access token (optional - will use cached token if not provided)
"""
# Check required parameters
@@ -143,6 +150,59 @@ async def create_adset(
if not billing_event:
return json.dumps({"error": "No billing event provided"}, indent=2)
+ # Validate mobile app parameters for APP_INSTALLS campaigns
+ if optimization_goal == "APP_INSTALLS":
+ if not promoted_object:
+ return json.dumps({
+ "error": "promoted_object is required for APP_INSTALLS optimization goal",
+ "details": "Mobile app campaigns must specify which app is being promoted",
+ "required_fields": ["application_id", "object_store_url"]
+ }, indent=2)
+
+ # Validate promoted_object structure
+ if not isinstance(promoted_object, dict):
+ return json.dumps({
+ "error": "promoted_object must be a dictionary",
+ "example": {"application_id": "123456789012345", "object_store_url": "https://apps.apple.com/app/id123456789"}
+ }, indent=2)
+
+ # Validate required promoted_object fields
+ if "application_id" not in promoted_object:
+ return json.dumps({
+ "error": "promoted_object missing required field: application_id",
+ "details": "application_id is the Facebook app ID for your mobile app"
+ }, indent=2)
+
+ if "object_store_url" not in promoted_object:
+ return json.dumps({
+ "error": "promoted_object missing required field: object_store_url",
+ "details": "object_store_url should be the App Store or Google Play URL for your app"
+ }, indent=2)
+
+ # Validate store URL format
+ store_url = promoted_object["object_store_url"]
+ valid_store_patterns = [
+ "apps.apple.com", # iOS App Store
+ "play.google.com", # Google Play Store
+ "itunes.apple.com" # Alternative iOS format
+ ]
+
+ if not any(pattern in store_url for pattern in valid_store_patterns):
+ return json.dumps({
+ "error": "Invalid object_store_url format",
+ "details": "URL must be from App Store (apps.apple.com) or Google Play (play.google.com)",
+ "provided_url": store_url
+ }, indent=2)
+
+ # Validate destination_type if provided
+ if destination_type:
+ valid_destination_types = ["APP_STORE", "DEEPLINK", "APP_INSTALL"]
+ if destination_type not in valid_destination_types:
+ return json.dumps({
+ "error": f"Invalid destination_type: {destination_type}",
+ "valid_values": valid_destination_types
+ }, indent=2)
+
# Basic targeting is required if not provided
if not targeting:
targeting = {
@@ -187,6 +247,13 @@ async def create_adset(
if dsa_beneficiary:
params["dsa_beneficiary"] = dsa_beneficiary
+ # Add mobile app parameters if provided
+ if promoted_object:
+ params["promoted_object"] = json.dumps(promoted_object)
+
+ if destination_type:
+ params["destination_type"] = destination_type
+
try:
data = await make_api_request(endpoint, access_token, params, method="POST")
return json.dumps(data, indent=2)
diff --git a/pyproject.toml b/pyproject.toml
index 96f379d..d22f594 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -39,3 +39,11 @@ meta-ads-mcp = "meta_ads_mcp:entrypoint"
[tool.hatch.build.targets.wheel]
packages = ["meta_ads_mcp"]
+
+[tool.pytest.ini_options]
+markers = [
+ "e2e: marks tests as end-to-end (requires running MCP server) - excluded from default runs",
+]
+addopts = "-v --strict-markers -m 'not e2e'"
+testpaths = ["tests"]
+asyncio_mode = "auto"
diff --git a/tests/test_mobile_app_adset_creation.py b/tests/test_mobile_app_adset_creation.py
new file mode 100644
index 0000000..a47d144
--- /dev/null
+++ b/tests/test_mobile_app_adset_creation.py
@@ -0,0 +1,501 @@
+#!/usr/bin/env python3
+"""
+Unit Tests for Mobile App Adset Creation Functionality
+
+This test suite validates the mobile app parameters implementation for the
+create_adset function in meta_ads_mcp/core/adsets.py.
+
+Test cases cover:
+- Mobile app adset creation success scenarios
+- promoted_object parameter validation and formatting
+- destination_type parameter validation
+- Mobile app specific error handling
+- Cross-platform mobile app support (iOS, Android)
+- Integration with APP_INSTALLS optimization goal
+
+Usage:
+ uv run python -m pytest tests/test_mobile_app_adset_creation.py -v
+
+Related to Issue #008: Missing Mobile App Parameters in create_adset Function
+"""
+
+import pytest
+import json
+import asyncio
+from unittest.mock import AsyncMock, patch, MagicMock
+from typing import Dict, Any, List
+
+# Import the function to test
+from meta_ads_mcp.core.adsets import create_adset
+
+
+class TestMobileAppAdsetCreation:
+ """Test suite for mobile app adset creation functionality"""
+
+ @pytest.fixture
+ def mock_api_request(self):
+ """Mock for the make_api_request function"""
+ with patch('meta_ads_mcp.core.adsets.make_api_request') as mock:
+ mock.return_value = {
+ "id": "test_mobile_adset_id",
+ "name": "Test Mobile App Adset",
+ "optimization_goal": "APP_INSTALLS",
+ "promoted_object": {
+ "application_id": "123456789012345",
+ "object_store_url": "https://apps.apple.com/app/id123456789"
+ },
+ "destination_type": "APP_STORE"
+ }
+ yield mock
+
+ @pytest.fixture
+ def mock_auth_manager(self):
+ """Mock for the authentication manager"""
+ with patch('meta_ads_mcp.core.api.auth_manager') as mock, \
+ patch('meta_ads_mcp.core.api.get_current_access_token') as mock_get_token:
+ # Mock a valid access token
+ mock.get_current_access_token.return_value = "test_access_token"
+ mock.is_token_valid.return_value = True
+ mock.app_id = "test_app_id"
+ mock_get_token.return_value = "test_access_token"
+ yield mock
+
+ @pytest.fixture
+ def valid_mobile_app_params(self):
+ """Valid mobile app parameters for testing"""
+ return {
+ "account_id": "act_123456789",
+ "campaign_id": "campaign_123456789",
+ "name": "Test Mobile App Adset",
+ "optimization_goal": "APP_INSTALLS",
+ "billing_event": "IMPRESSIONS",
+ "targeting": {
+ "age_min": 18,
+ "age_max": 65,
+ "app_install_state": "not_installed",
+ "geo_locations": {"countries": ["US"]},
+ "user_device": ["Android_Smartphone", "iPhone"],
+ "user_os": ["Android", "iOS"]
+ }
+ }
+
+ @pytest.fixture
+ def ios_promoted_object(self):
+ """Valid iOS app promoted object"""
+ return {
+ "application_id": "123456789012345",
+ "object_store_url": "https://apps.apple.com/app/id123456789",
+ "custom_event_type": "APP_INSTALL"
+ }
+
+ @pytest.fixture
+ def android_promoted_object(self):
+ """Valid Android app promoted object"""
+ return {
+ "application_id": "987654321098765",
+ "object_store_url": "https://play.google.com/store/apps/details?id=com.example.app",
+ "custom_event_type": "APP_INSTALL"
+ }
+
+ @pytest.fixture
+ def promoted_object_with_pixel(self):
+ """Promoted object with Facebook pixel for tracking"""
+ return {
+ "application_id": "123456789012345",
+ "object_store_url": "https://apps.apple.com/app/id123456789",
+ "custom_event_type": "APP_INSTALL",
+ "pixel_id": "pixel_123456789"
+ }
+
+ # Test: Mobile App Adset Creation Success
+ @pytest.mark.asyncio
+ async def test_mobile_app_adset_creation_success_ios(
+ self, mock_api_request, mock_auth_manager, valid_mobile_app_params, ios_promoted_object
+ ):
+ """Test successful iOS mobile app adset creation"""
+
+ result = await create_adset(
+ **valid_mobile_app_params,
+ promoted_object=ios_promoted_object,
+ destination_type="APP_STORE"
+ )
+
+ # Parse the result
+ result_data = json.loads(result)
+
+ # Verify the API was called with correct parameters
+ mock_api_request.assert_called_once()
+ call_args = mock_api_request.call_args
+
+ # Check endpoint (first argument)
+ assert call_args[0][0] == f"{valid_mobile_app_params['account_id']}/adsets"
+
+ # Check parameters (third argument)
+ params = call_args[0][2]
+ assert 'promoted_object' in params
+ assert 'destination_type' in params
+
+ # Verify promoted_object is properly JSON-encoded
+ promoted_obj_param = json.loads(params['promoted_object']) if isinstance(params['promoted_object'], str) else params['promoted_object']
+ assert promoted_obj_param['application_id'] == ios_promoted_object['application_id']
+ assert promoted_obj_param['object_store_url'] == ios_promoted_object['object_store_url']
+
+ # Verify destination_type
+ assert params['destination_type'] == "APP_STORE"
+
+ # Verify response structure
+ assert 'id' in result_data
+ assert result_data['optimization_goal'] == "APP_INSTALLS"
+
+ @pytest.mark.asyncio
+ async def test_mobile_app_adset_creation_success_android(
+ self, mock_api_request, mock_auth_manager, valid_mobile_app_params, android_promoted_object
+ ):
+ """Test successful Android mobile app adset creation"""
+
+ result = await create_adset(
+ **valid_mobile_app_params,
+ promoted_object=android_promoted_object,
+ destination_type="APP_STORE"
+ )
+
+ # Parse the result
+ result_data = json.loads(result)
+
+ # Verify the API was called
+ mock_api_request.assert_called_once()
+ call_args = mock_api_request.call_args
+ params = call_args[0][2]
+
+ # Verify Android-specific promoted_object
+ promoted_obj_param = json.loads(params['promoted_object']) if isinstance(params['promoted_object'], str) else params['promoted_object']
+ assert promoted_obj_param['application_id'] == android_promoted_object['application_id']
+ assert "play.google.com" in promoted_obj_param['object_store_url']
+
+ # Verify response
+ assert 'id' in result_data
+
+ @pytest.mark.asyncio
+ async def test_mobile_app_adset_with_pixel_tracking(
+ self, mock_api_request, mock_auth_manager, valid_mobile_app_params, promoted_object_with_pixel
+ ):
+ """Test mobile app adset creation with Facebook pixel tracking"""
+
+ result = await create_adset(
+ **valid_mobile_app_params,
+ promoted_object=promoted_object_with_pixel,
+ destination_type="APP_STORE"
+ )
+
+ # Verify pixel_id is included
+ call_args = mock_api_request.call_args
+ params = call_args[0][2]
+ promoted_obj_param = json.loads(params['promoted_object']) if isinstance(params['promoted_object'], str) else params['promoted_object']
+
+ assert 'pixel_id' in promoted_obj_param
+ assert promoted_obj_param['pixel_id'] == promoted_object_with_pixel['pixel_id']
+
+ # Test: Parameter Validation
+ @pytest.mark.asyncio
+ async def test_invalid_promoted_object_missing_application_id(
+ self, mock_api_request, mock_auth_manager, valid_mobile_app_params
+ ):
+ """Test validation error for promoted_object missing application_id"""
+
+ invalid_promoted_object = {
+ "object_store_url": "https://apps.apple.com/app/id123456789",
+ "custom_event_type": "APP_INSTALL"
+ }
+
+ result = await create_adset(
+ **valid_mobile_app_params,
+ promoted_object=invalid_promoted_object,
+ destination_type="APP_STORE"
+ )
+
+ result_data = json.loads(result)
+
+ # Should return validation error - check for data wrapper format
+ if "data" in result_data:
+ error_data = json.loads(result_data["data"])
+ assert 'error' in error_data
+ assert 'application_id' in error_data['error'].lower()
+ else:
+ assert 'error' in result_data
+ assert 'application_id' in result_data['error'].lower()
+
+ @pytest.mark.asyncio
+ async def test_invalid_promoted_object_missing_store_url(
+ self, mock_api_request, mock_auth_manager, valid_mobile_app_params
+ ):
+ """Test validation error for promoted_object missing object_store_url"""
+
+ invalid_promoted_object = {
+ "application_id": "123456789012345",
+ "custom_event_type": "APP_INSTALL"
+ }
+
+ result = await create_adset(
+ **valid_mobile_app_params,
+ promoted_object=invalid_promoted_object,
+ destination_type="APP_STORE"
+ )
+
+ result_data = json.loads(result)
+
+ # Should return validation error - check for data wrapper format
+ if "data" in result_data:
+ error_data = json.loads(result_data["data"])
+ assert 'error' in error_data
+ assert 'object_store_url' in error_data['error'].lower()
+ else:
+ assert 'error' in result_data
+ assert 'object_store_url' in result_data['error'].lower()
+
+ @pytest.mark.asyncio
+ async def test_invalid_destination_type(
+ self, mock_api_request, mock_auth_manager, valid_mobile_app_params, ios_promoted_object
+ ):
+ """Test validation error for invalid destination_type value"""
+
+ result = await create_adset(
+ **valid_mobile_app_params,
+ promoted_object=ios_promoted_object,
+ destination_type="INVALID_TYPE"
+ )
+
+ result_data = json.loads(result)
+
+ # Should return validation error - check for data wrapper format
+ if "data" in result_data:
+ error_data = json.loads(result_data["data"])
+ assert 'error' in error_data
+ assert 'destination_type' in error_data['error'].lower()
+ else:
+ assert 'error' in result_data
+ assert 'destination_type' in result_data['error'].lower()
+
+ @pytest.mark.asyncio
+ async def test_app_installs_requires_promoted_object(
+ self, mock_api_request, mock_auth_manager, valid_mobile_app_params
+ ):
+ """Test that APP_INSTALLS optimization goal requires promoted_object"""
+
+ result = await create_adset(
+ **valid_mobile_app_params,
+ # Missing promoted_object
+ destination_type="APP_STORE"
+ )
+
+ result_data = json.loads(result)
+
+ # Should return validation error - check for data wrapper format
+ if "data" in result_data:
+ error_data = json.loads(result_data["data"])
+ assert 'error' in error_data
+ assert 'promoted_object' in error_data['error'].lower()
+ assert 'app_installs' in error_data['error'].lower()
+ else:
+ assert 'error' in result_data
+ assert 'promoted_object' in result_data['error'].lower()
+ assert 'app_installs' in result_data['error'].lower()
+
+ # Test: Cross-platform Support
+ @pytest.mark.asyncio
+ async def test_ios_app_store_url_validation(
+ self, mock_api_request, mock_auth_manager, valid_mobile_app_params
+ ):
+ """Test iOS App Store URL format validation"""
+
+ ios_promoted_object = {
+ "application_id": "123456789012345",
+ "object_store_url": "https://apps.apple.com/app/id123456789",
+ "custom_event_type": "APP_INSTALL"
+ }
+
+ result = await create_adset(
+ **valid_mobile_app_params,
+ promoted_object=ios_promoted_object,
+ destination_type="APP_STORE"
+ )
+
+ result_data = json.loads(result)
+
+ # Should succeed for valid iOS URL
+ assert 'error' not in result_data or result_data.get('error') is None
+
+ @pytest.mark.asyncio
+ async def test_google_play_url_validation(
+ self, mock_api_request, mock_auth_manager, valid_mobile_app_params
+ ):
+ """Test Google Play Store URL format validation"""
+
+ android_promoted_object = {
+ "application_id": "987654321098765",
+ "object_store_url": "https://play.google.com/store/apps/details?id=com.example.app",
+ "custom_event_type": "APP_INSTALL"
+ }
+
+ result = await create_adset(
+ **valid_mobile_app_params,
+ promoted_object=android_promoted_object,
+ destination_type="APP_STORE"
+ )
+
+ result_data = json.loads(result)
+
+ # Should succeed for valid Google Play URL
+ assert 'error' not in result_data or result_data.get('error') is None
+
+ @pytest.mark.asyncio
+ async def test_invalid_store_url_format(
+ self, mock_api_request, mock_auth_manager, valid_mobile_app_params
+ ):
+ """Test validation error for invalid app store URL format"""
+
+ invalid_promoted_object = {
+ "application_id": "123456789012345",
+ "object_store_url": "https://example.com/invalid-url",
+ "custom_event_type": "APP_INSTALL"
+ }
+
+ result = await create_adset(
+ **valid_mobile_app_params,
+ promoted_object=invalid_promoted_object,
+ destination_type="APP_STORE"
+ )
+
+ result_data = json.loads(result)
+
+ # Should return validation error for invalid URL - check for data wrapper format
+ if "data" in result_data:
+ error_data = json.loads(result_data["data"])
+ assert 'error' in error_data
+ assert 'store url' in error_data['error'].lower() or 'object_store_url' in error_data['error'].lower()
+ else:
+ assert 'error' in result_data
+ assert 'store url' in result_data['error'].lower() or 'object_store_url' in result_data['error'].lower()
+
+ # Test: Destination Type Variations
+ @pytest.mark.asyncio
+ async def test_deeplink_destination_type(
+ self, mock_api_request, mock_auth_manager, valid_mobile_app_params, ios_promoted_object
+ ):
+ """Test DEEPLINK destination_type"""
+
+ result = await create_adset(
+ **valid_mobile_app_params,
+ promoted_object=ios_promoted_object,
+ destination_type="DEEPLINK"
+ )
+
+ call_args = mock_api_request.call_args
+ params = call_args[0][2]
+ assert params['destination_type'] == "DEEPLINK"
+
+ @pytest.mark.asyncio
+ async def test_app_install_destination_type(
+ self, mock_api_request, mock_auth_manager, valid_mobile_app_params, ios_promoted_object
+ ):
+ """Test APP_INSTALL destination_type"""
+
+ result = await create_adset(
+ **valid_mobile_app_params,
+ promoted_object=ios_promoted_object,
+ destination_type="APP_INSTALL"
+ )
+
+ call_args = mock_api_request.call_args
+ params = call_args[0][2]
+ assert params['destination_type'] == "APP_INSTALL"
+
+ # Test: Error Handling
+ @pytest.mark.asyncio
+ async def test_meta_api_error_handling(
+ self, mock_auth_manager, valid_mobile_app_params, ios_promoted_object
+ ):
+ """Test handling of Meta API errors for mobile app adsets"""
+
+ with patch('meta_ads_mcp.core.adsets.make_api_request') as mock_api:
+ # Mock Meta API error response
+ mock_api.side_effect = Exception("HTTP Error: 400 - Select a dataset and conversion event for your ad set")
+
+ result = await create_adset(
+ **valid_mobile_app_params,
+ promoted_object=ios_promoted_object,
+ destination_type="APP_STORE"
+ )
+
+ result_data = json.loads(result)
+
+ # Should handle the error gracefully - check for data wrapper format
+ if "data" in result_data:
+ error_data = json.loads(result_data["data"])
+ assert 'error' in error_data
+ # Check for error text in either error message or details
+ error_text = error_data.get('error', '').lower()
+ details_text = error_data.get('details', '').lower()
+ assert 'dataset' in error_text or 'conversion event' in error_text or \
+ 'dataset' in details_text or 'conversion event' in details_text
+ else:
+ assert 'error' in result_data
+ error_text = result_data.get('error', '').lower()
+ details_text = result_data.get('details', '').lower()
+ assert 'dataset' in error_text or 'conversion event' in error_text or \
+ 'dataset' in details_text or 'conversion event' in details_text
+
+ # Test: Backward Compatibility
+ @pytest.mark.asyncio
+ async def test_backward_compatibility_non_mobile_campaigns(
+ self, mock_api_request, mock_auth_manager
+ ):
+ """Test that non-mobile campaigns still work without mobile app parameters"""
+
+ non_mobile_params = {
+ "account_id": "act_123456789",
+ "campaign_id": "campaign_123456789",
+ "name": "Test Web Adset",
+ "optimization_goal": "LINK_CLICKS",
+ "billing_event": "LINK_CLICKS",
+ "targeting": {
+ "age_min": 18,
+ "age_max": 65,
+ "geo_locations": {"countries": ["US"]}
+ }
+ }
+
+ result = await create_adset(**non_mobile_params)
+
+ # Should work without mobile app parameters
+ mock_api_request.assert_called_once()
+ call_args = mock_api_request.call_args
+ params = call_args[0][2]
+
+ # Should not include mobile app parameters
+ assert 'promoted_object' not in params
+ assert 'destination_type' not in params
+
+ @pytest.mark.asyncio
+ async def test_optional_mobile_parameters(
+ self, mock_api_request, mock_auth_manager, valid_mobile_app_params, ios_promoted_object
+ ):
+ """Test that mobile app parameters are optional for non-APP_INSTALLS campaigns"""
+
+ non_app_install_params = valid_mobile_app_params.copy()
+ non_app_install_params['optimization_goal'] = "REACH"
+
+ result = await create_adset(
+ **non_app_install_params,
+ # Mobile app parameters should be optional for non-APP_INSTALLS
+ promoted_object=ios_promoted_object,
+ destination_type="APP_STORE"
+ )
+
+ # Should work and include mobile parameters if provided
+ mock_api_request.assert_called_once()
+ call_args = mock_api_request.call_args
+ params = call_args[0][2]
+
+ # Mobile parameters should be included if provided
+ assert 'promoted_object' in params
+ assert 'destination_type' in params
\ No newline at end of file
diff --git a/tests/test_mobile_app_adset_issue.py b/tests/test_mobile_app_adset_issue.py
new file mode 100644
index 0000000..457e20a
--- /dev/null
+++ b/tests/test_mobile_app_adset_issue.py
@@ -0,0 +1,315 @@
+#!/usr/bin/env python3
+"""
+E2E Test for mobile app adset creation issue (Issue #008)
+
+This test validates that the create_adset tool supports required parameters
+for mobile app campaigns:
+- promoted_object configuration
+- destination_type settings
+- Conversion event dataset linking
+- Custom event type specification
+
+Expected Meta API error when parameters are missing:
+"Select a dataset and conversion event for your ad set (Code 100)"
+
+Usage (Manual execution only):
+ 1. Start the server: uv run python -m meta_ads_mcp --transport streamable-http --port 8080
+ 2. Run test: uv run python tests/test_mobile_app_adset_issue.py
+
+Or with pytest (explicit E2E flag required):
+ uv run python -m pytest tests/test_mobile_app_adset_issue.py -v -m e2e
+
+Note: This test is marked as E2E and will NOT run automatically in CI.
+It must be executed manually to validate mobile app campaign functionality.
+"""
+
+import pytest
+import requests
+import json
+import time
+import sys
+import os
+from typing import Dict, Any
+
+# Add project root to path for imports
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+class MobileAppAdsetTester:
+ """Test suite for mobile app adset creation 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
+
+ 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 for MCP protocol with streamable HTTP transport
+ default_headers = {
+ "Content-Type": "application/json",
+ "Accept": "application/json, text/event-stream",
+ "User-Agent": "MobileApp-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=30 # Increased timeout for API calls
+ )
+
+ 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_create_adset_tool_exists(self) -> Dict[str, Any]:
+ """Test that create_adset tool exists and check its parameters"""
+ result = self._make_request("tools/list", {})
+
+ if not result["success"]:
+ return {"success": False, "error": "Failed to get tools list"}
+
+ tools = result["json"]["result"].get("tools", [])
+ create_adset_tool = next((tool for tool in tools if tool["name"] == "create_adset"), None)
+
+ if not create_adset_tool:
+ return {"success": False, "error": "create_adset tool not found"}
+
+ # Check if mobile app specific parameters are supported
+ input_schema = create_adset_tool.get("inputSchema", {})
+ properties = input_schema.get("properties", {})
+
+ mobile_app_params = ["promoted_object", "destination_type"]
+ missing_params = []
+
+ for param in mobile_app_params:
+ if param not in properties:
+ missing_params.append(param)
+
+ return {
+ "success": True,
+ "tool": create_adset_tool,
+ "missing_mobile_app_params": missing_params,
+ "has_mobile_app_support": len(missing_params) == 0
+ }
+
+ def test_reproduce_mobile_app_error(self) -> Dict[str, Any]:
+ """Reproduce mobile app adset creation error scenario"""
+
+ # Test parameters for mobile app campaign
+ test_params = {
+ "name": "create_adset",
+ "arguments": {
+ "account_id": "act_123456789012345", # Generic test account
+ "campaign_id": "120230566078340163", # This will likely be invalid but that's OK for testing
+ "name": "test mobile app ad set",
+ "status": "PAUSED",
+ "targeting": {
+ "age_max": 65,
+ "age_min": 18,
+ "app_install_state": "not_installed",
+ "geo_locations": {
+ "countries": ["DE"],
+ "location_types": ["home", "recent"]
+ },
+ "user_device": ["Android_Smartphone", "Android_Tablet"],
+ "user_os": ["Android"],
+ "brand_safety_content_filter_levels": ["FACEBOOK_STANDARD", "AN_STANDARD"],
+ "targeting_automation": {"advantage_audience": 1}
+ },
+ "optimization_goal": "APP_INSTALLS",
+ "billing_event": "IMPRESSIONS"
+ }
+ }
+
+ result = self._make_request("tools/call", test_params)
+
+ if not result["success"]:
+ return {
+ "success": False,
+ "error": f"MCP call failed: {result.get('text', 'Unknown error')}"
+ }
+
+ # Parse the response
+ response_data = result["json"]["result"]
+ content = response_data.get("content", [{}])[0].get("text", "")
+
+ try:
+ parsed_content = json.loads(content)
+
+ # Check if this is an error response
+ if "error" in parsed_content:
+ error_details = parsed_content["error"]
+ if isinstance(error_details, dict) and "details" in error_details:
+ meta_error = error_details["details"]
+
+ # Check for the specific error we're looking for
+ if isinstance(meta_error, dict) and "error" in meta_error:
+ error_code = meta_error["error"].get("code")
+ error_message = meta_error["error"].get("error_user_msg", "")
+
+ is_dataset_error = (
+ error_code == 100 and
+ "conversion event" in error_message.lower()
+ )
+
+ return {
+ "success": True,
+ "reproduced_error": is_dataset_error,
+ "error_code": error_code,
+ "error_message": error_message,
+ "full_response": parsed_content
+ }
+
+ return {
+ "success": True,
+ "reproduced_error": False,
+ "unexpected_response": parsed_content
+ }
+
+ except json.JSONDecodeError as e:
+ return {
+ "success": False,
+ "error": f"Failed to parse response: {e}",
+ "raw_content": content
+ }
+
+# Pytest E2E test class - marked to prevent automatic execution
[email protected](reason="E2E test - requires running MCP server - execute manually only")
+class TestMobileAppAdsetIssueE2E:
+ """E2E test for mobile app adset creation functionality (Issue #008)"""
+
+ def setup_method(self):
+ """Set up test instance"""
+ self.tester = MobileAppAdsetTester()
+
+ def test_create_adset_tool_has_mobile_app_params(self):
+ """Test that create_adset tool exists and has mobile app parameters"""
+ result = self.tester.test_create_adset_tool_exists()
+
+ assert result["success"], f"Tool test failed: {result.get('error', 'Unknown error')}"
+
+ missing_params = result["missing_mobile_app_params"]
+ has_mobile_support = result["has_mobile_app_support"]
+
+ # Report results but don't fail if parameters are missing (this is what we're testing)
+ if missing_params:
+ pytest.skip(f"Missing mobile app parameters: {missing_params}")
+ else:
+ # Parameters are present - mobile app support is available
+ assert has_mobile_support, "Tool should have mobile app support when parameters are present"
+
+ def test_reproduce_mobile_app_error_scenario(self):
+ """Test reproducing mobile app adset creation error scenario"""
+ result = self.tester.test_reproduce_mobile_app_error()
+
+ assert result["success"], f"Error reproduction test failed: {result.get('error', 'Unknown error')}"
+
+ # This test is mainly for validation, not assertion
+ # The actual error depends on authentication and server state
+ if result.get("reproduced_error"):
+ print(f"Reproduced error - Code: {result.get('error_code')}, Message: {result.get('error_message')}")
+ else:
+ print("Different response received (may indicate parameters are working or auth issues)")
+
+
+def main():
+ """Run mobile app adset creation tests (manual execution)"""
+ print("🚀 Mobile App Adset Creation E2E Test")
+ print("=" * 50)
+ print("⚠️ This is an E2E test - requires MCP server running on localhost:8080")
+ print(" Start server with: uv run python -m meta_ads_mcp --transport streamable-http --port 8080")
+ print()
+
+ tester = MobileAppAdsetTester()
+
+ # Test 1: Check if create_adset tool exists and has mobile app parameters
+ print("\n🧪 Test 1: Checking create_adset tool parameters...")
+ tool_test = tester.test_create_adset_tool_exists()
+
+ if tool_test["success"]:
+ missing_params = tool_test["missing_mobile_app_params"]
+ if missing_params:
+ print(f"❌ Missing mobile app parameters: {missing_params}")
+ print("⚠️ Mobile app campaigns may not work without these parameters")
+ else:
+ print("✅ All mobile app parameters are present")
+ else:
+ print(f"❌ Tool test failed: {tool_test['error']}")
+
+ # Test 2: Try to reproduce mobile app error scenario
+ print("\n🧪 Test 2: Testing mobile app campaign creation...")
+ error_test = tester.test_reproduce_mobile_app_error()
+
+ if error_test["success"]:
+ if error_test.get("reproduced_error"):
+ print("✅ Successfully reproduced the error!")
+ print(f" Error Code: {error_test['error_code']}")
+ print(f" Error Message: {error_test['error_message']}")
+ else:
+ print("⚠️ Error not reproduced - different response received")
+ if "unexpected_response" in error_test:
+ print(f" Response: {json.dumps(error_test['unexpected_response'], indent=2)}")
+ else:
+ print(f"❌ Error reproduction test failed: {error_test['error']}")
+
+ # Summary
+ print("\n🏁 TEST SUMMARY")
+ print("=" * 30)
+
+ if tool_test["success"]:
+ missing_params = tool_test["missing_mobile_app_params"]
+ issue_confirmed = len(missing_params) > 0
+ fix_validated = len(missing_params) == 0
+
+ if fix_validated:
+ print("✅ MOBILE APP SUPPORT VALIDATED")
+ print(" All required mobile app parameters are present")
+ print(" Mobile app campaigns should work correctly!")
+ elif issue_confirmed:
+ print("❌ MOBILE APP SUPPORT INCOMPLETE")
+ print(f" Missing parameters: {missing_params}")
+ print(" Mobile app campaigns may fail without these parameters")
+ else:
+ print("❓ STATUS UNCLEAR")
+ print(" Could not determine mobile app parameter status")
+ else:
+ print("❌ TEST FAILED")
+ print(" Could not connect to MCP server or validate tools")
+
+ return 0
+
+if __name__ == "__main__":
+ sys.exit(main())
\ No newline at end of file