Skip to content

Meta Ads (Facebook/Instagram) MCP server for Claude, ChatGPT, Perplexity & Cursor — the Meta node of Pipeboard’s 5-platform family (+ Google, TikTok, Snap, Reddit). Hosted remote MCP, badged Meta Business Partner, free plan — no self-hosting required.

Refactor get_account_pages function to implement multi-approach strategy for page retrieval

Yves Junqueira523cabc3c007
diff --git a/meta_ads_mcp/core/ads.py b/meta_ads_mcp/core/ads.py
index c7f2387..f5d7b84 100644
--- a/meta_ads_mcp/core/ads.py
+++ b/meta_ads_mcp/core/ads.py
@@ -1212,69 +1212,143 @@ async def get_account_pages(access_token: str = None, account_id: str = None) ->
account_id = f"act_{account_id}"
try:
- # Try all approaches that might work
+ # Collect all page IDs from multiple approaches
+ all_page_ids = set()
- # Approach 1: Get active ads and extract page IDs
- endpoint = f"{account_id}/ads"
- params = {
- "fields": "creative{object_story_spec{page_id}}",
- "limit": 100
- }
-
- ads_data = await make_api_request(endpoint, access_token, params)
-
- # Extract unique page IDs from ads
- page_ids = set()
- if "data" in ads_data:
- for ad in ads_data.get("data", []):
- if "creative" in ad and "creative" in ad and "object_story_spec" in ad["creative"] and "page_id" in ad["creative"]["object_story_spec"]:
- page_ids.add(ad["creative"]["object_story_spec"]["page_id"])
-
- # If we found page IDs, get details for each
- if page_ids:
- page_details = {"data": []}
+ # Approach 1: Get user's personal pages (broad scope)
+ try:
+ endpoint = "me/accounts"
+ params = {
+ "fields": "id,name,username,category,fan_count,link,verification_status,picture"
+ }
+ user_pages_data = await make_api_request(endpoint, access_token, params)
+ if "data" in user_pages_data:
+ for page in user_pages_data["data"]:
+ if "id" in page:
+ all_page_ids.add(page["id"])
+ except Exception:
+ pass
+
+ # Approach 2: Try business manager pages
+ try:
+ # Strip 'act_' prefix to get raw account ID for business endpoints
+ raw_account_id = account_id.replace("act_", "")
+ endpoint = f"{raw_account_id}/owned_pages"
+ params = {
+ "fields": "id,name,username,category,fan_count,link,verification_status,picture"
+ }
+ business_pages_data = await make_api_request(endpoint, access_token, params)
+ if "data" in business_pages_data:
+ for page in business_pages_data["data"]:
+ if "id" in page:
+ all_page_ids.add(page["id"])
+ except Exception:
+ pass
+
+ # Approach 3: Try ad account client pages
+ try:
+ 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:
+ for page in client_pages_data["data"]:
+ if "id" in page:
+ all_page_ids.add(page["id"])
+ except Exception:
+ pass
+
+ # Approach 4: Extract page IDs from all ad creatives (broader creative search)
+ try:
+ endpoint = f"{account_id}/adcreatives"
+ params = {
+ "fields": "id,name,object_story_spec,link_url,call_to_action,image_hash",
+ "limit": 100
+ }
+ creatives_data = await make_api_request(endpoint, access_token, params)
+ if "data" in creatives_data:
+ for creative in creatives_data["data"]:
+ if "object_story_spec" in creative and "page_id" in creative["object_story_spec"]:
+ all_page_ids.add(creative["object_story_spec"]["page_id"])
+ except Exception:
+ pass
- for page_id in page_ids:
- 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:
- page_details["data"].append(page_data)
+ # Approach 5: Get active ads and extract page IDs from creatives
+ try:
+ endpoint = f"{account_id}/ads"
+ params = {
+ "fields": "creative{object_story_spec{page_id},link_url,call_to_action}",
+ "limit": 100
+ }
+ ads_data = await make_api_request(endpoint, access_token, params)
+ if "data" in ads_data:
+ for ad in ads_data.get("data", []):
+ if "creative" in ad and "object_story_spec" in ad["creative"] and "page_id" in ad["creative"]["object_story_spec"]:
+ all_page_ids.add(ad["creative"]["object_story_spec"]["page_id"])
+ except Exception:
+ pass
+
+ # Approach 6: Try promoted_objects endpoint
+ try:
+ endpoint = f"{account_id}/promoted_objects"
+ params = {
+ "fields": "page_id,object_store_url,product_set_id,application_id"
+ }
+ promoted_objects_data = await make_api_request(endpoint, access_token, params)
+ if "data" in promoted_objects_data:
+ for obj in promoted_objects_data["data"]:
+ if "page_id" in obj:
+ all_page_ids.add(obj["page_id"])
+ except Exception:
+ pass
+
+ # Approach 7: Extract page IDs from tracking_specs in ads (most reliable)
+ try:
+ endpoint = f"{account_id}/ads"
+ params = {
+ "fields": "id,name,status,creative,tracking_specs",
+ "limit": 100
+ }
+ tracking_ads_data = await make_api_request(endpoint, access_token, params)
+ 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():
+ all_page_ids.add(str(page_id))
+ except Exception:
+ pass
- if page_details["data"]:
- return json.dumps(page_details, indent=2)
-
- # 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"]:
- return json.dumps(client_pages_data, indent=2)
-
- # Approach 3: Try promoted_objects endpoint to find page IDs
- endpoint = f"{account_id}/promoted_objects"
- params = {
- "fields": "page_id"
- }
-
- promoted_objects_data = await make_api_request(endpoint, access_token, params)
-
- if "data" in promoted_objects_data and promoted_objects_data["data"]:
- page_ids = set()
- for obj in promoted_objects_data["data"]:
- if "page_id" in obj:
- page_ids.add(obj["page_id"])
+ # Approach 8: Try campaigns and extract page info
+ try:
+ endpoint = f"{account_id}/campaigns"
+ params = {
+ "fields": "id,name,promoted_object,objective",
+ "limit": 50
+ }
+ campaigns_data = await make_api_request(endpoint, access_token, params)
+ if "data" in campaigns_data:
+ for campaign in campaigns_data["data"]:
+ if "promoted_object" in campaign and "page_id" in campaign["promoted_object"]:
+ all_page_ids.add(campaign["promoted_object"]["page_id"])
+ except Exception:
+ pass
- if page_ids:
- page_details = {"data": []}
- for page_id in page_ids:
+ # If we found any page IDs, get details for each
+ if all_page_ids:
+ page_details = {
+ "data": [],
+ "total_pages_found": len(all_page_ids)
+ }
+
+ for page_id in all_page_ids:
+ try:
page_endpoint = f"{page_id}"
page_params = {
"fields": "id,name,username,category,fan_count,link,verification_status,picture"
@@ -1283,62 +1357,15 @@ async def get_account_pages(access_token: str = None, account_id: str = None) ->
page_data = await make_api_request(page_endpoint, access_token, page_params)
if "id" in page_data:
page_details["data"].append(page_data)
-
- if page_details["data"]:
- return json.dumps(page_details, indent=2)
-
- # Approach 4: Extract page IDs from tracking_specs in ads
- # Inspired by praveen92y's implementation for robust page detection
- # This approach is often the most reliable as confirmed by community feedback
- 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 'page' key exists, add all page IDs
- if isinstance(spec, dict) and "page" in spec:
- page_list = spec["page"]
- if isinstance(page_list, list):
- for page_id in page_list:
- # Validate page ID format (should be numeric string)
- if isinstance(page_id, (str, int)) and str(page_id).isdigit():
- tracking_page_ids.add(str(page_id))
-
- if tracking_page_ids:
- page_details = {"data": [], "source": "tracking_specs", "note": "Page IDs extracted from active ads - these are the most reliable for ad creation"}
- for page_id in tracking_page_ids:
- 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:
- # Add additional context about this page ID being suitable for ads
- page_data["_meta"] = {
- "suitable_for_ads": True,
- "found_in_tracking_specs": True,
- "recommended_for_create_ad_creative": True
- }
- page_details["data"].append(page_data)
- else:
+ else:
+ page_details["data"].append({
+ "id": page_id,
+ "error": "Page details not accessible"
+ })
+ except Exception as e:
page_details["data"].append({
- "id": page_id,
- "error": "Page details not found",
- "_meta": {
- "suitable_for_ads": True,
- "found_in_tracking_specs": True,
- "note": "Page ID exists in ads but details not accessible - you can still use this ID for ad creation"
- }
+ "id": page_id,
+ "error": f"Failed to get page details: {str(e)}"
})
if page_details["data"]:
@@ -1347,18 +1374,17 @@ async def get_account_pages(access_token: str = None, account_id: str = None) ->
# If all approaches failed, return empty data with a message
return json.dumps({
"data": [],
- "message": "No pages found associated with this account using automated methods",
- "troubleshooting": {
- "suggestion_1": "If you have existing ads, run 'get_ads' and look for page IDs in the 'tracking_specs' field",
- "suggestion_2": "Use the exact page ID from existing ads' tracking_specs for creating new ad creatives",
- "suggestion_3": "Verify your page ID format - it should be a numeric string (e.g., '123456789')",
- "suggestion_4": "Check for digit transpositions or formatting errors in your page ID"
- },
- "note": "Based on community feedback, page IDs from existing ads' tracking_specs are the most reliable for ad creation"
+ "message": "No pages found associated with this account",
+ "suggestion": "Create a Facebook page and connect it to this ad account, or ensure existing pages are properly connected through Business Manager"
}, indent=2)
except Exception as e:
return json.dumps({
"error": "Failed to get account pages",
"details": str(e)
- }, indent=2)
\ No newline at end of file
+ }, indent=2)
+
+
+
+
+
diff --git a/meta_ads_mcp/core/openai_deep_research.py b/meta_ads_mcp/core/openai_deep_research.py
index 74c2ded..4555d49 100644
--- a/meta_ads_mcp/core/openai_deep_research.py
+++ b/meta_ads_mcp/core/openai_deep_research.py
@@ -103,6 +103,24 @@ class MetaAdsDataManager:
logger.error(f"Error fetching pages for {account_id}: {e}")
return []
+ async def _get_businesses(self, access_token: str, user_id: str = "me", limit: int = 25) -> List[Dict[str, Any]]:
+ """Get businesses accessible by the current user"""
+ try:
+ endpoint = f"{user_id}/businesses"
+ params = {
+ "fields": "id,name,created_time,verification_status",
+ "limit": limit
+ }
+
+ data = await make_api_request(endpoint, access_token, params)
+
+ if "data" in data:
+ return data["data"]
+ return []
+ except Exception as e:
+ logger.error(f"Error fetching businesses: {e}")
+ return []
+
async def search_records(self, query: str, access_token: str) -> List[str]:
"""Search Meta Ads data and return matching record IDs
@@ -230,6 +248,32 @@ class MetaAdsDataManager:
},
"raw_data": page
}
+
+ # If query specifically mentions "business" or "businesses", also search businesses
+ if any(term in ['business', 'businesses', 'company', 'companies'] for term in query_terms):
+ businesses = await self._get_businesses(access_token, limit=25)
+ for business in businesses:
+ business_text = f"{business.get('name', '')} {business.get('verification_status', '')}".lower()
+
+ if any(term in business_text for term in query_terms):
+ business_record_id = f"business:{business['id']}"
+ matching_ids.append(business_record_id)
+
+ # Cache the business data
+ self._cache[business_record_id] = {
+ "id": business_record_id,
+ "type": "business",
+ "title": f"Business: {business.get('name', 'Unnamed Business')}",
+ "text": f"Meta Business {business.get('name', 'Unnamed')} (ID: {business.get('id', 'N/A')}) - Created: {business.get('created_time', 'Unknown')}, Verification: {business.get('verification_status', 'Unknown')}",
+ "metadata": {
+ "business_id": business.get('id'),
+ "business_name": business.get('name'),
+ "created_time": business.get('created_time'),
+ "verification_status": business.get('verification_status'),
+ "data_type": "meta_ads_business"
+ },
+ "raw_data": business
+ }
except Exception as e:
logger.error(f"Error during search operation: {e}")
@@ -273,7 +317,7 @@ async def search(
Search through Meta Ads data and return matching record IDs.
This tool is required for OpenAI ChatGPT Deep Research integration.
- It searches across ad accounts, campaigns, ads, and pages to find relevant records
+ It searches across ad accounts, campaigns, ads, pages, and businesses to find relevant records
based on the provided query.
Args:
@@ -288,6 +332,7 @@ async def search(
search(query="account spending")
search(query="facebook ads performance")
search(query="facebook pages")
+ search(query="user businesses")
"""
if not query:
return json.dumps({
diff --git a/tests/test_get_account_pages.py b/tests/test_get_account_pages.py
new file mode 100644
index 0000000..5c0af89
--- /dev/null
+++ b/tests/test_get_account_pages.py
@@ -0,0 +1,399 @@
+"""
+Tests for the updated get_account_pages function with multi-approach strategy.
+"""
+
+import pytest
+import json
+from unittest.mock import AsyncMock, patch
+from meta_ads_mcp.core.ads import get_account_pages
+
+
+class TestGetAccountPages:
+ """Test the updated get_account_pages function with comprehensive multi-approach testing."""
+
+ @pytest.mark.asyncio
+ async def test_get_account_pages_multi_approach_success(self):
+ """Test successful page discovery using multiple approaches."""
+ # Mock data for different endpoints
+ mock_user_pages = {
+ "data": [
+ {
+ "id": "111111111",
+ "name": "Personal Page",
+ "category": "Personal Blog",
+ "fan_count": 100
+ }
+ ]
+ }
+
+ mock_client_pages = {
+ "data": [
+ {
+ "id": "222222222",
+ "name": "Client Page",
+ "category": "Business",
+ "fan_count": 500
+ }
+ ]
+ }
+
+ mock_adcreatives = {
+ "data": [
+ {
+ "id": "creative_123",
+ "object_story_spec": {"page_id": "333333333"}
+ }
+ ]
+ }
+
+ # Mock page details for discovered IDs
+ mock_page_details = {
+ "111111111": {
+ "id": "111111111",
+ "name": "Personal Page",
+ "username": "personalpage",
+ "category": "Personal Blog",
+ "fan_count": 100,
+ "link": "https://facebook.com/personalpage",
+ "verification_status": "not_verified"
+ },
+ "222222222": {
+ "id": "222222222",
+ "name": "Client Page",
+ "username": "clientpage",
+ "category": "Business",
+ "fan_count": 500,
+ "link": "https://facebook.com/clientpage",
+ "verification_status": "verified"
+ },
+ "333333333": {
+ "id": "333333333",
+ "name": "Creative Page",
+ "username": "creativepage",
+ "category": "Creative",
+ "fan_count": 1000,
+ "link": "https://facebook.com/creativepage",
+ "verification_status": "not_verified"
+ }
+ }
+
+ with patch('meta_ads_mcp.core.api.get_current_access_token', new_callable=AsyncMock) as mock_auth, \
+ patch('meta_ads_mcp.core.ads.make_api_request') as mock_api:
+
+ mock_auth.return_value = "test_access_token"
+
+ # Mock API calls in sequence for different approaches
+ def mock_api_side_effect(endpoint, access_token, params):
+ if endpoint == "me/accounts":
+ return mock_user_pages
+ elif endpoint == "3182643988557192/owned_pages":
+ return {"data": []} # No business pages
+ elif endpoint == "act_3182643988557192/client_pages":
+ return mock_client_pages
+ elif endpoint == "act_3182643988557192/adcreatives":
+ return mock_adcreatives
+ elif endpoint == "act_3182643988557192/ads":
+ return {"data": []} # No ads
+ elif endpoint == "act_3182643988557192/promoted_objects":
+ return {"data": []} # No promoted objects
+ elif endpoint == "act_3182643988557192/campaigns":
+ return {"data": []} # No campaigns
+ elif endpoint in mock_page_details:
+ return mock_page_details[endpoint]
+ else:
+ return {"data": []}
+
+ mock_api.side_effect = mock_api_side_effect
+
+ # Call the function
+ result = await get_account_pages(account_id="act_3182643988557192")
+ result_data = json.loads(result)
+
+ # Verify the structure and content
+ assert "data" in result_data
+ assert "total_pages_found" in result_data
+
+ # Should find 3 unique pages
+ assert result_data["total_pages_found"] == 3
+ assert len(result_data["data"]) == 3
+
+ # Verify that we found valid page data
+ assert all("id" in page for page in result_data["data"])
+
+ # Verify the page names are correct
+ page_names = [page.get("name") for page in result_data["data"]]
+ assert "Personal Page" in page_names
+ assert "Client Page" in page_names
+ assert "Creative Page" in page_names
+
+ # Verify each page has basic required fields
+ for page in result_data["data"]:
+ assert "id" in page
+ assert "name" in page
+
+ @pytest.mark.asyncio
+ async def test_get_account_pages_me_special_case(self):
+ """Test the special case when account_id is 'me'."""
+ mock_user_pages = {
+ "data": [
+ {
+ "id": "444444444",
+ "name": "My Personal Page",
+ "category": "Personal",
+ "fan_count": 50
+ }
+ ]
+ }
+
+ with patch('meta_ads_mcp.core.api.get_current_access_token', new_callable=AsyncMock) as mock_auth, \
+ patch('meta_ads_mcp.core.ads.make_api_request') as mock_api:
+
+ mock_auth.return_value = "test_access_token"
+ mock_api.return_value = mock_user_pages
+
+ result = await get_account_pages(account_id="me")
+ result_data = json.loads(result)
+
+ # Verify the call was made to me/accounts
+ mock_api.assert_called_once_with(
+ "me/accounts",
+ "test_access_token",
+ {"fields": "id,name,username,category,fan_count,link,verification_status,picture"}
+ )
+
+ # Verify response structure
+ assert "data" in result_data
+ assert len(result_data["data"]) == 1
+ assert result_data["data"][0]["id"] == "444444444"
+
+ @pytest.mark.asyncio
+ async def test_get_account_pages_tracking_specs_discovery(self):
+ """Test page discovery from tracking specs (most reliable method)."""
+ mock_ads_data = {
+ "data": [
+ {
+ "id": "ad_123",
+ "tracking_specs": [
+ {
+ "page": ["555555555", "666666666"]
+ }
+ ]
+ }
+ ]
+ }
+
+ mock_page_details = {
+ "id": "555555555",
+ "name": "Tracking Page",
+ "username": "trackingpage",
+ "category": "Business"
+ }
+
+ with patch('meta_ads_mcp.core.api.get_current_access_token', new_callable=AsyncMock) as mock_auth, \
+ patch('meta_ads_mcp.core.ads.make_api_request') as mock_api:
+
+ mock_auth.return_value = "test_access_token"
+
+ def mock_api_side_effect(endpoint, access_token, params):
+ if "tracking_specs" in params.get("fields", ""):
+ return mock_ads_data
+ elif endpoint == "555555555":
+ return mock_page_details
+ elif endpoint == "666666666":
+ return {"error": "Page not accessible"}
+ else:
+ return {"data": []}
+
+ mock_api.side_effect = mock_api_side_effect
+
+ result = await get_account_pages(account_id="act_123456789")
+ result_data = json.loads(result)
+
+ # Should find pages from tracking specs
+ assert result_data["total_pages_found"] == 2
+
+ # Check that one page has details and one has error
+ pages = result_data["data"]
+ assert len(pages) == 2
+
+ # One should have full details, one should have error
+ page_with_details = next((p for p in pages if "error" not in p), None)
+ page_with_error = next((p for p in pages if "error" in p), None)
+
+ assert page_with_details is not None
+ assert page_with_error is not None
+ assert page_with_details["name"] == "Tracking Page"
+ assert "not accessible" in page_with_error["error"]
+
+ @pytest.mark.asyncio
+ async def test_get_account_pages_no_pages_found(self):
+ """Test when no pages are found through any approach."""
+ with patch('meta_ads_mcp.core.api.get_current_access_token', new_callable=AsyncMock) as mock_auth, \
+ patch('meta_ads_mcp.core.ads.make_api_request') as mock_api:
+
+ mock_auth.return_value = "test_access_token"
+ mock_api.return_value = {"data": []} # All endpoints return empty
+
+ result = await get_account_pages(account_id="act_123456789")
+ result_data = json.loads(result)
+
+ # Should return the fallback message
+ assert "data" in result_data
+ assert len(result_data["data"]) == 0
+ assert "message" in result_data
+ assert "No pages found" in result_data["message"]
+ assert "suggestion" in result_data
+
+ @pytest.mark.asyncio
+ async def test_get_account_pages_error_handling(self):
+ """Test error handling when API calls fail."""
+ with patch('meta_ads_mcp.core.api.get_current_access_token', new_callable=AsyncMock) as mock_auth, \
+ patch('meta_ads_mcp.core.ads.make_api_request') as mock_api:
+
+ mock_auth.return_value = "test_access_token"
+ mock_api.side_effect = Exception("API Error")
+
+ result = await get_account_pages(account_id="act_123456789")
+ result_data = json.loads(result)
+
+ # Individual API errors are caught and logged, function returns "no pages found"
+ assert "data" in result_data
+ assert len(result_data["data"]) == 0
+ assert "message" in result_data
+ assert "No pages found" in result_data["message"]
+
+ # But debug info should show the errors
+ if "debug" in result_data:
+ debug = result_data["debug"]
+ assert "errors" in debug
+ assert len(debug["errors"]) > 0
+ # Should have multiple API errors logged
+ assert any("API Error" in error for error in debug["errors"])
+
+ @pytest.mark.asyncio
+ async def test_get_account_pages_no_account_id(self):
+ """Test error when no account ID is provided."""
+ result = await get_account_pages(account_id=None)
+ result_data = json.loads(result)
+
+ # The @meta_api_tool decorator handles authentication before function logic
+ # So it returns an authentication error instead of the simple account ID error
+ # Error responses may be wrapped in a "data" field (MCP format)
+
+ # Check for direct error format
+ if "error" in result_data or "message" in result_data:
+ if "message" in result_data and "Authentication Required" in result_data["message"]:
+ # MCP decorator returns authentication error - this is expected
+ assert True # This is the expected behavior
+ return
+ elif "error" in result_data and "No account ID provided" in result_data["error"]:
+ # Direct function call might return the account ID error
+ assert True # This is also valid
+ return
+
+ # Check for wrapped error format (MCP response format)
+ if "data" in result_data:
+ try:
+ error_data = json.loads(result_data["data"])
+ if "error" in error_data and "No account ID provided" in error_data["error"]:
+ assert True # Wrapped error format
+ return
+ except (json.JSONDecodeError, TypeError):
+ pass
+
+ # Fallback: Check if the response contains any indication of missing account ID
+ result_str = str(result_data)
+ assert "No account ID provided" in result_str or "Authentication Required" in result_str
+
+ @pytest.mark.asyncio
+ async def test_get_account_pages_account_id_validation_direct(self):
+ """Test account ID validation by directly testing the function logic."""
+ # Import the function implementation directly to bypass decorators
+ from meta_ads_mcp.core.ads import get_account_pages
+
+ # Mock the function to bypass decorator authentication
+ with patch('meta_ads_mcp.core.api.get_current_access_token', new_callable=AsyncMock) as mock_auth:
+ mock_auth.return_value = "test_token"
+
+ # Call with empty string (should be treated as None)
+ result = await get_account_pages(account_id="")
+ result_data = json.loads(result)
+
+ # Response might be wrapped in MCP format
+ if "data" in result_data and isinstance(result_data["data"], str):
+ # Parse the nested JSON response
+ inner_data = json.loads(result_data["data"])
+ assert "error" in inner_data
+ assert "No account ID provided" in inner_data["error"]
+ else:
+ # Direct response format
+ assert "error" in result_data or "message" in result_data
+ result_str = str(result_data)
+ assert "No account ID provided" in result_str or "Authentication Required" in result_str
+
+ @pytest.mark.asyncio
+ async def test_get_account_pages_multiple_sources(self):
+ """Test that pages from multiple sources are properly collected."""
+ # Mock different results for different approaches
+ mock_responses = {
+ "me/accounts": {"data": [{"id": "111111111"}]},
+ "123456789/owned_pages": {"data": []},
+ "act_123456789/client_pages": {"data": [{"id": "222222222"}]},
+ "act_123456789/adcreatives": {"data": []},
+ "act_123456789/ads": {"data": []},
+ "act_123456789/promoted_objects": {"data": []},
+ "act_123456789/campaigns": {"data": []},
+ "111111111": {"id": "111111111", "name": "Page 1"},
+ "222222222": {"id": "222222222", "name": "Page 2"}
+ }
+
+ with patch('meta_ads_mcp.core.api.get_current_access_token', new_callable=AsyncMock) as mock_auth, \
+ patch('meta_ads_mcp.core.ads.make_api_request') as mock_api:
+
+ mock_auth.return_value = "test_access_token"
+
+ def mock_api_side_effect(endpoint, access_token, params):
+ return mock_responses.get(endpoint, {"data": []})
+
+ mock_api.side_effect = mock_api_side_effect
+
+ result = await get_account_pages(account_id="act_123456789")
+ result_data = json.loads(result)
+
+ # Verify basic response structure
+ assert "data" in result_data
+ assert "total_pages_found" in result_data
+ assert result_data["total_pages_found"] == 2
+ assert len(result_data["data"]) == 2
+
+ # Verify pages have correct names
+ page_names = [page.get("name") for page in result_data["data"]]
+ assert "Page 1" in page_names
+ assert "Page 2" in page_names
+
+ @pytest.mark.asyncio
+ async def test_get_account_pages_act_prefix_handling(self):
+ """Test that account IDs without 'act_' prefix are handled correctly."""
+ with patch('meta_ads_mcp.core.api.get_current_access_token', new_callable=AsyncMock) as mock_auth, \
+ patch('meta_ads_mcp.core.ads.make_api_request') as mock_api:
+
+ mock_auth.return_value = "test_access_token"
+ mock_api.return_value = {"data": []}
+
+ # Test with account ID without 'act_' prefix
+ result = await get_account_pages(account_id="123456789")
+
+ # Check that API calls were made with 'act_' prefix added
+ calls = mock_api.call_args_list
+
+ # Should find calls with 'act_123456789' in the endpoint
+ act_calls = [call for call in calls if 'act_123456789' in str(call)]
+ assert len(act_calls) > 0, "Should have made calls with 'act_' prefix"
+
+ # Should also have made calls with raw account ID for business endpoints
+ business_calls = [call for call in calls if '123456789/owned_pages' in str(call)]
+ assert len(business_calls) > 0, "Should have made calls to business endpoints"
+
+
+if __name__ == "__main__":
+ pytest.main([__file__])
\ No newline at end of file
diff --git a/tests/test_openai.py b/tests/test_openai.py
index c0f935e..5a69437 100644
--- a/tests/test_openai.py
+++ b/tests/test_openai.py
@@ -1,23 +1,29 @@
from openai import OpenAI
import os
+import pytest
-client = OpenAI()
-# error if no token
-if not os.getenv("PIPEBOARD_API_TOKEN"):
- raise ValueError("PIPEBOARD_API_TOKEN is not set")
-resp = client.responses.create(
- model="gpt-4.1",
- tools=[{
- "type": "mcp",
- "server_label": "meta-ads",
- "server_url": "https://mcp.pipeboard.co/meta-ads-mcp",
- "headers": {
- "Authorization": f"Bearer {os.getenv('PIPEBOARD_API_TOKEN')}"
- },
- "require_approval": "never",
- }],
- input="What are my meta ad accounts? Do not pass access_token since auth is already done.",
+ not os.getenv("PIPEBOARD_API_TOKEN"),
+ reason="PIPEBOARD_API_TOKEN not set - skipping OpenAI integration test"
)
+def test_openai_mcp_integration():
+ """Test OpenAI integration with Meta Ads MCP via Pipeboard."""
+ client = OpenAI()
-print(resp.output_text)
+ resp = client.responses.create(
+ model="gpt-4.1",
+ tools=[{
+ "type": "mcp",
+ "server_label": "meta-ads",
+ "server_url": "https://mcp.pipeboard.co/meta-ads-mcp",
+ "headers": {
+ "Authorization": f"Bearer {os.getenv('PIPEBOARD_API_TOKEN')}"
+ },
+ "require_approval": "never",
+ }],
+ input="What are my meta ad accounts? Do not pass access_token since auth is already done.",
+ )
+
+ assert resp.output_text is not None
+ print(resp.output_text)