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: Enhance search functionality to include page results
Yves Junqueira56b535afef27
diff --git a/README.md b/README.mdindex 2d63986..03d26d0 100644--- a/README.md+++ b/README.md@@ -89,6 +89,7 @@ For detailed step-by-step instructions, authentication setup, debugging, and tro- **Campaign Management**: Request changes to campaigns, ad sets, and ads (all changes require explicit confirmation)- **Cross-Platform Integration**: Works with Facebook, Instagram, and all Meta ad platforms- **Universal LLM Support**: Compatible with any MCP client including Claude Desktop, Cursor, Cherry Studio, and more+- **Enhanced Search**: Generic search function includes page searching when queries mention "page" or "pages"- **Simple Authentication**: Easy setup with secure OAuth authentication- **Cross-Platform Support**: Works on Windows, macOS, and Linux@@ -354,6 +355,14 @@ For local installation configuration, authentication options, and advanced techn- `limit`: Maximum number of results to return (default: 25)- Returns: Location data with key, name, type, and geographic hierarchy information+28. `mcp_meta_ads_search` (Enhanced)+ - Generic search across accounts, campaigns, ads, and pages+ - Automatically includes page searching when query mentions "page" or "pages"+ - Inputs:+ - `access_token` (optional): Meta API access token (will use cached token if not provided)+ - `query`: Search query string (e.g., "Injury Payouts pages", "active campaigns")+ - Returns: List of matching record IDs in ChatGPT-compatible format+## Privacy and SecurityMeta Ads MCP follows security best practices with secure token management and automatic authentication handling.diff --git a/meta_ads_mcp/core/openai_deep_research.py b/meta_ads_mcp/core/openai_deep_research.pyindex c0ef3c8..74c2ded 100644--- a/meta_ads_mcp/core/openai_deep_research.py+++ b/meta_ads_mcp/core/openai_deep_research.py@@ -77,6 +77,32 @@ class MetaAdsDataManager:logger.error(f"Error fetching ads for {account_id}: {e}")return []+ async def _get_pages_for_account(self, access_token: str, account_id: str) -> List[Dict[str, Any]]:+ """Get pages associated with an account"""+ try:+ # Import the page discovery function from ads module+ from .ads import _discover_pages_for_account++ # Ensure account_id has the 'act_' prefix+ if not account_id.startswith("act_"):+ account_id = f"act_{account_id}"++ page_discovery_result = await _discover_pages_for_account(account_id, access_token)++ if not page_discovery_result.get("success"):+ return []++ # Return page data in a consistent format+ return [{+ "id": page_discovery_result["page_id"],+ "name": page_discovery_result.get("page_name", "Unknown"),+ "source": page_discovery_result.get("source", "unknown"),+ "account_id": account_id+ }]+ except Exception as e:+ logger.error(f"Error fetching pages for {account_id}: {e}")+ return []+async def search_records(self, query: str, access_token: str) -> List[str]:"""Search Meta Ads data and return matching record IDs@@ -176,6 +202,34 @@ class MetaAdsDataManager:},"raw_data": ad}++ # If query specifically mentions "page" or "pages", also search pages+ if any(term in ['page', 'pages', 'facebook page'] for term in query_terms):+ for account in accounts[:5]: # Limit to first 5 accounts for performance+ pages = await self._get_pages_for_account(access_token, account['id'])+ for page in pages:+ page_text = f"{page.get('name', '')} {page.get('source', '')}".lower()++ if any(term in page_text for term in query_terms):+ page_record_id = f"page:{page['id']}"+ matching_ids.append(page_record_id)++ # Cache the page data+ self._cache[page_record_id] = {+ "id": page_record_id,+ "type": "page",+ "title": f"Facebook Page: {page.get('name', 'Unnamed Page')}",+ "text": f"Facebook Page {page.get('name', 'Unnamed')} (ID: {page.get('id', 'N/A')}) - Source: {page.get('source', 'Unknown')}, Account: {account.get('name', 'Unknown')}",+ "metadata": {+ "page_id": page.get('id'),+ "page_name": page.get('name'),+ "source": page.get('source'),+ "account_id": account.get('id'),+ "account_name": account.get('name'),+ "data_type": "meta_ads_page"+ },+ "raw_data": page+ }except Exception as e:logger.error(f"Error during search operation: {e}")@@ -219,7 +273,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, and ads to find relevant records+ It searches across ad accounts, campaigns, ads, and pages to find relevant recordsbased on the provided query.Args:@@ -233,6 +287,7 @@ async def search(search(query="active campaigns")search(query="account spending")search(query="facebook ads performance")+ search(query="facebook pages")"""if not query:return json.dumps({@@ -285,6 +340,7 @@ async def fetch(fetch(id="account:act_123456789")fetch(id="campaign:23842588888640185")fetch(id="ad:23842614006130185")+ fetch(id="page:123456789")"""if not id:return json.dumps({diff --git a/tests/test_openai_mcp_deep_research.py b/tests/test_openai_mcp_deep_research.pyindex f15e1b2..a93a1d6 100644--- a/tests/test_openai_mcp_deep_research.py+++ b/tests/test_openai_mcp_deep_research.py@@ -300,6 +300,50 @@ class OpenAIMCPTester:return results+ def test_page_search_functionality(self, auth_headers: Dict[str, str] = None) -> Dict[str, Any]:+ """Test that the search function includes page searching when query mentions pages"""+ print("\n🔍 Testing page search functionality")++ # Test 1: Search with page-related query that matches an account name+ page_search_result = self.test_search_tool_call("Injury Payouts pages", auth_headers)++ if not page_search_result["success"]:+ return {+ "success": False,+ "error": f"Page search failed: {page_search_result.get('error', 'Unknown error')}"+ }++ # Check if page records are included in results+ page_ids = [id for id in page_search_result["ids"] if id.startswith("page:")]++ result = {+ "success": True,+ "page_search_works": len(page_ids) > 0,+ "page_ids_found": len(page_ids),+ "total_ids": len(page_search_result["ids"]),+ "page_ids": page_ids+ }++ if len(page_ids) > 0:+ print(f"✅ Page search working - found {len(page_ids)} page records")++ # Test 2: Fetch a page record+ first_page_id = page_ids[0]+ fetch_result = self.test_fetch_tool_call(first_page_id, auth_headers)++ if fetch_result["success"]:+ print(f"✅ Page fetch working - retrieved page record: {first_page_id}")+ result["page_fetch_works"] = True+ result["fetched_page_data"] = fetch_result.get("record", {})+ else:+ print(f"❌ Page fetch failed: {fetch_result.get('error', 'Unknown error')}")+ result["page_fetch_works"] = False+ else:+ print("⚠️ No page records found in search results")+ result["page_fetch_works"] = False++ return result+def run_openai_compliance_test_suite(self) -> bool:"""Run complete OpenAI MCP compliance test suite"""print("🚀 OpenAI MCP Deep Research Compliance Test Suite")@@ -335,6 +379,12 @@ class OpenAIMCPTester:print("-" * 40)results = self.test_openai_specification_compliance(scenario["headers"])++ # Add page search test+ page_results = self.test_page_search_functionality(scenario["headers"])+ results["page_search_functionality"] = page_results.get("page_search_works", False)+ results["page_fetch_functionality"] = page_results.get("page_fetch_works", False)+all_results[scenario["name"]] = results# Summary@@ -360,9 +410,10 @@ class OpenAIMCPTester:if overall_success:print("\n🎉 Server is fully compatible with OpenAI's MCP specification!")print(" • ChatGPT Deep Research: Ready")- print(" • Search tool: Compliant")+ print(" • Search tool: Compliant (includes page search)")print(" • Fetch tool: Compliant")print(" • Workflow: Complete")+ print(" • Page Search: Enhanced")else:print("\n⚠️ Server needs updates for OpenAI MCP compliance")print(" See failed tests above for required changes")