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
fix(security): remove deep-research search/fetch tools (GHSA-j7p8-g5m6-3wv5) (#162)
Yves Junqueira96eaf2d8a0e6
diff --git a/README.md b/README.mdindex 9f5abd3..4e65c1f 100644--- a/README.md+++ b/README.md@@ -502,14 +502,6 @@ For advanced users who need to self-host, the package can be installed from sour- `limit`: Maximum number of results to return (default: 25)- Returns: Location data with key, name, type, and geographic hierarchy information-29. `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-## LicensingMeta Ads MCP is licensed under the [Business Source License 1.1](LICENSE), which means:diff --git a/SECURITY.md b/SECURITY.mdindex 7c56b1b..a0f27a0 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -180,3 +180,44 @@ same-origin page — the escalation target for the XSS above.- If you completed an OAuth login on a machine where an untrusted page may havebeen open, reconnect the Meta account so a fresh token is issued.- Credited to zx — GitHub [@manus-pi](https://github.com/manus-pi).++### GHSA-j7p8-g5m6-3wv5 — `search`/`fetch` deep-research tools returned one caller's cached records to another++- **Severity:** High (CVSS 3.1 7.5 — `AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N`)+- **Affected versions:** `>= 0.6.0, <= 1.0.121` when run with+ `--transport streamable-http` and serving more than one caller from one+ process.+- **Fixed in:** `1.0.122`+- **Affected configurations:** Multi-caller deployments only. The default stdio+ transport, and any deployment where a process serves a single caller, has no+ cross-caller boundary to cross. The hosted MCP at `*.mcp.pipeboard.co`+ intercepts `search` and answers it with its own implementation, so the Python+ cache was never populated there and `fetch` had nothing to return — measured+ over production traffic, every hosted `fetch` call returned "Record not found"+ or a schema-validation error.++**What went wrong.** `openai_deep_research.py` cached Meta Ads records in a+module-level `MetaAdsDataManager` singleton, keyed only by `"<type>:<id>"` with+no caller, session or tenant component. `search` populated that cache under the+calling user's credential; `fetch` read it back with no credential resolution+and no ownership check, so any caller who knew (or guessed) a record id could+read another caller's cached ad-account, campaign, ad, page or business records+— including account name, currency, total spend, balance and the raw Graph+objects. `fetch` never called the Graph API, so nothing downstream validated+the reader's token either; the HTTP auth gate gets a request past on any+non-empty bearer token, which is enough for every other tool because Graph+rejects a bad token, but not for a tool that answers from local state.++**Fix.** The `search` and `fetch` tools and the module that backed them were+removed outright. They had no working use left to preserve, so scoping the+cache per caller would have kept the machinery without the benefit.++**Action for operators.**+- Upgrade to `1.0.122` or later.+- If you ran an earlier version as a shared multi-caller service, treat the+ record types listed above as potentially disclosed to other callers of that+ process.+- Clients that relied on the deep-research `search`/`fetch` pair should use the+ typed tools instead: `get_ad_accounts`, `get_campaigns`,+ `get_campaign_details`, `get_adsets`, `get_ads`, `get_ad_details`.+- Credited to [@BarakSrour](https://github.com/BarakSrour).diff --git a/meta_ads_mcp/__init__.py b/meta_ads_mcp/__init__.pyindex 14f6f7c..92834f1 100644--- a/meta_ads_mcp/__init__.py+++ b/meta_ads_mcp/__init__.py@@ -6,7 +6,7 @@ This package provides a Meta Ads MCP integrationfrom meta_ads_mcp.core.server import main-__version__ = "1.0.121"+__version__ = "1.0.122"__all__ = ['get_ad_accounts',diff --git a/meta_ads_mcp/core/__init__.py b/meta_ads_mcp/core/__init__.pyindex 2664c27..82307bb 100644--- a/meta_ads_mcp/core/__init__.py+++ b/meta_ads_mcp/core/__init__.py@@ -14,7 +14,6 @@ from .budget_schedules import create_budget_schedulefrom .targeting import search_interests, get_interest_suggestions, estimate_audience_size, search_behaviors, search_demographics, search_geo_locationsfrom . import reports # Import module to register conditional toolsfrom . import duplication # Import module to register conditional duplication tools-from .openai_deep_research import search, fetch # OpenAI MCP Deep Research tools__all__ = ['mcp_server',@@ -44,6 +43,4 @@ __all__ = ['search_behaviors','search_demographics','search_geo_locations',- 'search', # OpenAI MCP Deep Research search tool- 'fetch', # OpenAI MCP Deep Research fetch tool]\ No newline at end of filediff --git a/meta_ads_mcp/core/openai_deep_research.py b/meta_ads_mcp/core/openai_deep_research.pydeleted file mode 100644index 91db412..0000000--- a/meta_ads_mcp/core/openai_deep_research.py+++ /dev/null@@ -1,418 +0,0 @@-"""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, ensure_act_prefix-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 = 200) -> 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 _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-- account_id = ensure_act_prefix(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 _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-- 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=200)- 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- }-- # 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- }-- # 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}")- # 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(- query: str,- access_token: Optional[str] = None-) -> str:- """- Search through Meta Ads data and return matching record IDs.- It searches across ad accounts, campaigns, ads, pages, and businesses to find relevant records- based on the provided query.-- Args:- query: Search query string to find relevant Meta Ads records- access_token: Meta API access token (optional - will use cached token if not provided)-- Returns:- JSON response with list of matching record IDs-- Example Usage:- search(query="active campaigns")- search(query="account spending")- search(query="facebook ads performance")- search(query="facebook pages")- search(query="user businesses")- """- 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-) -> str:- """- Fetch a record previously returned by the 'search' tool in the same session.-- IMPORTANT LIMITATIONS:- - This tool ONLY returns records that were cached by a prior 'search' call.- It does NOT make direct API calls to Meta. If the record was not found by- 'search' first, this tool will return "Record not found".- - Do NOT use this tool to look up campaigns, adsets, or ads by ID directly.-- For direct lookups by ID, use these tools instead:- - get_campaign_details(campaign_id=...) - for campaigns- - get_adset_details(adset_id=...) - for ad sets- - get_ads(account_id=..., campaign_id=...) - for ads- - get_adsets(account_id=..., campaign_id=...) - for ad sets in a campaign-- Args:- id: The record ID to fetch (format: "type:id", e.g., "account:act_123456").- Must have been returned by a previous 'search' call.-- Returns:- JSON response with record data, or "Record not found" if the record- was not previously cached by 'search'.- """- 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 filediff --git a/meta_ads_mcp/core/server.py b/meta_ads_mcp/core/server.pyindex 2229b5b..3e4b772 100644--- a/meta_ads_mcp/core/server.py+++ b/meta_ads_mcp/core/server.py@@ -324,7 +324,7 @@ def main():# Import all tool modules to ensure they are registeredlogger.info("Ensuring all tools are registered for HTTP transport")from . import accounts, campaigns, adsets, ads, insights, authentication- from . import ads_library, budget_schedules, reports, openai_deep_research+ from . import ads_library, budget_schedules, reports# ✅ NEW: Setup HTTP authentication middlewarelogger.info("Setting up HTTP authentication middleware")diff --git a/pyproject.toml b/pyproject.tomlindex db9cca9..3237250 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -4,7 +4,7 @@ build-backend = "hatchling.build"[project]name = "meta-ads-mcp"-version = "1.0.121"+version = "1.0.122"description = "Model Context Protocol (MCP) server for Meta Ads - Use Remote MCP at pipeboard.co for easiest setup"readme = "README.md"requires-python = ">=3.10"diff --git a/server.json b/server.jsonindex 89edf8d..0eb13f5 100644--- a/server.json+++ b/server.json@@ -2,7 +2,7 @@"$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json","name": "co.pipeboard/meta-ads-mcp","description": "Facebook / Meta Ads automation with AI: analyze performance, test creatives, optimize spend.",- "version": "1.0.121",+ "version": "1.0.122","remotes": [{"type": "streamable-http",diff --git a/tests/test_account_search.py b/tests/test_account_search.pydeleted file mode 100644index 08226ef..0000000--- a/tests/test_account_search.py+++ /dev/null@@ -1,336 +0,0 @@-#!/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 filediff --git a/tests/test_deep_research_tools_removed.py b/tests/test_deep_research_tools_removed.pynew file mode 100644index 0000000..1ea2800--- /dev/null+++ b/tests/test_deep_research_tools_removed.py@@ -0,0 +1,54 @@+"""Regression tests for the removal of the OpenAI Deep Research `search`/`fetch` tools.++The `openai_deep_research` module cached Meta Ads records in a module-level+singleton keyed only by `"<type>:<id>"`. Under `--transport streamable-http`+one process serves every caller, so `fetch` — which read that cache with no+credential resolution and no ownership check — returned one caller's cached+ad-account, campaign, ad, page and business records to any other caller+(GHSA-j7p8-g5m6-3wv5).++The module is gone rather than scoped: in production 100% of `fetch` calls+already failed (70% "Record not found", the rest schema-validation errors from+clients treating it as a generic Graph fetch), so the tool had no working use+to preserve. These tests fail if it comes back.+"""++import importlib++import pytest+++def test_openai_deep_research_module_is_gone():+ """The module that held the process-global record cache must not exist."""+ with pytest.raises(ModuleNotFoundError):+ importlib.import_module("meta_ads_mcp.core.openai_deep_research")+++def test_core_package_exports_no_search_or_fetch():+ import meta_ads_mcp.core as core++ assert not hasattr(core, "fetch"), "fetch was re-exported from meta_ads_mcp.core"+ assert not hasattr(core, "search"), "search was re-exported from meta_ads_mcp.core"+ assert "fetch" not in core.__all__+ assert "search" not in core.__all__+++async def test_search_and_fetch_are_not_registered_tools():+ from meta_ads_mcp.core.server import mcp_server++ tool_names = {tool.name for tool in await mcp_server.list_tools()}++ assert "fetch" not in tool_names, "the cross-caller-readable fetch tool is registered again"+ assert "search" not in tool_names, "the deep-research search tool is registered again"+++async def test_unrelated_tools_survived_the_removal():+ """Removing the module must not take neighbouring tools with it."""+ from meta_ads_mcp.core.server import mcp_server++ tool_names = {tool.name for tool in await mcp_server.list_tools()}++ for expected in ("get_ad_accounts", "get_campaigns", "get_insights", "search_interests"):+ assert expected in tool_names, f"{expected} disappeared along with the deep-research tools"diff --git a/tests/test_integration_openai_mcp.py b/tests/test_integration_openai_mcp.pydeleted file mode 100644index eec41a9..0000000--- a/tests/test_integration_openai_mcp.py+++ /dev/null@@ -1,242 +0,0 @@-#!/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 filediff --git a/tests/test_openai_mcp_deep_research.py b/tests/test_openai_mcp_deep_research.pydeleted file mode 100644index a93a1d6..0000000--- a/tests/test_openai_mcp_deep_research.py+++ /dev/null@@ -1,432 +0,0 @@-#!/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 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")- 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"])-- # 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- 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 (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")-- 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