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.

feat: Add OpenAI MCP Deep Research integration

Yves Junqueira497c46ffbd8a
diff --git a/meta_ads_mcp/core/__init__.py b/meta_ads_mcp/core/__init__.py
index 871bd5f..fe65b69 100644
--- a/meta_ads_mcp/core/__init__.py
+++ b/meta_ads_mcp/core/__init__.py
@@ -13,6 +13,7 @@ from .ads_library import search_ads_archive
from .budget_schedules import create_budget_schedule
from . import reports # Import module to register conditional tools
from . import duplication # Import module to register conditional duplication tools
+from .openai_deep_research import search, fetch # OpenAI MCP Deep Research tools
__all__ = [
'mcp_server',
@@ -36,4 +37,6 @@ __all__ = [
'main',
'search_ads_archive',
'create_budget_schedule',
+ 'search', # OpenAI MCP Deep Research search tool
+ 'fetch', # OpenAI MCP Deep Research fetch tool
]
\ No newline at end of file
diff --git a/meta_ads_mcp/core/openai_deep_research.py b/meta_ads_mcp/core/openai_deep_research.py
new file mode 100644
index 0000000..c0ef3c8
--- /dev/null
+++ b/meta_ads_mcp/core/openai_deep_research.py
@@ -0,0 +1,316 @@
+"""OpenAI MCP Deep Research tools for Meta Ads API.
+
+This module implements the required 'search' and 'fetch' tools for OpenAI's
+ChatGPT Deep Research feature, providing access to Meta Ads data in the format
+expected by ChatGPT.
+
+The tools expose Meta Ads data (accounts, campaigns, ads, etc.) as searchable
+and fetchable records for ChatGPT Deep Research analysis.
+"""
+
+import json
+import re
+from typing import List, Dict, Any, Optional
+from .api import meta_api_tool, make_api_request
+from .server import mcp_server
+from .utils import logger
+
+
+class MetaAdsDataManager:
+ """Manages Meta Ads data for OpenAI MCP search and fetch operations"""
+
+ def __init__(self):
+ self._cache = {}
+ logger.debug("MetaAdsDataManager initialized")
+
+ async def _get_ad_accounts(self, access_token: str, limit: int = 25) -> List[Dict[str, Any]]:
+ """Get ad accounts data"""
+ try:
+ endpoint = "me/adaccounts"
+ params = {
+ "fields": "id,name,account_id,account_status,amount_spent,balance,currency,business_city,business_country_code",
+ "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 ad accounts: {e}")
+ return []
+
+ async def _get_campaigns(self, access_token: str, account_id: str, limit: int = 25) -> List[Dict[str, Any]]:
+ """Get campaigns data for an account"""
+ try:
+ endpoint = f"{account_id}/campaigns"
+ params = {
+ "fields": "id,name,status,objective,daily_budget,lifetime_budget,start_time,stop_time,created_time,updated_time",
+ "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 campaigns for {account_id}: {e}")
+ return []
+
+ async def _get_ads(self, access_token: str, account_id: str, limit: int = 25) -> List[Dict[str, Any]]:
+ """Get ads data for an account"""
+ try:
+ endpoint = f"{account_id}/ads"
+ params = {
+ "fields": "id,name,status,creative,targeting,bid_amount,created_time,updated_time",
+ "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 ads 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
+
+ Args:
+ query: Search query string
+ access_token: Meta API access token
+
+ Returns:
+ List of record IDs that match the query
+ """
+ logger.info(f"Searching Meta Ads data with query: {query}")
+
+ # Normalize query for matching
+ query_lower = query.lower()
+ query_terms = re.findall(r'\w+', query_lower)
+
+ matching_ids = []
+
+ try:
+ # Search ad accounts
+ accounts = await self._get_ad_accounts(access_token, limit=25)
+ for account in accounts:
+ account_text = f"{account.get('name', '')} {account.get('id', '')} {account.get('account_status', '')} {account.get('business_city', '')} {account.get('business_country_code', '')}".lower()
+
+ if any(term in account_text for term in query_terms):
+ record_id = f"account:{account['id']}"
+ matching_ids.append(record_id)
+
+ # Cache the account data
+ self._cache[record_id] = {
+ "id": record_id,
+ "type": "account",
+ "title": f"Ad Account: {account.get('name', 'Unnamed Account')}",
+ "text": f"Meta Ads Account {account.get('name', 'Unnamed')} (ID: {account.get('id', 'N/A')}) - Status: {account.get('account_status', 'Unknown')}, Currency: {account.get('currency', 'Unknown')}, Spent: ${account.get('amount_spent', 0)}, Balance: ${account.get('balance', 0)}",
+ "metadata": {
+ "account_id": account.get('id'),
+ "account_name": account.get('name'),
+ "status": account.get('account_status'),
+ "currency": account.get('currency'),
+ "business_location": f"{account.get('business_city', '')}, {account.get('business_country_code', '')}".strip(', '),
+ "data_type": "meta_ads_account"
+ },
+ "raw_data": account
+ }
+
+ # Also search campaigns for this account if it matches
+ campaigns = await self._get_campaigns(access_token, account['id'], limit=10)
+ for campaign in campaigns:
+ campaign_text = f"{campaign.get('name', '')} {campaign.get('objective', '')} {campaign.get('status', '')}".lower()
+
+ if any(term in campaign_text for term in query_terms):
+ campaign_record_id = f"campaign:{campaign['id']}"
+ matching_ids.append(campaign_record_id)
+
+ # Cache the campaign data
+ self._cache[campaign_record_id] = {
+ "id": campaign_record_id,
+ "type": "campaign",
+ "title": f"Campaign: {campaign.get('name', 'Unnamed Campaign')}",
+ "text": f"Meta Ads Campaign {campaign.get('name', 'Unnamed')} (ID: {campaign.get('id', 'N/A')}) - Objective: {campaign.get('objective', 'Unknown')}, Status: {campaign.get('status', 'Unknown')}, Daily Budget: ${campaign.get('daily_budget', 'Not set')}, Account: {account.get('name', 'Unknown')}",
+ "metadata": {
+ "campaign_id": campaign.get('id'),
+ "campaign_name": campaign.get('name'),
+ "objective": campaign.get('objective'),
+ "status": campaign.get('status'),
+ "account_id": account.get('id'),
+ "account_name": account.get('name'),
+ "data_type": "meta_ads_campaign"
+ },
+ "raw_data": campaign
+ }
+
+ # If query specifically mentions "ads" or "ad", also search individual ads
+ if any(term in ['ad', 'ads', 'advertisement', 'creative'] for term in query_terms):
+ for account in accounts[:3]: # Limit to first 3 accounts for performance
+ ads = await self._get_ads(access_token, account['id'], limit=10)
+ for ad in ads:
+ ad_text = f"{ad.get('name', '')} {ad.get('status', '')}".lower()
+
+ if any(term in ad_text for term in query_terms):
+ ad_record_id = f"ad:{ad['id']}"
+ matching_ids.append(ad_record_id)
+
+ # Cache the ad data
+ self._cache[ad_record_id] = {
+ "id": ad_record_id,
+ "type": "ad",
+ "title": f"Ad: {ad.get('name', 'Unnamed Ad')}",
+ "text": f"Meta Ad {ad.get('name', 'Unnamed')} (ID: {ad.get('id', 'N/A')}) - Status: {ad.get('status', 'Unknown')}, Bid Amount: ${ad.get('bid_amount', 'Not set')}, Account: {account.get('name', 'Unknown')}",
+ "metadata": {
+ "ad_id": ad.get('id'),
+ "ad_name": ad.get('name'),
+ "status": ad.get('status'),
+ "account_id": account.get('id'),
+ "account_name": account.get('name'),
+ "data_type": "meta_ads_ad"
+ },
+ "raw_data": ad
+ }
+
+ except Exception as e:
+ logger.error(f"Error during search operation: {e}")
+ # Return empty list on error, but don't raise exception
+ return []
+
+ logger.info(f"Search completed. Found {len(matching_ids)} matching records")
+ return matching_ids[:50] # Limit to 50 results for performance
+
+ def fetch_record(self, record_id: str) -> Optional[Dict[str, Any]]:
+ """Fetch a cached record by ID
+
+ Args:
+ record_id: The record ID to fetch
+
+ Returns:
+ Record data or None if not found
+ """
+ logger.info(f"Fetching record: {record_id}")
+
+ record = self._cache.get(record_id)
+ if record:
+ logger.debug(f"Record found in cache: {record['type']}")
+ return record
+ else:
+ logger.warning(f"Record not found in cache: {record_id}")
+ return None
+
+
+# Global data manager instance
+_data_manager = MetaAdsDataManager()
+
+
+@mcp_server.tool()
+@meta_api_tool
+async def search(
+ access_token: str = None,
+ query: str = None
+) -> str:
+ """
+ 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
+ based on the provided query.
+
+ Args:
+ access_token: Meta API access token (optional - will use cached token if not provided)
+ query: Search query string to find relevant Meta Ads records
+
+ Returns:
+ JSON response with list of matching record IDs
+
+ Example Usage:
+ search(query="active campaigns")
+ search(query="account spending")
+ search(query="facebook ads performance")
+ """
+ if not query:
+ return json.dumps({
+ "error": "query parameter is required",
+ "ids": []
+ }, indent=2)
+
+ try:
+ # Use the data manager to search records
+ matching_ids = await _data_manager.search_records(query, access_token)
+
+ response = {
+ "ids": matching_ids,
+ "query": query,
+ "total_results": len(matching_ids)
+ }
+
+ logger.info(f"Search successful. Query: '{query}', Results: {len(matching_ids)}")
+ return json.dumps(response, indent=2)
+
+ except Exception as e:
+ error_msg = str(e)
+ logger.error(f"Error in search tool: {error_msg}")
+
+ return json.dumps({
+ "error": "Failed to search Meta Ads data",
+ "details": error_msg,
+ "ids": [],
+ "query": query
+ }, indent=2)
+
+
+@mcp_server.tool()
+async def fetch(
+ id: str = None
+) -> str:
+ """
+ Fetch complete record data by ID.
+
+ This tool is required for OpenAI ChatGPT Deep Research integration.
+ It retrieves the full data for a specific record identified by its ID.
+
+ Args:
+ id: The record ID to fetch (format: "type:id", e.g., "account:act_123456")
+
+ Returns:
+ JSON response with complete record data including id, title, text, and metadata
+
+ Example Usage:
+ fetch(id="account:act_123456789")
+ fetch(id="campaign:23842588888640185")
+ fetch(id="ad:23842614006130185")
+ """
+ if not id:
+ return json.dumps({
+ "error": "id parameter is required"
+ }, indent=2)
+
+ try:
+ # Use the data manager to fetch the record
+ record = _data_manager.fetch_record(id)
+
+ if record:
+ logger.info(f"Record fetched successfully: {id}")
+ return json.dumps(record, indent=2)
+ else:
+ logger.warning(f"Record not found: {id}")
+ return json.dumps({
+ "error": f"Record not found: {id}",
+ "id": id
+ }, indent=2)
+
+ except Exception as e:
+ error_msg = str(e)
+ logger.error(f"Error in fetch tool: {error_msg}")
+
+ return json.dumps({
+ "error": "Failed to fetch record",
+ "details": error_msg,
+ "id": id
+ }, indent=2)
\ No newline at end of file
diff --git a/meta_ads_mcp/core/server.py b/meta_ads_mcp/core/server.py
index c55946c..e7abe62 100644
--- a/meta_ads_mcp/core/server.py
+++ b/meta_ads_mcp/core/server.py
@@ -276,6 +276,8 @@ def main():
pipeboard_api_token = os.environ.get("PIPEBOARD_API_TOKEN")
if pipeboard_api_token:
logger.info("Using Pipeboard authentication")
+ print("✅ Pipeboard authentication enabled")
+ print(f" API token: {pipeboard_api_token[:8]}...{pipeboard_api_token[-4:]}")
# Check for existing token
token = pipeboard_auth_manager.get_access_token()
if not token:
@@ -312,6 +314,9 @@ def main():
except Exception as e:
logger.error(f"Error initiating browser-based authentication: {e}")
print(f"Error: Could not start authentication: {e}")
+ else:
+ print(f"✅ Valid Pipeboard access token found")
+ print(f" Token preview: {token[:10]}...{token[-5:]}")
# Transport-specific server initialization and startup
if args.transport == "streamable-http":
@@ -336,7 +341,7 @@ def main():
# Import all tool modules to ensure they are registered
logger.info("Ensuring all tools are registered for HTTP transport")
from . import accounts, campaigns, adsets, ads, insights, authentication
- from . import ads_library, budget_schedules, reports
+ from . import ads_library, budget_schedules, reports, openai_deep_research
# ✅ NEW: Setup HTTP authentication middleware
logger.info("Setting up HTTP authentication middleware")
diff --git a/tests/test_account_search.py b/tests/test_account_search.py
new file mode 100644
index 0000000..08226ef
--- /dev/null
+++ b/tests/test_account_search.py
@@ -0,0 +1,336 @@
+#!/usr/bin/env python3
+"""
+Focused Account Search Test for Meta Ads MCP
+
+This test validates that the search tool correctly finds and returns
+account data for known test accounts.
+
+Expected test accounts:
+- act_4891437610982483 (Yves Junqueira)
+- act_701351919139047 (Injury Payouts)
+"""
+
+import requests
+import json
+import os
+import sys
+from typing import Dict, Any, List
+
+# Load environment variables from .env file
+try:
+ from dotenv import load_dotenv
+ load_dotenv()
+ print("✅ Loaded environment variables from .env file")
+except ImportError:
+ print("⚠️ python-dotenv not installed, using system environment variables only")
+
+class AccountSearchTester:
+ """Test suite focused on account search 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
+
+ # Expected test data
+ self.expected_accounts = [
+ {
+ "id": "act_4891437610982483",
+ "name": "Yves Junqueira",
+ "account_id": "4891437610982483"
+ },
+ {
+ "id": "act_701351919139047",
+ "name": "Injury Payouts",
+ "account_id": "701351919139047"
+ }
+ ]
+
+ 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 = {
+ "Content-Type": "application/json",
+ "Accept": "application/json, text/event-stream",
+ "User-Agent": "Account-Search-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=10
+ )
+
+ 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_search_accounts(self) -> Dict[str, Any]:
+ """Test searching for accounts with various queries"""
+
+ queries_to_test = [
+ "accounts",
+ "ad accounts",
+ "meta accounts",
+ "Yves",
+ "Injury Payouts"
+ ]
+
+ results = {}
+
+ for query in queries_to_test:
+ print(f"\n🔍 Testing search query: '{query}'")
+
+ result = self._make_request("tools/call", {
+ "name": "search",
+ "arguments": {"query": query}
+ })
+
+ if not result["success"]:
+ results[query] = {
+ "success": False,
+ "error": result.get("text", "Unknown error")
+ }
+ print(f"❌ Search failed: {result.get('text', 'Unknown error')}")
+ continue
+
+ # Parse the tool response
+ response_data = result["json"]["result"]
+ content = response_data.get("content", [{}])[0].get("text", "")
+
+ try:
+ parsed_content = json.loads(content)
+ ids = parsed_content.get("ids", [])
+
+ # Check for expected account IDs
+ expected_account_ids = [f"account:{acc['id']}" for acc in self.expected_accounts]
+ found_account_ids = [id for id in ids if id.startswith("account:")]
+
+ results[query] = {
+ "success": True,
+ "ids": ids,
+ "account_ids": found_account_ids,
+ "found_expected_accounts": len([id for id in expected_account_ids if id in found_account_ids]),
+ "total_expected": len(expected_account_ids),
+ "raw_content": parsed_content
+ }
+
+ print(f"✅ Found {len(found_account_ids)} account IDs: {found_account_ids}")
+ print(f"📊 Expected accounts found: {results[query]['found_expected_accounts']}/{results[query]['total_expected']}")
+ print(f"🔍 Raw response: {json.dumps(parsed_content, indent=2)}")
+
+ except json.JSONDecodeError:
+ results[query] = {
+ "success": False,
+ "error": "Search tool did not return valid JSON",
+ "raw_content": content
+ }
+ print(f"❌ Invalid JSON response: {content}")
+
+ return results
+
+ def test_fetch_account(self, account_id: str) -> Dict[str, Any]:
+ """Test fetching a specific account by ID"""
+
+ print(f"\n🔍 Testing fetch for account: {account_id}")
+
+ result = self._make_request("tools/call", {
+ "name": "fetch",
+ "arguments": {"id": account_id}
+ })
+
+ if not result["success"]:
+ return {
+ "success": False,
+ "error": result.get("text", "Unknown error")
+ }
+
+ # Parse the tool response
+ response_data = result["json"]["result"]
+ content = response_data.get("content", [{}])[0].get("text", "")
+
+ try:
+ parsed_content = json.loads(content)
+
+ # Validate required fields for OpenAI MCP compliance
+ required_fields = ["id", "title", "text"]
+ has_required_fields = all(field in parsed_content for field in required_fields)
+
+ result_data = {
+ "success": True,
+ "record": parsed_content,
+ "has_required_fields": has_required_fields,
+ "missing_fields": [field for field in required_fields if field not in parsed_content]
+ }
+
+ if has_required_fields:
+ print(f"✅ Successfully fetched account with all required fields")
+ print(f" Title: {parsed_content.get('title', 'N/A')}")
+ print(f" ID: {parsed_content.get('id', 'N/A')}")
+ else:
+ print(f"⚠️ Account fetched but missing required fields: {result_data['missing_fields']}")
+
+ return result_data
+
+ except json.JSONDecodeError:
+ return {
+ "success": False,
+ "error": "Fetch tool did not return valid JSON",
+ "raw_content": content
+ }
+
+ def run_account_search_tests(self) -> bool:
+ """Run comprehensive account search tests"""
+
+ print("🚀 Meta Ads Account Search Test Suite")
+ print("="*50)
+
+ # Check server availability
+ try:
+ response = requests.get(f"{self.base_url}/", timeout=5)
+ server_running = response.status_code in [200, 404]
+ except:
+ server_running = False
+
+ if not server_running:
+ print("❌ Server is not running at", self.base_url)
+ print(" Please start the server with:")
+ print(" python3 -m meta_ads_mcp --transport streamable-http --port 8080")
+ return False
+
+ print("✅ Server is running")
+ print("🔐 Using implicit authentication from server")
+
+ # Test 0: First try get_ad_accounts to see if we can get raw data
+ print("\n" + "="*50)
+ print("📋 PHASE 0: Testing Direct Account Access")
+ print("="*50)
+
+ account_result = self._make_request("tools/call", {
+ "name": "get_ad_accounts",
+ "arguments": {
+ "user_id": "me",
+ "parameters": json.dumps({"limit": 5})
+ }
+ })
+
+ if account_result["success"]:
+ response_data = account_result["json"]["result"]
+ content = response_data.get("content", [{}])[0].get("text", "")
+ try:
+ account_data = json.loads(content)
+ print(f"✅ get_ad_accounts returned: {json.dumps(account_data, indent=2)}")
+ except:
+ print(f"⚠️ get_ad_accounts raw response: {content}")
+ else:
+ print(f"❌ get_ad_accounts failed: {account_result.get('text', 'Unknown error')}")
+
+ # Test 1: Search for accounts
+ print("\n" + "="*50)
+ print("📋 PHASE 1: Testing Account Search")
+ print("="*50)
+
+ search_results = self.test_search_accounts()
+
+ # Find the best search result that returned accounts
+ best_search = None
+ for query, result in search_results.items():
+ if result.get("success") and result.get("account_ids"):
+ best_search = result
+ break
+
+ if not best_search:
+ print("\n❌ No search queries returned account IDs")
+ print("📊 Search Results Summary:")
+ for query, result in search_results.items():
+ if result.get("success"):
+ print(f" '{query}': {len(result.get('ids', []))} total IDs, {len(result.get('account_ids', []))} account IDs")
+ else:
+ print(f" '{query}': FAILED - {result.get('error', 'Unknown error')}")
+ return False
+
+ print(f"\n✅ Found accounts in search results")
+ account_ids = best_search["account_ids"]
+ print(f"📋 Account IDs found: {account_ids}")
+
+ # Test 2: Fetch account details
+ print("\n" + "="*50)
+ print("📋 PHASE 2: Testing Account Fetch")
+ print("="*50)
+
+ fetch_success = True
+ for account_id in account_ids[:2]: # Test first 2 accounts
+ fetch_result = self.test_fetch_account(account_id)
+ if not fetch_result["success"]:
+ print(f"❌ Failed to fetch {account_id}: {fetch_result.get('error', 'Unknown error')}")
+ fetch_success = False
+ elif not fetch_result["has_required_fields"]:
+ print(f"⚠️ {account_id} missing required fields: {fetch_result['missing_fields']}")
+ fetch_success = False
+
+ # Final assessment
+ print("\n" + "="*50)
+ print("📊 FINAL RESULTS")
+ print("="*50)
+
+ if fetch_success and account_ids:
+ print("✅ Account search and fetch workflow: SUCCESS")
+ print(f" • Found {len(account_ids)} accounts")
+ print(f" • All fetched accounts have required fields")
+ print(f" • OpenAI MCP compliance: PASSED")
+ return True
+ else:
+ print("❌ Account search and fetch workflow: FAILED")
+ if not account_ids:
+ print(" • Issue: No account IDs returned by search")
+ if not fetch_success:
+ print(" • Issue: Some accounts failed to fetch or missing required fields")
+ return False
+
+
+def main():
+ """Main test execution"""
+ tester = AccountSearchTester()
+ success = tester.run_account_search_tests()
+
+ if success:
+ print("\n🎉 All account search tests passed!")
+ else:
+ print("\n⚠️ Some account search tests failed - see details above")
+
+ sys.exit(0 if success else 1)
+
+
+if __name__ == "__main__":
+ main()
\ No newline at end of file
diff --git a/tests/test_integration_openai_mcp.py b/tests/test_integration_openai_mcp.py
new file mode 100644
index 0000000..eec41a9
--- /dev/null
+++ b/tests/test_integration_openai_mcp.py
@@ -0,0 +1,242 @@
+#!/usr/bin/env python3
+"""
+Integration Test for OpenAI MCP functionality with existing Meta Ads tools
+
+This test verifies that:
+1. Existing Meta Ads tools still work after adding OpenAI MCP tools
+2. New search and fetch tools are properly registered
+3. Both old and new tools can coexist without conflicts
+
+Usage:
+ python tests/test_integration_openai_mcp.py
+"""
+
+import sys
+import os
+import importlib
+
+# Add project root to path for imports
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+def test_module_imports():
+ """Test that all modules can be imported successfully"""
+ print("🧪 Testing module imports...")
+
+ try:
+ # Test core module import
+ import meta_ads_mcp.core as core
+ print("✅ Core module imported successfully")
+
+ # Test that mcp_server is available
+ assert hasattr(core, 'mcp_server'), "mcp_server not found in core module"
+ print("✅ mcp_server available")
+
+ # Test that existing tools are still available
+ existing_tools = [
+ 'get_ad_accounts', 'get_account_info', 'get_campaigns',
+ 'get_ads', 'get_insights', 'search_ads_archive'
+ ]
+
+ for tool in existing_tools:
+ assert hasattr(core, tool), f"Existing tool {tool} not found"
+ print(f"✅ All {len(existing_tools)} existing tools available")
+
+ # Test that new OpenAI tools are available
+ openai_tools = ['search', 'fetch']
+ for tool in openai_tools:
+ assert hasattr(core, tool), f"OpenAI tool {tool} not found"
+ print(f"✅ All {len(openai_tools)} OpenAI MCP tools available")
+
+ return True
+
+ except Exception as e:
+ print(f"❌ Module import test failed: {e}")
+ return False
+
+def test_tool_registration():
+ """Test that tools are properly registered with the MCP server"""
+ print("\n🧪 Testing tool registration...")
+
+ try:
+ # Import the server and get registered tools
+ from meta_ads_mcp.core.server import mcp_server
+
+ # Get all registered tools
+ # Note: FastMCP may not expose tools until runtime, so we'll check the module structure
+ print("✅ MCP server accessible")
+
+ # Test that OpenAI Deep Research module can be imported
+ from meta_ads_mcp.core import openai_deep_research
+ print("✅ OpenAI Deep Research module imported")
+
+ # Test that the tools are callable
+ assert callable(openai_deep_research.search), "search tool is not callable"
+ assert callable(openai_deep_research.fetch), "fetch tool is not callable"
+ print("✅ OpenAI tools are callable")
+
+ return True
+
+ except Exception as e:
+ print(f"❌ Tool registration test failed: {e}")
+ return False
+
+def test_tool_signatures():
+ """Test that tool signatures are correct"""
+ print("\n🧪 Testing tool signatures...")
+
+ try:
+ from meta_ads_mcp.core.openai_deep_research import search, fetch
+ import inspect
+
+ # Test search tool signature
+ search_sig = inspect.signature(search)
+ search_params = list(search_sig.parameters.keys())
+
+ # Should have access_token and query parameters
+ expected_search_params = ['access_token', 'query']
+ for param in expected_search_params:
+ assert param in search_params, f"search tool missing parameter: {param}"
+ print("✅ search tool has correct signature")
+
+ # Test fetch tool signature
+ fetch_sig = inspect.signature(fetch)
+ fetch_params = list(fetch_sig.parameters.keys())
+
+ # Should have id parameter
+ assert 'id' in fetch_params, "fetch tool missing 'id' parameter"
+ print("✅ fetch tool has correct signature")
+
+ return True
+
+ except Exception as e:
+ print(f"❌ Tool signature test failed: {e}")
+ return False
+
+def test_existing_functionality_preserved():
+ """Test that existing functionality is not broken"""
+ print("\n🧪 Testing existing functionality preservation...")
+
+ try:
+ # Test that we can still import and access existing tools
+ from meta_ads_mcp.core.accounts import get_ad_accounts
+ from meta_ads_mcp.core.campaigns import get_campaigns
+ from meta_ads_mcp.core.ads import get_ads
+ from meta_ads_mcp.core.insights import get_insights
+
+ # Verify they're still callable
+ assert callable(get_ad_accounts), "get_ad_accounts is not callable"
+ assert callable(get_campaigns), "get_campaigns is not callable"
+ assert callable(get_ads), "get_ads is not callable"
+ assert callable(get_insights), "get_insights is not callable"
+
+ print("✅ All existing tools remain callable")
+
+ # Test that existing tool signatures haven't changed
+ import inspect
+
+ accounts_sig = inspect.signature(get_ad_accounts)
+ accounts_params = list(accounts_sig.parameters.keys())
+ assert 'access_token' in accounts_params, "get_ad_accounts signature changed"
+
+ print("✅ Existing tool signatures preserved")
+
+ return True
+
+ except Exception as e:
+ print(f"❌ Existing functionality test failed: {e}")
+ return False
+
+def test_no_name_conflicts():
+ """Test that there are no naming conflicts between old and new tools"""
+ print("\n🧪 Testing for naming conflicts...")
+
+ try:
+ import meta_ads_mcp.core as core
+
+ # Get all attributes from the core module
+ all_attrs = dir(core)
+
+ # Check for expected tools
+ existing_tools = [
+ 'get_ad_accounts', 'get_campaigns', 'get_ads', 'get_insights',
+ 'search_ads_archive' # This is the existing search function
+ ]
+
+ new_tools = ['search', 'fetch'] # These are the new OpenAI tools
+
+ # Verify all tools exist
+ for tool in existing_tools + new_tools:
+ assert tool in all_attrs, f"Tool {tool} not found in core module"
+
+ # Verify search_ads_archive and search are different functions
+ assert core.search_ads_archive != core.search, "search and search_ads_archive should be different functions"
+
+ print("✅ No naming conflicts detected")
+ print(f" - Existing search tool: search_ads_archive (Meta Ads Library)")
+ print(f" - New search tool: search (OpenAI MCP Deep Research)")
+
+ return True
+
+ except Exception as e:
+ print(f"❌ Naming conflict test failed: {e}")
+ return False
+
+def main():
+ """Run all integration tests"""
+ print("🚀 OpenAI MCP Integration Tests")
+ print("="*50)
+
+ tests = [
+ ("Module Imports", test_module_imports),
+ ("Tool Registration", test_tool_registration),
+ ("Tool Signatures", test_tool_signatures),
+ ("Existing Functionality", test_existing_functionality_preserved),
+ ("Naming Conflicts", test_no_name_conflicts),
+ ]
+
+ results = {}
+ all_passed = True
+
+ for test_name, test_func in tests:
+ try:
+ result = test_func()
+ results[test_name] = result
+ if not result:
+ all_passed = False
+ except Exception as e:
+ print(f"❌ {test_name} test crashed: {e}")
+ results[test_name] = False
+ all_passed = False
+
+ # Summary
+ print("\n🏁 INTEGRATION TEST RESULTS")
+ print("="*30)
+
+ for test_name, result in results.items():
+ status = "✅ PASSED" if result else "❌ FAILED"
+ print(f"{test_name}: {status}")
+
+ print(f"\n📊 Overall Result: {'✅ ALL TESTS PASSED' if all_passed else '❌ SOME TESTS FAILED'}")
+
+ if all_passed:
+ print("\n🎉 Integration successful!")
+ print(" • Existing Meta Ads tools: Working")
+ print(" • New OpenAI MCP tools: Working")
+ print(" • No conflicts detected")
+ print(" • Ready for OpenAI ChatGPT Deep Research")
+ print("\n📋 Next steps:")
+ print(" 1. Start server inside uv virtual env:")
+ print(" # Basic HTTP server (default: localhost:8080)")
+ print(" python -m meta_ads_mcp --transport streamable-http")
+ print(" ")
+ print(" # Custom host and port")
+ print(" python -m meta_ads_mcp --transport streamable-http --host 0.0.0.0 --port 9000")
+ print(" 2. Run OpenAI tests: python tests/test_openai_mcp_deep_research.py")
+ else:
+ print("\n⚠️ Integration issues detected")
+ print(" Please fix failed tests before proceeding")
+
+ return 0 if all_passed else 1
+
+if __name__ == "__main__":
+ sys.exit(main())
\ No newline at end of file
diff --git a/tests/test_openai_mcp_deep_research.py b/tests/test_openai_mcp_deep_research.py
new file mode 100644
index 0000000..f15e1b2
--- /dev/null
+++ b/tests/test_openai_mcp_deep_research.py
@@ -0,0 +1,381 @@
+#!/usr/bin/env python3
+"""
+OpenAI MCP Deep Research Integration Tests
+
+This test suite validates the OpenAI MCP specification compliance:
+- search tool: Returns list of IDs based on query
+- fetch tool: Returns complete record data by ID
+- ChatGPT Deep Research compatibility
+- Integration with existing authentication
+
+Usage:
+ 1. Start the server: python -m meta_ads_mcp --transport streamable-http --port 8080
+ 2. Run tests: python -m pytest tests/test_openai_mcp_deep_research.py -v
+
+Or run directly:
+ python tests/test_openai_mcp_deep_research.py
+"""
+
+import requests
+import json
+import time
+import sys
+import os
+from typing import Dict, Any, Optional, List
+
+# Load environment variables from .env file
+try:
+ from dotenv import load_dotenv
+ load_dotenv()
+ print("✅ Loaded environment variables from .env file")
+except ImportError:
+ print("⚠️ python-dotenv not installed, using system environment variables only")
+ print(" Install with: pip install python-dotenv")
+
+# Add project root to path for imports
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+class OpenAIMCPTester:
+ """Test suite for OpenAI MCP Deep Research compatibility"""
+
+ 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": "OpenAI-MCP-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=10
+ )
+
+ 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_search_tool_exists(self, auth_headers: Dict[str, str] = None) -> Dict[str, Any]:
+ """Test that the search tool is available in tools list"""
+ result = self._make_request("tools/list", {}, auth_headers)
+
+ if not result["success"]:
+ return {"success": False, "error": "Failed to get tools list"}
+
+ tools = result["json"]["result"].get("tools", [])
+ search_tool = next((tool for tool in tools if tool["name"] == "search"), None)
+
+ return {
+ "success": search_tool is not None,
+ "tool": search_tool,
+ "all_tools": [tool["name"] for tool in tools]
+ }
+
+ def test_fetch_tool_exists(self, auth_headers: Dict[str, str] = None) -> Dict[str, Any]:
+ """Test that the fetch tool is available in tools list"""
+ result = self._make_request("tools/list", {}, auth_headers)
+
+ if not result["success"]:
+ return {"success": False, "error": "Failed to get tools list"}
+
+ tools = result["json"]["result"].get("tools", [])
+ fetch_tool = next((tool for tool in tools if tool["name"] == "fetch"), None)
+
+ return {
+ "success": fetch_tool is not None,
+ "tool": fetch_tool,
+ "all_tools": [tool["name"] for tool in tools]
+ }
+
+ def test_search_tool_call(self, query: str, auth_headers: Dict[str, str] = None) -> Dict[str, Any]:
+ """Test calling the search tool with a query"""
+ result = self._make_request("tools/call", {
+ "name": "search",
+ "arguments": {"query": query}
+ }, auth_headers)
+
+ if not result["success"]:
+ return {"success": False, "error": result.get("text", "Unknown error")}
+
+ # Parse the tool response
+ response_data = result["json"]["result"]
+ content = response_data.get("content", [{}])[0].get("text", "")
+
+ try:
+ parsed_content = json.loads(content)
+ ids = parsed_content.get("ids", [])
+
+ return {
+ "success": True,
+ "ids": ids,
+ "raw_content": content,
+ "id_count": len(ids)
+ }
+ except json.JSONDecodeError:
+ return {
+ "success": False,
+ "error": "Search tool did not return valid JSON",
+ "raw_content": content
+ }
+
+ def test_fetch_tool_call(self, record_id: str, auth_headers: Dict[str, str] = None) -> Dict[str, Any]:
+ """Test calling the fetch tool with an ID"""
+ result = self._make_request("tools/call", {
+ "name": "fetch",
+ "arguments": {"id": record_id}
+ }, auth_headers)
+
+ if not result["success"]:
+ return {"success": False, "error": result.get("text", "Unknown error")}
+
+ # Parse the tool response
+ response_data = result["json"]["result"]
+ content = response_data.get("content", [{}])[0].get("text", "")
+
+ try:
+ parsed_content = json.loads(content)
+
+ return {
+ "success": True,
+ "record": parsed_content,
+ "raw_content": content,
+ "has_required_fields": all(field in parsed_content for field in ["id", "title", "text"])
+ }
+ except json.JSONDecodeError:
+ return {
+ "success": False,
+ "error": "Fetch tool did not return valid JSON",
+ "raw_content": content
+ }
+
+ def test_search_fetch_workflow(self, auth_headers: Dict[str, str] = None) -> Dict[str, Any]:
+ """Test the complete search->fetch workflow that ChatGPT Deep Research expects"""
+
+ # Step 1: Search for something that will return account IDs
+ search_result = self.test_search_tool_call("Yves", auth_headers)
+
+ if not search_result["success"]:
+ return {
+ "success": False,
+ "step": "search",
+ "error": search_result.get("error", "Search failed")
+ }
+
+ if not search_result["ids"]:
+ return {
+ "success": False,
+ "step": "search",
+ "error": "Search returned no IDs"
+ }
+
+ # Step 2: Fetch the first ID
+ first_id = search_result["ids"][0]
+ fetch_result = self.test_fetch_tool_call(first_id, auth_headers)
+
+ if not fetch_result["success"]:
+ return {
+ "success": False,
+ "step": "fetch",
+ "error": fetch_result.get("error", "Fetch failed"),
+ "searched_id": first_id
+ }
+
+ return {
+ "success": True,
+ "search_ids": search_result["ids"],
+ "fetched_record": fetch_result["record"],
+ "workflow_complete": True
+ }
+
+ def test_openai_specification_compliance(self, auth_headers: Dict[str, str] = None) -> Dict[str, bool]:
+ """Test compliance with OpenAI's MCP specification for Deep Research"""
+ results = {}
+
+ print("\n🧪 Testing OpenAI MCP Specification Compliance")
+ print("="*55)
+
+ # Test 1: Both required tools exist
+ print("🔍 Checking required tools exist")
+ search_exists = self.test_search_tool_exists(auth_headers)
+ fetch_exists = self.test_fetch_tool_exists(auth_headers)
+
+ results["search_tool_exists"] = search_exists["success"]
+ results["fetch_tool_exists"] = fetch_exists["success"]
+
+ if not search_exists["success"]:
+ print("❌ Search tool not found")
+ print(f" Available tools: {search_exists.get('all_tools', [])}")
+ return results
+
+ if not fetch_exists["success"]:
+ print("❌ Fetch tool not found")
+ print(f" Available tools: {fetch_exists.get('all_tools', [])}")
+ return results
+
+ print("✅ Both search and fetch tools found")
+
+ # Test 2: Search tool returns proper format
+ print("\n🔍 Testing search tool format")
+ search_result = self.test_search_tool_call("Yves", auth_headers)
+ results["search_format_valid"] = search_result["success"]
+
+ if not search_result["success"]:
+ print(f"❌ Search tool failed: {search_result.get('error', 'Unknown error')}")
+ return results
+
+ print(f"✅ Search tool returns valid format with {search_result['id_count']} IDs")
+
+ # Test 3: Fetch tool returns proper format
+ if search_result["ids"]:
+ print("\n🔍 Testing fetch tool format")
+ first_id = search_result["ids"][0]
+ fetch_result = self.test_fetch_tool_call(first_id, auth_headers)
+ results["fetch_format_valid"] = fetch_result["success"]
+ results["fetch_has_required_fields"] = fetch_result.get("has_required_fields", False)
+
+ if not fetch_result["success"]:
+ print(f"❌ Fetch tool failed: {fetch_result.get('error', 'Unknown error')}")
+ return results
+
+ print("✅ Fetch tool returns valid format")
+
+ if fetch_result["has_required_fields"]:
+ print("✅ Fetch response includes required fields (id, title, text)")
+ else:
+ print("⚠️ Fetch response missing some required fields")
+ else:
+ print("⚠️ Cannot test fetch tool - no IDs returned by search")
+ results["fetch_format_valid"] = False
+ results["fetch_has_required_fields"] = False
+
+ # Test 4: Complete workflow
+ print("\n🔍 Testing complete search->fetch workflow")
+ workflow_result = self.test_search_fetch_workflow(auth_headers)
+ results["workflow_complete"] = workflow_result["success"]
+
+ if workflow_result["success"]:
+ print("✅ Complete workflow successful")
+ else:
+ print(f"❌ Workflow failed at {workflow_result.get('step', 'unknown')} step")
+ print(f" Error: {workflow_result.get('error', 'Unknown error')}")
+
+ return results
+
+ def run_openai_compliance_test_suite(self) -> bool:
+ """Run complete OpenAI MCP compliance test suite"""
+ print("🚀 OpenAI MCP Deep Research Compliance Test Suite")
+ print("="*60)
+
+ # Check server availability first
+ try:
+ response = requests.get(f"{self.base_url}/", timeout=5)
+ server_running = response.status_code in [200, 404]
+ except:
+ server_running = False
+
+ if not server_running:
+ print("❌ Server is not running at", self.base_url)
+ print(" Please start the server with:")
+ print(" python -m meta_ads_mcp --transport streamable-http --port 8080")
+ return False
+
+ print("✅ Server is running")
+
+ # Test with no authentication (server handles auth implicitly)
+ auth_scenarios = [
+ {
+ "name": "No Authentication",
+ "headers": None
+ }
+ ]
+
+ all_results = {}
+
+ for scenario in auth_scenarios:
+ print(f"\n📋 Testing with: {scenario['name']}")
+ print("-" * 40)
+
+ results = self.test_openai_specification_compliance(scenario["headers"])
+ all_results[scenario["name"]] = results
+
+ # Summary
+ print("\n🏁 OPENAI MCP COMPLIANCE TEST RESULTS")
+ print("="*40)
+
+ overall_success = True
+ for scenario_name, results in all_results.items():
+ scenario_success = all(results.values()) if results else False
+ status = "✅ COMPLIANT" if scenario_success else "❌ NON-COMPLIANT"
+ print(f"{scenario_name}: {status}")
+
+ if not scenario_success and results:
+ for test_name, test_result in results.items():
+ if not test_result:
+ print(f" ❌ {test_name}")
+
+ if not scenario_success:
+ overall_success = False
+
+ print(f"\n📊 Overall OpenAI MCP Compliance: {'✅ COMPLIANT' if overall_success else '❌ NON-COMPLIANT'}")
+
+ if overall_success:
+ print("\n🎉 Server is fully compatible with OpenAI's MCP specification!")
+ print(" • ChatGPT Deep Research: Ready")
+ print(" • Search tool: Compliant")
+ print(" • Fetch tool: Compliant")
+ print(" • Workflow: Complete")
+ else:
+ print("\n⚠️ Server needs updates for OpenAI MCP compliance")
+ print(" See failed tests above for required changes")
+
+ return overall_success
+
+
+def main():
+ """Main test execution"""
+ tester = OpenAIMCPTester()
+ success = tester.run_openai_compliance_test_suite()
+ sys.exit(0 if success else 1)
+
+
+if __name__ == "__main__":
+ main()
\ No newline at end of file
diff --git a/uv.lock b/uv.lock
index 3b015c6..5ad8826 100644
--- a/uv.lock
+++ b/uv.lock
@@ -279,7 +279,7 @@ wheels = [
[[package]]
name = "meta-ads-mcp"
-version = "0.4.0"
+version = "0.5.0"
source = { editable = "." }
dependencies = [
{ name = "httpx" },