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.

Bump version to 0.7.10

Yves Junqueirac720dd6f26ee
diff --git a/meta_ads_mcp/__init__.py b/meta_ads_mcp/__init__.py
index c2860dc..e1abc0a 100644
--- a/meta_ads_mcp/__init__.py
+++ b/meta_ads_mcp/__init__.py
@@ -7,7 +7,7 @@ with the Claude LLM.
from meta_ads_mcp.core.server import main
-__version__ = "0.7.9"
+__version__ = "0.7.10"
__all__ = [
'get_ad_accounts',
diff --git a/meta_ads_mcp/core/ads.py b/meta_ads_mcp/core/ads.py
index f2c0835..8171dca 100644
--- a/meta_ads_mcp/core/ads.py
+++ b/meta_ads_mcp/core/ads.py
@@ -670,31 +670,31 @@ async def create_ad_creative(
if not account_id.startswith("act_"):
account_id = f"act_{account_id}"
- # If no page ID is provided, try to find a page associated with the account
+ # Enhanced page discovery: If no page ID is provided, use robust discovery methods
if not page_id:
try:
- # Query to get pages associated with the account
- pages_endpoint = f"{account_id}/assigned_pages"
- pages_params = {
- "fields": "id,name",
- "limit": 1
- }
-
- pages_data = await make_api_request(pages_endpoint, access_token, pages_params)
+ # Use the comprehensive page discovery logic from get_account_pages
+ page_discovery_result = await _discover_pages_for_account(account_id, access_token)
- if "data" in pages_data and pages_data["data"]:
- page_id = pages_data["data"][0]["id"]
- print(f"Using page ID: {page_id} ({pages_data['data'][0].get('name', 'Unknown')})")
+ if page_discovery_result.get("success"):
+ page_id = page_discovery_result["page_id"]
+ page_name = page_discovery_result.get("page_name", "Unknown")
+ print(f"Auto-discovered page ID: {page_id} ({page_name})")
else:
return json.dumps({
- "error": "No page ID provided and no pages found for this account",
- "suggestion": "Please provide a page_id parameter"
+ "error": "No page ID provided and no suitable pages found for this account",
+ "details": page_discovery_result.get("message", "Page discovery failed"),
+ "suggestions": [
+ "Use get_account_pages to see available pages",
+ "Use search_pages_by_name to find specific pages",
+ "Provide a page_id parameter manually"
+ ]
}, indent=2)
except Exception as e:
return json.dumps({
- "error": "Error finding page for account",
+ "error": "Error during page discovery",
"details": str(e),
- "suggestion": "Please provide a page_id parameter"
+ "suggestion": "Please provide a page_id parameter or use get_account_pages to find available pages"
}, indent=2)
# Prepare the creative data
@@ -759,6 +759,191 @@ async def create_ad_creative(
}, indent=2)
+async def _discover_pages_for_account(account_id: str, access_token: str) -> dict:
+ """
+ Internal function to discover pages for an account using multiple approaches.
+ Returns the best available page ID for ad creation.
+ """
+ try:
+ # Approach 1: Extract page IDs from tracking_specs in ads (most reliable)
+ endpoint = f"{account_id}/ads"
+ params = {
+ "fields": "id,name,adset_id,campaign_id,status,creative,created_time,updated_time,bid_amount,conversion_domain,tracking_specs",
+ "limit": 100
+ }
+
+ tracking_ads_data = await make_api_request(endpoint, access_token, params)
+
+ tracking_page_ids = set()
+ if "data" in tracking_ads_data:
+ for ad in tracking_ads_data.get("data", []):
+ tracking_specs = ad.get("tracking_specs", [])
+ if isinstance(tracking_specs, list):
+ for spec in tracking_specs:
+ if isinstance(spec, dict) and "page" in spec:
+ page_list = spec["page"]
+ if isinstance(page_list, list):
+ for page_id in page_list:
+ if isinstance(page_id, (str, int)) and str(page_id).isdigit():
+ tracking_page_ids.add(str(page_id))
+
+ if tracking_page_ids:
+ # Get details for the first page found
+ page_id = list(tracking_page_ids)[0]
+ page_endpoint = f"{page_id}"
+ page_params = {
+ "fields": "id,name,username,category,fan_count,link,verification_status,picture"
+ }
+
+ page_data = await make_api_request(page_endpoint, access_token, page_params)
+ if "id" in page_data:
+ return {
+ "success": True,
+ "page_id": page_id,
+ "page_name": page_data.get("name", "Unknown"),
+ "source": "tracking_specs",
+ "note": "Page ID extracted from existing ads - most reliable for ad creation"
+ }
+
+ # Approach 2: Try client_pages endpoint
+ endpoint = f"{account_id}/client_pages"
+ params = {
+ "fields": "id,name,username,category,fan_count,link,verification_status,picture"
+ }
+
+ client_pages_data = await make_api_request(endpoint, access_token, params)
+
+ if "data" in client_pages_data and client_pages_data["data"]:
+ page = client_pages_data["data"][0]
+ return {
+ "success": True,
+ "page_id": page["id"],
+ "page_name": page.get("name", "Unknown"),
+ "source": "client_pages"
+ }
+
+ # Approach 3: Try assigned_pages endpoint
+ pages_endpoint = f"{account_id}/assigned_pages"
+ pages_params = {
+ "fields": "id,name",
+ "limit": 1
+ }
+
+ pages_data = await make_api_request(pages_endpoint, access_token, pages_params)
+
+ if "data" in pages_data and pages_data["data"]:
+ page = pages_data["data"][0]
+ return {
+ "success": True,
+ "page_id": page["id"],
+ "page_name": page.get("name", "Unknown"),
+ "source": "assigned_pages"
+ }
+
+ # If all approaches failed
+ return {
+ "success": False,
+ "message": "No suitable pages found for this account",
+ "note": "Try using get_account_pages to see all available pages or provide page_id manually"
+ }
+
+ except Exception as e:
+ return {
+ "success": False,
+ "message": f"Error during page discovery: {str(e)}"
+ }
+
+
+async def _search_pages_by_name_core(access_token: str, account_id: str, search_term: str = None) -> str:
+ """
+ Core logic for searching pages by name.
+
+ Args:
+ access_token: Meta API access token
+ account_id: Meta Ads account ID (format: act_XXXXXXXXX)
+ search_term: Search term to find pages by name (optional - returns all pages if not provided)
+
+ Returns:
+ JSON string with search results
+ """
+ # Ensure account_id has the 'act_' prefix
+ if not account_id.startswith("act_"):
+ account_id = f"act_{account_id}"
+
+ try:
+ # Use the internal discovery function directly
+ page_discovery_result = await _discover_pages_for_account(account_id, access_token)
+
+ if not page_discovery_result.get("success"):
+ return json.dumps({
+ "data": [],
+ "message": "No pages found for this account",
+ "details": page_discovery_result.get("message", "Page discovery failed")
+ }, indent=2)
+
+ # Create a single page result
+ page_data = {
+ "id": page_discovery_result["page_id"],
+ "name": page_discovery_result.get("page_name", "Unknown"),
+ "source": page_discovery_result.get("source", "unknown")
+ }
+
+ all_pages_data = {"data": [page_data]}
+
+ # Filter pages by search term if provided
+ if search_term:
+ search_term_lower = search_term.lower()
+ filtered_pages = []
+
+ for page in all_pages_data["data"]:
+ page_name = page.get("name", "").lower()
+ if search_term_lower in page_name:
+ filtered_pages.append(page)
+
+ return json.dumps({
+ "data": filtered_pages,
+ "search_term": search_term,
+ "total_found": len(filtered_pages),
+ "total_available": len(all_pages_data["data"])
+ }, indent=2)
+ else:
+ # Return all pages if no search term provided
+ return json.dumps({
+ "data": all_pages_data["data"],
+ "total_available": len(all_pages_data["data"]),
+ "note": "Use search_term parameter to filter pages by name"
+ }, indent=2)
+
+ except Exception as e:
+ return json.dumps({
+ "error": "Failed to search pages by name",
+ "details": str(e)
+ }, indent=2)
+
+
+@mcp_server.tool()
+@meta_api_tool
+async def search_pages_by_name(access_token: str = None, account_id: str = None, search_term: str = None) -> str:
+ """
+ Search for pages by name within an account.
+
+ Args:
+ access_token: Meta API access token (optional - will use cached token if not provided)
+ account_id: Meta Ads account ID (format: act_XXXXXXXXX)
+ search_term: Search term to find pages by name (optional - returns all pages if not provided)
+
+ Returns:
+ JSON response with matching pages
+ """
+ # Check required parameters
+ if not account_id:
+ return json.dumps({"error": "No account ID provided"}, indent=2)
+
+ # Call the core function
+ result = await _search_pages_by_name_core(access_token, account_id, search_term)
+ return result
+
+
@mcp_server.tool()
@meta_api_tool
async def get_account_pages(access_token: str = None, account_id: str = None) -> str:
diff --git a/pyproject.toml b/pyproject.toml
index 99a9536..9bd8b51 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "meta-ads-mcp"
-version = "0.7.9"
+version = "0.7.10"
description = "Model Context Protocol (MCP) plugin for interacting with Meta Ads API"
readme = "README.md"
requires-python = ">=3.10"
diff --git a/tests/test_page_discovery.py b/tests/test_page_discovery.py
new file mode 100644
index 0000000..c7d53d0
--- /dev/null
+++ b/tests/test_page_discovery.py
@@ -0,0 +1,377 @@
+"""
+Test page discovery functionality for Meta Ads MCP.
+"""
+
+import pytest
+import json
+from unittest.mock import AsyncMock, patch
+from meta_ads_mcp.core.ads import _discover_pages_for_account, search_pages_by_name, _search_pages_by_name_core
+
+
+class TestPageDiscovery:
+ """Test page discovery functionality."""
+
+ @pytest.mark.asyncio
+ async def test_discover_pages_from_tracking_specs(self):
+ """Test page discovery from tracking specs (most reliable method)."""
+ mock_ads_data = {
+ "data": [
+ {
+ "id": "123456789",
+ "tracking_specs": [
+ {
+ "page": ["987654321", "111222333"]
+ }
+ ]
+ }
+ ]
+ }
+
+ mock_page_data = {
+ "id": "987654321",
+ "name": "Test Page",
+ "username": "testpage",
+ "category": "Test Category"
+ }
+
+ with patch('meta_ads_mcp.core.ads.make_api_request') as mock_api:
+ # Mock the ads endpoint call
+ mock_api.side_effect = [
+ mock_ads_data, # First call for ads
+ mock_page_data # Second call for page details
+ ]
+
+ result = await _discover_pages_for_account("act_123456789", "test_token")
+
+ assert result["success"] is True
+ # Check that we got one of the expected page IDs (set order is not guaranteed)
+ assert result["page_id"] in ["987654321", "111222333"]
+ assert result["page_name"] == "Test Page"
+ assert result["source"] == "tracking_specs"
+
+ @pytest.mark.asyncio
+ async def test_discover_pages_from_client_pages(self):
+ """Test page discovery from client_pages endpoint."""
+ mock_client_pages_data = {
+ "data": [
+ {
+ "id": "555666777",
+ "name": "Client Page",
+ "username": "clientpage"
+ }
+ ]
+ }
+
+ # Mock empty ads data, then client_pages data
+ with patch('meta_ads_mcp.core.ads.make_api_request') as mock_api:
+ mock_api.side_effect = [
+ {"data": []}, # No ads found
+ mock_client_pages_data # Client pages found
+ ]
+
+ result = await _discover_pages_for_account("act_123456789", "test_token")
+
+ assert result["success"] is True
+ assert result["page_id"] == "555666777"
+ assert result["page_name"] == "Client Page"
+ assert result["source"] == "client_pages"
+
+ @pytest.mark.asyncio
+ async def test_discover_pages_from_assigned_pages(self):
+ """Test page discovery from assigned_pages endpoint."""
+ mock_assigned_pages_data = {
+ "data": [
+ {
+ "id": "888999000",
+ "name": "Assigned Page"
+ }
+ ]
+ }
+
+ # Mock empty responses for first two methods, then assigned_pages
+ with patch('meta_ads_mcp.core.ads.make_api_request') as mock_api:
+ mock_api.side_effect = [
+ {"data": []}, # No ads found
+ {"data": []}, # No client pages found
+ mock_assigned_pages_data # Assigned pages found
+ ]
+
+ result = await _discover_pages_for_account("act_123456789", "test_token")
+
+ assert result["success"] is True
+ assert result["page_id"] == "888999000"
+ assert result["page_name"] == "Assigned Page"
+ assert result["source"] == "assigned_pages"
+
+ @pytest.mark.asyncio
+ async def test_discover_pages_no_pages_found(self):
+ """Test page discovery when no pages are found."""
+ with patch('meta_ads_mcp.core.ads.make_api_request') as mock_api:
+ mock_api.side_effect = [
+ {"data": []}, # No ads found
+ {"data": []}, # No client pages found
+ {"data": []} # No assigned pages found
+ ]
+
+ result = await _discover_pages_for_account("act_123456789", "test_token")
+
+ assert result["success"] is False
+ assert "No suitable pages found" in result["message"]
+
+ @pytest.mark.asyncio
+ async def test_discover_pages_with_invalid_page_ids(self):
+ """Test page discovery with invalid page IDs in tracking_specs."""
+ mock_ads_data = {
+ "data": [
+ {
+ "id": "123456789",
+ "tracking_specs": [
+ {
+ "page": ["invalid_id", "not_numeric", "123abc"]
+ }
+ ]
+ }
+ ]
+ }
+
+ with patch('meta_ads_mcp.core.ads.make_api_request') as mock_api:
+ mock_api.side_effect = [
+ mock_ads_data, # Ads with invalid page IDs
+ {"data": []}, # No client pages
+ {"data": []} # No assigned pages
+ ]
+
+ result = await _discover_pages_for_account("act_123456789", "test_token")
+
+ assert result["success"] is False
+ assert "No suitable pages found" in result["message"]
+
+ @pytest.mark.asyncio
+ async def test_discover_pages_api_error_handling(self):
+ """Test page discovery with API errors."""
+ with patch('meta_ads_mcp.core.ads.make_api_request') as mock_api:
+ mock_api.side_effect = Exception("API Error")
+
+ result = await _discover_pages_for_account("act_123456789", "test_token")
+
+ assert result["success"] is False
+ assert "Error during page discovery" in result["message"]
+
+ @pytest.mark.asyncio
+ async def test_search_pages_by_name_logic(self):
+ """Test the core search logic without authentication interference."""
+ # Test the filtering logic directly
+ mock_pages_data = {
+ "data": [
+ {"id": "111", "name": "Test Page 1"},
+ {"id": "222", "name": "Another Test Page"},
+ {"id": "333", "name": "Different Page"}
+ ]
+ }
+
+ # Test filtering with search term
+ search_term_lower = "test"
+ filtered_pages = []
+
+ for page in mock_pages_data["data"]:
+ page_name = page.get("name", "").lower()
+ if search_term_lower in page_name:
+ filtered_pages.append(page)
+
+ assert len(filtered_pages) == 2
+ assert filtered_pages[0]["name"] == "Test Page 1"
+ assert filtered_pages[1]["name"] == "Another Test Page"
+
+ @pytest.mark.asyncio
+ async def test_search_pages_by_name_no_matches(self):
+ """Test search logic with no matching results."""
+ mock_pages_data = {
+ "data": [
+ {"id": "111", "name": "Test Page 1"},
+ {"id": "222", "name": "Another Test Page"}
+ ]
+ }
+
+ # Test filtering with non-matching search term
+ search_term_lower = "nonexistent"
+ filtered_pages = []
+
+ for page in mock_pages_data["data"]:
+ page_name = page.get("name", "").lower()
+ if search_term_lower in page_name:
+ filtered_pages.append(page)
+
+ assert len(filtered_pages) == 0
+
+ @pytest.mark.asyncio
+ async def test_search_pages_by_name_core_success(self):
+ """Test the core search function with successful page discovery."""
+ mock_discovery_result = {
+ "success": True,
+ "page_id": "123456789",
+ "page_name": "Test Page",
+ "source": "tracking_specs"
+ }
+
+ with patch('meta_ads_mcp.core.ads._discover_pages_for_account') as mock_discover:
+ mock_discover.return_value = mock_discovery_result
+
+ result = await _search_pages_by_name_core("test_token", "act_123456789", "test")
+ result_data = json.loads(result)
+
+ assert len(result_data["data"]) == 1
+ assert result_data["data"][0]["id"] == "123456789"
+ assert result_data["data"][0]["name"] == "Test Page"
+ assert result_data["search_term"] == "test"
+ assert result_data["total_found"] == 1
+ assert result_data["total_available"] == 1
+
+ @pytest.mark.asyncio
+ async def test_search_pages_by_name_core_no_pages(self):
+ """Test the core search function when no pages are found."""
+ mock_discovery_result = {
+ "success": False,
+ "message": "No pages found"
+ }
+
+ with patch('meta_ads_mcp.core.ads._discover_pages_for_account') as mock_discover:
+ mock_discover.return_value = mock_discovery_result
+
+ result = await _search_pages_by_name_core("test_token", "act_123456789", "test")
+ result_data = json.loads(result)
+
+ assert len(result_data["data"]) == 0
+ assert "No pages found" in result_data["message"]
+
+ @pytest.mark.asyncio
+ async def test_search_pages_by_name_core_no_search_term(self):
+ """Test the core search function without search term."""
+ mock_discovery_result = {
+ "success": True,
+ "page_id": "123456789",
+ "page_name": "Test Page",
+ "source": "tracking_specs"
+ }
+
+ with patch('meta_ads_mcp.core.ads._discover_pages_for_account') as mock_discover:
+ mock_discover.return_value = mock_discovery_result
+
+ result = await _search_pages_by_name_core("test_token", "act_123456789")
+ result_data = json.loads(result)
+
+ assert len(result_data["data"]) == 1
+ assert result_data["total_available"] == 1
+ assert "note" in result_data
+
+ @pytest.mark.asyncio
+ async def test_search_pages_by_name_core_exception_handling(self):
+ """Test the core search function with exception handling."""
+ with patch('meta_ads_mcp.core.ads._discover_pages_for_account') as mock_discover:
+ mock_discover.side_effect = Exception("Test exception")
+
+ result = await _search_pages_by_name_core("test_token", "act_123456789", "test")
+ result_data = json.loads(result)
+
+ assert "error" in result_data
+ assert "Failed to search pages by name" in result_data["error"]
+
+ @pytest.mark.asyncio
+ async def test_discover_pages_with_multiple_page_ids(self):
+ """Test page discovery with multiple page IDs in tracking_specs."""
+ mock_ads_data = {
+ "data": [
+ {
+ "id": "123456789",
+ "tracking_specs": [
+ {
+ "page": ["111222333", "444555666", "777888999"]
+ }
+ ]
+ }
+ ]
+ }
+
+ mock_page_data = {
+ "id": "111222333",
+ "name": "First Page",
+ "username": "firstpage"
+ }
+
+ with patch('meta_ads_mcp.core.ads.make_api_request') as mock_api:
+ mock_api.side_effect = [
+ mock_ads_data, # First call for ads
+ mock_page_data # Second call for page details
+ ]
+
+ result = await _discover_pages_for_account("act_123456789", "test_token")
+
+ assert result["success"] is True
+ # Should get the first page ID from the set
+ assert result["page_id"] in ["111222333", "444555666", "777888999"]
+ assert result["page_name"] == "First Page"
+
+ @pytest.mark.asyncio
+ async def test_discover_pages_with_mixed_valid_invalid_ids(self):
+ """Test page discovery with mixed valid and invalid page IDs."""
+ mock_ads_data = {
+ "data": [
+ {
+ "id": "123456789",
+ "tracking_specs": [
+ {
+ "page": ["invalid", "123456789", "not_numeric", "987654321"]
+ }
+ ]
+ }
+ ]
+ }
+
+ mock_page_data = {
+ "id": "123456789",
+ "name": "Valid Page",
+ "username": "validpage"
+ }
+
+ with patch('meta_ads_mcp.core.ads.make_api_request') as mock_api:
+ mock_api.side_effect = [
+ mock_ads_data, # First call for ads
+ mock_page_data # Second call for page details
+ ]
+
+ result = await _discover_pages_for_account("act_123456789", "test_token")
+
+ assert result["success"] is True
+ # Should get one of the valid numeric IDs
+ assert result["page_id"] in ["123456789", "987654321"]
+ assert result["page_name"] == "Valid Page"
+
+ @pytest.mark.asyncio
+ async def test_search_pages_by_name_case_insensitive(self):
+ """Test search function with case insensitive matching."""
+ mock_discovery_result = {
+ "success": True,
+ "page_id": "123456789",
+ "page_name": "Test Page",
+ "source": "tracking_specs"
+ }
+
+ with patch('meta_ads_mcp.core.ads._discover_pages_for_account') as mock_discover:
+ mock_discover.return_value = mock_discovery_result
+
+ # Test with uppercase search term
+ result = await _search_pages_by_name_core("test_token", "act_123456789", "TEST")
+ result_data = json.loads(result)
+
+ assert len(result_data["data"]) == 1
+ assert result_data["total_found"] == 1
+
+ # Test with lowercase search term
+ result = await _search_pages_by_name_core("test_token", "act_123456789", "test")
+ result_data = json.loads(result)
+
+ assert len(result_data["data"]) == 1
+ assert result_data["total_found"] == 1
+
+
+if __name__ == "__main__":
+ pytest.main([__file__])
\ No newline at end of file
diff --git a/tests/test_page_discovery_integration.py b/tests/test_page_discovery_integration.py
new file mode 100644
index 0000000..db33d8d
--- /dev/null
+++ b/tests/test_page_discovery_integration.py
@@ -0,0 +1,245 @@
+"""
+Integration tests for page discovery functionality.
+Tests the complete workflow from page discovery to ad creative creation.
+"""
+
+import pytest
+import json
+from unittest.mock import AsyncMock, patch
+from meta_ads_mcp.core.ads import create_ad_creative, search_pages_by_name, get_account_pages
+
+
+class TestPageDiscoveryIntegration:
+ """Integration tests for page discovery functionality."""
+
+ @pytest.mark.asyncio
+ async def test_end_to_end_page_discovery_in_create_ad_creative(self):
+ """Test that create_ad_creative automatically discovers pages when no page_id is provided."""
+ # Mock the page discovery to return a successful result
+ mock_discovery_result = {
+ "success": True,
+ "page_id": "123456789",
+ "page_name": "Test Page",
+ "source": "tracking_specs"
+ }
+
+ # Mock the API request for creating the creative (will fail due to invalid image, but that's expected)
+ mock_creative_response = {
+ "error": {
+ "message": "Invalid parameter",
+ "type": "OAuthException",
+ "code": 100,
+ "error_subcode": 2446386,
+ "error_user_title": "Image Not Found",
+ "error_user_msg": "The image you selected is not available."
+ }
+ }
+
+ with patch('meta_ads_mcp.core.ads._discover_pages_for_account') as mock_discover, \
+ patch('meta_ads_mcp.core.ads.make_api_request') as mock_api, \
+ patch('meta_ads_mcp.core.api.meta_api_tool') as mock_decorator:
+
+ # Make the decorator just return the function
+ mock_decorator.side_effect = lambda func: func
+
+ mock_discover.return_value = mock_discovery_result
+ mock_api.return_value = mock_creative_response
+
+ # Call create_ad_creative without providing page_id
+ result = await create_ad_creative(
+ account_id="act_123456789",
+ name="Test Creative",
+ image_hash="test_hash_123",
+ message="Test message",
+ headline="Test Headline",
+ description="Test description"
+ )
+
+ result_data = json.loads(result)
+
+ # Verify that the function attempted to create a creative (even though it failed due to invalid image)
+ assert "error" in result_data["data"]
+ assert "Image Not Found" in result_data["data"]["error"]["error_user_title"]
+
+ # Verify that page discovery was called
+ mock_discover.assert_called_once_with("act_123456789", None)
+
+ @pytest.mark.asyncio
+ async def test_search_pages_by_name_integration(self):
+ """Test the complete search_pages_by_name function with real-like data."""
+ # Mock the page discovery to return a successful result
+ mock_discovery_result = {
+ "success": True,
+ "page_id": "123456789",
+ "page_name": "Injury Payouts",
+ "source": "tracking_specs"
+ }
+
+ with patch('meta_ads_mcp.core.ads._discover_pages_for_account') as mock_discover, \
+ patch('meta_ads_mcp.core.api.meta_api_tool') as mock_decorator:
+
+ # Make the decorator just return the function
+ mock_decorator.side_effect = lambda func: func
+
+ mock_discover.return_value = mock_discovery_result
+
+ # Test searching for pages
+ result = await search_pages_by_name(
+ account_id="act_123456789",
+ search_term="Injury"
+ )
+
+ result_data = json.loads(result)
+
+ # Verify the search results
+ assert len(result_data["data"]) == 1
+ assert result_data["data"][0]["id"] == "123456789"
+ assert result_data["data"][0]["name"] == "Injury Payouts"
+ assert result_data["search_term"] == "Injury"
+ assert result_data["total_found"] == 1
+ assert result_data["total_available"] == 1
+
+ @pytest.mark.asyncio
+ async def test_create_ad_creative_with_manual_page_id(self):
+ """Test that create_ad_creative works with manually provided page_id."""
+ # Mock the API request for creating the creative
+ mock_creative_response = {
+ "error": {
+ "message": "Invalid parameter",
+ "type": "OAuthException",
+ "code": 100,
+ "error_subcode": 2446386,
+ "error_user_title": "Image Not Found",
+ "error_user_msg": "The image you selected is not available."
+ }
+ }
+
+ with patch('meta_ads_mcp.core.ads.make_api_request') as mock_api, \
+ patch('meta_ads_mcp.core.api.meta_api_tool') as mock_decorator:
+
+ # Make the decorator just return the function
+ mock_decorator.side_effect = lambda func: func
+
+ mock_api.return_value = mock_creative_response
+
+ # Call create_ad_creative with a manual page_id
+ result = await create_ad_creative(
+ account_id="act_123456789",
+ name="Test Creative",
+ image_hash="test_hash_123",
+ page_id="123456789", # Manual page ID
+ message="Test message",
+ headline="Test Headline",
+ description="Test description"
+ )
+
+ result_data = json.loads(result)
+
+ # Verify that the function attempted to create a creative
+ assert "error" in result_data["data"]
+ assert "Image Not Found" in result_data["data"]["error"]["error_user_title"]
+
+ # Verify that make_api_request was called for creating the creative
+ mock_api.assert_called_once()
+
+ @pytest.mark.asyncio
+ async def test_create_ad_creative_no_pages_found(self):
+ """Test create_ad_creative when no pages are found."""
+ # Mock the page discovery to return no pages
+ mock_discovery_result = {
+ "success": False,
+ "message": "No suitable pages found for this account"
+ }
+
+ with patch('meta_ads_mcp.core.ads._discover_pages_for_account') as mock_discover, \
+ patch('meta_ads_mcp.core.api.meta_api_tool') as mock_decorator:
+
+ # Make the decorator just return the function
+ mock_decorator.side_effect = lambda func: func
+
+ mock_discover.return_value = mock_discovery_result
+
+ # Call create_ad_creative without providing page_id
+ result = await create_ad_creative(
+ account_id="act_123456789",
+ name="Test Creative",
+ image_hash="test_hash_123",
+ message="Test message"
+ )
+
+ result_data = json.loads(result)
+
+ # Verify that the function returned an error about no pages found
+ assert "error" in result_data["data"]
+ assert "No page ID provided and no suitable pages found" in result_data["data"]["error"]
+ assert "suggestions" in result_data["data"]["error"]
+
+ @pytest.mark.asyncio
+ async def test_search_pages_by_name_no_search_term(self):
+ """Test search_pages_by_name without a search term (should return all pages)."""
+ # Mock the page discovery to return a successful result
+ mock_discovery_result = {
+ "success": True,
+ "page_id": "123456789",
+ "page_name": "Test Page",
+ "source": "tracking_specs"
+ }
+
+ with patch('meta_ads_mcp.core.ads._discover_pages_for_account') as mock_discover, \
+ patch('meta_ads_mcp.core.api.meta_api_tool') as mock_decorator:
+
+ # Make the decorator just return the function
+ mock_decorator.side_effect = lambda func: func
+
+ mock_discover.return_value = mock_discovery_result
+
+ # Test searching without a search term
+ result = await search_pages_by_name(
+ account_id="act_123456789"
+ )
+
+ result_data = json.loads(result)
+
+ # Verify the results
+ assert len(result_data["data"]) == 1
+ assert result_data["data"][0]["id"] == "123456789"
+ assert result_data["data"][0]["name"] == "Test Page"
+ assert result_data["total_available"] == 1
+ assert "note" in result_data
+
+ @pytest.mark.asyncio
+ async def test_search_pages_by_name_no_matches(self):
+ """Test search_pages_by_name when no pages match the search term."""
+ # Mock the page discovery to return a successful result
+ mock_discovery_result = {
+ "success": True,
+ "page_id": "123456789",
+ "page_name": "Test Page",
+ "source": "tracking_specs"
+ }
+
+ with patch('meta_ads_mcp.core.ads._discover_pages_for_account') as mock_discover, \
+ patch('meta_ads_mcp.core.api.meta_api_tool') as mock_decorator:
+
+ # Make the decorator just return the function
+ mock_decorator.side_effect = lambda func: func
+
+ mock_discover.return_value = mock_discovery_result
+
+ # Test searching for a term that doesn't match
+ result = await search_pages_by_name(
+ account_id="act_123456789",
+ search_term="Nonexistent"
+ )
+
+ result_data = json.loads(result)
+
+ # Verify that no pages were found
+ assert len(result_data["data"]) == 0
+ assert result_data["search_term"] == "Nonexistent"
+ assert result_data["total_found"] == 0
+ assert result_data["total_available"] == 1
+
+
+if __name__ == "__main__":
+ pytest.main([__file__])
\ No newline at end of file