Skip to content

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

Refactor get_account_info function to improve error handling and accessibility checks

Yves Junqueira1557077bfb6b
diff --git a/meta_ads_mcp/core/accounts.py b/meta_ads_mcp/core/accounts.py
index db788b5..e2ba9c4 100644
--- a/meta_ads_mcp/core/accounts.py
+++ b/meta_ads_mcp/core/accounts.py
@@ -51,32 +51,7 @@ async def get_account_info(access_token: str = None, account_id: str = None) ->
if not account_id.startswith("act_"):
account_id = f"act_{account_id}"
- # First, check if the account is accessible to the user
- endpoint = "me/adaccounts"
- params = {
- "fields": "id,name,account_id,account_status,amount_spent,balance,currency,age,business_city,business_country_code",
- "limit": 50
- }
- accessible_accounts_data = await make_api_request(endpoint, access_token, params)
-
- if "data" in accessible_accounts_data:
- accessible_account_ids = [acc["id"] for acc in accessible_accounts_data["data"]]
- if account_id not in accessible_account_ids:
- # Provide a helpful error message with accessible accounts
- accessible_accounts = [
- {"id": acc["id"], "name": acc["name"]}
- for acc in accessible_accounts_data["data"][:10] # Show first 10
- ]
- return {
- "error": {
- "message": f"Account {account_id} is not accessible to your user account",
- "details": "This account either doesn't exist or you don't have permission to access it",
- "accessible_accounts": accessible_accounts,
- "total_accessible_accounts": len(accessible_accounts_data["data"]),
- "suggestion": "Try using one of the accessible account IDs listed above"
- }
- }
-
+ # Try to get the account info directly first
endpoint = f"{account_id}"
params = {
"fields": "id,name,account_id,account_status,amount_spent,balance,currency,age,business_city,business_country_code,timezone_name"
@@ -86,6 +61,32 @@ async def get_account_info(access_token: str = None, account_id: str = None) ->
# Check if the API request returned an error
if "error" in data:
+ # If access was denied, provide helpful error message with accessible accounts
+ if "access" in str(data.get("error", {})).lower() or "permission" in str(data.get("error", {})).lower():
+ # Get list of accessible accounts for helpful error message
+ accessible_endpoint = "me/adaccounts"
+ accessible_params = {
+ "fields": "id,name,account_id,account_status,amount_spent,balance,currency,age,business_city,business_country_code",
+ "limit": 50
+ }
+ accessible_accounts_data = await make_api_request(accessible_endpoint, access_token, accessible_params)
+
+ if "data" in accessible_accounts_data:
+ accessible_accounts = [
+ {"id": acc["id"], "name": acc["name"]}
+ for acc in accessible_accounts_data["data"][:10] # Show first 10
+ ]
+ return {
+ "error": {
+ "message": f"Account {account_id} is not accessible to your user account",
+ "details": "This account either doesn't exist or you don't have permission to access it",
+ "accessible_accounts": accessible_accounts,
+ "total_accessible_accounts": len(accessible_accounts_data["data"]),
+ "suggestion": "Try using one of the accessible account IDs listed above"
+ }
+ }
+
+ # Return the original error for non-permission related issues
return data
# Add DSA requirement detection
diff --git a/meta_ads_mcp/core/openai_deep_research.py b/meta_ads_mcp/core/openai_deep_research.py
index 4555d49..2075118 100644
--- a/meta_ads_mcp/core/openai_deep_research.py
+++ b/meta_ads_mcp/core/openai_deep_research.py
@@ -23,7 +23,7 @@ class MetaAdsDataManager:
self._cache = {}
logger.debug("MetaAdsDataManager initialized")
- async def _get_ad_accounts(self, access_token: str, limit: int = 25) -> List[Dict[str, Any]]:
+ async def _get_ad_accounts(self, access_token: str, limit: int = 200) -> List[Dict[str, Any]]:
"""Get ad accounts data"""
try:
endpoint = "me/adaccounts"
@@ -141,7 +141,7 @@ class MetaAdsDataManager:
try:
# Search ad accounts
- accounts = await self._get_ad_accounts(access_token, limit=25)
+ 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()
diff --git a/tests/e2e_account_info_search_issue.py b/tests/e2e_account_info_search_issue.py
new file mode 100644
index 0000000..22549db
--- /dev/null
+++ b/tests/e2e_account_info_search_issue.py
@@ -0,0 +1,320 @@
+#!/usr/bin/env python3
+"""
+E2E Test for Account Info Search Issue
+
+This test reproduces the issue reported by a user where get_account_info
+cannot find account ID 414174661097171, while get_ad_accounts can see it.
+
+Usage:
+ 1. Start the server: uv run python -m meta_ads_mcp --transport streamable-http --port 8080
+ 2. Run test: uv run python tests/e2e_account_info_search_issue.py
+
+Or with pytest (manual only):
+ uv run python -m pytest tests/e2e_account_info_search_issue.py -v -m e2e
+"""
+
+import pytest
+import requests
+import json
+from typing import Dict, Any
+
[email protected](reason="E2E test - run manually only")
+class TestAccountInfoSearchIssue:
+ """E2E test for account info search issue"""
+
+ 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
+ self.target_account_id = "414174661097171"
+
+ def test_get_ad_accounts_can_see_target_account(self):
+ """Verify get_ad_accounts can see account 414174661097171"""
+ print(f"\n🔍 Testing if get_ad_accounts can see account {self.target_account_id}")
+
+ params = {
+ "name": "get_ad_accounts",
+ "arguments": {}
+ }
+
+ result = self._make_request("tools/call", params)
+
+ if not result["success"]:
+ return {
+ "success": False,
+ "error": f"Request failed: {result.get('error', 'Unknown error')}",
+ "status_code": result["status_code"]
+ }
+
+ try:
+ response_data = result["json"]["result"]
+ content = response_data.get("content", [{}])[0].get("text", "")
+ parsed_content = json.loads(content)
+
+ # Check for errors first
+ error_info = self._check_for_errors(parsed_content)
+ if error_info["has_error"]:
+ return {
+ "success": False,
+ "error": f"get_ad_accounts returned error: {error_info['error_message']}",
+ "error_format": error_info["format"]
+ }
+
+ # Extract accounts data
+ accounts = []
+ if "data" in parsed_content:
+ data = parsed_content["data"]
+
+ # Handle case where data is already parsed (list/dict)
+ if isinstance(data, list):
+ accounts = data
+ elif isinstance(data, dict) and "data" in data:
+ accounts = data["data"]
+
+ # Handle case where data is a JSON string that needs parsing
+ elif isinstance(data, str):
+ try:
+ parsed_data = json.loads(data)
+ if isinstance(parsed_data, list):
+ accounts = parsed_data
+ elif isinstance(parsed_data, dict) and "data" in parsed_data:
+ accounts = parsed_data["data"]
+ except json.JSONDecodeError:
+ pass
+ elif isinstance(parsed_content, list):
+ accounts = parsed_content
+
+ # Search for target account
+ found_account = None
+ for account in accounts:
+ if isinstance(account, dict):
+ account_id = account.get("id", "").replace("act_", "")
+ if account_id == self.target_account_id:
+ found_account = account
+ break
+
+ result_data = {
+ "success": True,
+ "total_accounts": len(accounts),
+ "target_account_found": found_account is not None,
+ "found_account_details": found_account if found_account else None,
+ "all_account_ids": [
+ acc.get("id", "").replace("act_", "")
+ for acc in accounts
+ if isinstance(acc, dict) and acc.get("id")
+ ]
+ }
+
+ print(f"✅ get_ad_accounts results:")
+ print(f" Total accounts found: {result_data['total_accounts']}")
+ print(f" Target account {self.target_account_id} found: {result_data['target_account_found']}")
+ if found_account:
+ print(f" Account details: {found_account}")
+
+ return result_data
+
+ except json.JSONDecodeError as e:
+ return {
+ "success": False,
+ "error": f"Could not parse get_ad_accounts response: {str(e)}",
+ "raw_content": content
+ }
+
+ def test_get_account_info_cannot_find_target_account(self):
+ """Verify get_account_info cannot find account 414174661097171"""
+ print(f"\n🔍 Testing if get_account_info can find account {self.target_account_id}")
+
+ params = {
+ "name": "get_account_info",
+ "arguments": {
+ "account_id": self.target_account_id
+ }
+ }
+
+ result = self._make_request("tools/call", params)
+
+ if not result["success"]:
+ return {
+ "success": False,
+ "error": f"Request failed: {result.get('error', 'Unknown error')}",
+ "status_code": result["status_code"]
+ }
+
+ try:
+ response_data = result["json"]["result"]
+ content = response_data.get("content", [{}])[0].get("text", "")
+ parsed_content = json.loads(content)
+
+ # Check for errors
+ error_info = self._check_for_errors(parsed_content)
+
+ result_data = {
+ "success": True,
+ "has_error": error_info["has_error"],
+ "error_message": error_info.get("error_message", ""),
+ "error_format": error_info.get("format", ""),
+ "raw_response": parsed_content
+ }
+
+ print(f"✅ get_account_info results:")
+ print(f" Has error: {result_data['has_error']}")
+ if result_data['has_error']:
+ print(f" Error message: {result_data['error_message']}")
+ print(f" Error format: {result_data['error_format']}")
+ else:
+ print(f" Unexpected success: {parsed_content}")
+
+ return result_data
+
+ except json.JSONDecodeError as e:
+ return {
+ "success": False,
+ "error": f"Could not parse get_account_info response: {str(e)}",
+ "raw_content": content
+ }
+
+ def _check_for_errors(self, parsed_content: Dict[str, Any]) -> Dict[str, Any]:
+ """Properly handle both wrapped and direct error formats"""
+
+ # Check for data wrapper format first
+ if "data" in parsed_content:
+ data = parsed_content["data"]
+
+ # Handle case where data is already parsed (dict/list)
+ if isinstance(data, dict) and 'error' in data:
+ return {
+ "has_error": True,
+ "error_message": data['error'],
+ "error_details": data.get('details', ''),
+ "format": "wrapped_dict"
+ }
+
+ # Handle case where data is a JSON string that needs parsing
+ if isinstance(data, str):
+ try:
+ error_data = json.loads(data)
+ if 'error' in error_data:
+ return {
+ "has_error": True,
+ "error_message": error_data['error'],
+ "error_details": error_data.get('details', ''),
+ "format": "wrapped_json"
+ }
+ except json.JSONDecodeError:
+ # Data field exists but isn't valid JSON
+ pass
+
+ # Check for direct error format
+ if 'error' in parsed_content:
+ return {
+ "has_error": True,
+ "error_message": parsed_content['error'],
+ "error_details": parsed_content.get('details', ''),
+ "format": "direct"
+ }
+
+ return {"has_error": False}
+
+ def _make_request(self, method: str, params: Dict[str, Any] = None) -> Dict[str, Any]:
+ """Make a JSON-RPC request to the MCP server"""
+
+ headers = {
+ "Content-Type": "application/json",
+ "Accept": "application/json, text/event-stream",
+ "User-Agent": "E2E-Test-Client/1.0"
+ }
+
+ payload = {
+ "jsonrpc": "2.0",
+ "method": method,
+ "id": self.request_id
+ }
+
+ if params:
+ payload["params"] = params
+
+ try:
+ response = requests.post(
+ self.endpoint,
+ headers=headers,
+ json=payload,
+ timeout=30
+ )
+
+ self.request_id += 1
+
+ return {
+ "status_code": response.status_code,
+ "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,
+ "json": None,
+ "text": str(e),
+ "success": False,
+ "error": str(e)
+ }
+
+def run_validation():
+ """Run the validation tests"""
+ print("🚀 Starting Account Info Search Issue Validation")
+ print(f"Target Account ID: 414174661097171")
+ print("="*60)
+
+ test_instance = TestAccountInfoSearchIssue()
+
+ # Test 1: Check if get_ad_accounts can see the account
+ accounts_result = test_instance.test_get_ad_accounts_can_see_target_account()
+
+ # Test 2: Check if get_account_info can find the account
+ account_info_result = test_instance.test_get_account_info_cannot_find_target_account()
+
+ print("\n" + "="*60)
+ print("📊 VALIDATION SUMMARY")
+ print("="*60)
+
+ if accounts_result["success"]:
+ print(f"✅ get_ad_accounts: Found {accounts_result['total_accounts']} total accounts")
+ if accounts_result["target_account_found"]:
+ print(f"✅ get_ad_accounts: Target account 414174661097171 IS visible")
+ else:
+ print(f"❌ get_ad_accounts: Target account 414174661097171 is NOT visible")
+ print(f" Available account IDs: {accounts_result.get('all_account_ids', [])}")
+ else:
+ print(f"❌ get_ad_accounts: Failed - {accounts_result['error']}")
+
+ if account_info_result["success"]:
+ if account_info_result["has_error"]:
+ print(f"❌ get_account_info: Cannot find account (Error: {account_info_result['error_message']})")
+ else:
+ print(f"✅ get_account_info: Successfully found account")
+ else:
+ print(f"❌ get_account_info: Test failed - {account_info_result['error']}")
+
+ # Determine if issue is confirmed
+ issue_confirmed = (
+ accounts_result.get("success", False) and
+ accounts_result.get("target_account_found", False) and
+ account_info_result.get("success", False) and
+ account_info_result.get("has_error", False)
+ )
+
+ print("\n" + "="*60)
+ if issue_confirmed:
+ print("🐛 ISSUE CONFIRMED:")
+ print(" - get_ad_accounts CAN see the account")
+ print(" - get_account_info CANNOT find the account")
+ print(" - This validates the user's complaint")
+ else:
+ print("🤔 ISSUE NOT CONFIRMED:")
+ print(" - The behavior may be different than reported")
+ print(" - Check individual test results above")
+ print("="*60)
+
+if __name__ == "__main__":
+ run_validation()
\ No newline at end of file
diff --git a/tests/test_account_info_access_fix.py b/tests/test_account_info_access_fix.py
new file mode 100644
index 0000000..c61d0ca
--- /dev/null
+++ b/tests/test_account_info_access_fix.py
@@ -0,0 +1,317 @@
+#!/usr/bin/env python3
+"""
+Unit tests for get_account_info accessibility fix.
+
+This module tests the fix for the issue where get_account_info couldn't access
+accounts that were visible in get_ad_accounts but not in the limited direct
+accessibility list.
+
+The fix changes the logic to try fetching account info directly first,
+rather than pre-checking against a limited accessibility list.
+"""
+
+import pytest
+import json
+from unittest.mock import AsyncMock, patch
+
+from meta_ads_mcp.core.accounts import get_account_info
+
+
+class TestAccountInfoAccessFix:
+ """Test cases for the get_account_info accessibility fix"""
+
+ @pytest.mark.asyncio
+ async def test_account_info_direct_access_success(self):
+ """Test that get_account_info works when direct API call succeeds"""
+
+ # Mock the direct account info API response
+ mock_account_response = {
+ "id": "act_414174661097171",
+ "name": "Venture Hunting & Outdoors",
+ "account_id": "414174661097171",
+ "account_status": 1,
+ "amount_spent": "5818510",
+ "balance": "97677",
+ "currency": "AUD",
+ "timezone_name": "Australia/Brisbane",
+ "business_country_code": "AU"
+ }
+
+ with patch('meta_ads_mcp.core.accounts.make_api_request', new_callable=AsyncMock) as mock_api:
+ with patch('meta_ads_mcp.core.api.get_current_access_token', new_callable=AsyncMock) as mock_auth:
+ mock_auth.return_value = "test_access_token"
+ mock_api.return_value = mock_account_response
+
+ result = await get_account_info(account_id="414174661097171")
+
+ # Handle both string and dict return formats
+ if isinstance(result, str):
+ result_data = json.loads(result)
+ else:
+ result_data = result
+
+ # Verify the account info was returned successfully
+ assert "error" not in result_data
+ assert result_data["id"] == "act_414174661097171"
+ assert result_data["name"] == "Venture Hunting & Outdoors"
+ assert result_data["account_id"] == "414174661097171"
+ assert result_data["currency"] == "AUD"
+ assert result_data["timezone_name"] == "Australia/Brisbane"
+
+ # Verify DSA compliance detection was added
+ assert "dsa_required" in result_data
+ assert result_data["dsa_required"] is False # AU is not European
+ assert "dsa_compliance_note" in result_data
+
+ # Verify the API was called with correct parameters
+ mock_api.assert_called_once_with(
+ "act_414174661097171",
+ "test_access_token",
+ {
+ "fields": "id,name,account_id,account_status,amount_spent,balance,currency,age,business_city,business_country_code,timezone_name"
+ }
+ )
+
+ @pytest.mark.asyncio
+ async def test_account_info_permission_error_with_helpful_message(self):
+ """Test that permission errors provide helpful error messages with accessible accounts"""
+
+ # Mock the permission error response from direct API call
+ mock_permission_error = {
+ "error": {
+ "message": "Insufficient privileges to access the object",
+ "type": "OAuthException",
+ "code": 200
+ }
+ }
+
+ # Mock accessible accounts response for helpful error message
+ mock_accessible_accounts = {
+ "data": [
+ {"id": "act_123456", "name": "Accessible Account 1"},
+ {"id": "act_789012", "name": "Accessible Account 2"},
+ {"id": "act_345678", "name": "Accessible Account 3"}
+ ]
+ }
+
+ with patch('meta_ads_mcp.core.accounts.make_api_request', new_callable=AsyncMock) as mock_api:
+ with patch('meta_ads_mcp.core.api.get_current_access_token', new_callable=AsyncMock) as mock_auth:
+ mock_auth.return_value = "test_access_token"
+
+ # First call returns permission error, second call returns accessible accounts
+ mock_api.side_effect = [mock_permission_error, mock_accessible_accounts]
+
+ result = await get_account_info(account_id="414174661097171")
+
+ # Handle both string and dict return formats
+ if isinstance(result, str):
+ result_data = json.loads(result)
+ else:
+ result_data = result
+
+ # Verify helpful error message
+ assert "error" in result_data
+ assert "not accessible to your user account" in result_data["error"]["message"]
+ assert "accessible_accounts" in result_data["error"]
+ assert "suggestion" in result_data["error"]
+ assert result_data["error"]["total_accessible_accounts"] == 3
+
+ # Verify accessible accounts list
+ accessible_accounts = result_data["error"]["accessible_accounts"]
+ assert len(accessible_accounts) == 3
+ assert accessible_accounts[0]["id"] == "act_123456"
+ assert accessible_accounts[0]["name"] == "Accessible Account 1"
+
+ # Verify API calls were made
+ assert mock_api.call_count == 2
+
+ # First call: direct account access attempt
+ mock_api.assert_any_call(
+ "act_414174661097171",
+ "test_access_token",
+ {
+ "fields": "id,name,account_id,account_status,amount_spent,balance,currency,age,business_city,business_country_code,timezone_name"
+ }
+ )
+
+ # Second call: get accessible accounts for error message
+ mock_api.assert_any_call(
+ "me/adaccounts",
+ "test_access_token",
+ {
+ "fields": "id,name,account_id,account_status,amount_spent,balance,currency,age,business_city,business_country_code",
+ "limit": 50
+ }
+ )
+
+ @pytest.mark.asyncio
+ async def test_account_info_non_permission_error_passthrough(self):
+ """Test that non-permission errors are passed through unchanged"""
+
+ # Mock a non-permission error (e.g., invalid account ID)
+ mock_error_response = {
+ "error": {
+ "message": "Invalid account ID format",
+ "type": "GraphAPIException",
+ "code": 100
+ }
+ }
+
+ with patch('meta_ads_mcp.core.accounts.make_api_request', new_callable=AsyncMock) as mock_api:
+ with patch('meta_ads_mcp.core.api.get_current_access_token', new_callable=AsyncMock) as mock_auth:
+ mock_auth.return_value = "test_access_token"
+ mock_api.return_value = mock_error_response
+
+ result = await get_account_info(account_id="invalid_id")
+
+ # Handle both string and dict return formats
+ if isinstance(result, str):
+ result_data = json.loads(result)
+ else:
+ result_data = result
+
+ # Verify the original error is returned unchanged
+ assert result_data == mock_error_response
+
+ # Verify only one API call was made (no attempt to get accessible accounts)
+ mock_api.assert_called_once()
+
+ @pytest.mark.asyncio
+ async def test_account_info_missing_account_id_error(self):
+ """Test that missing account_id parameter returns appropriate error"""
+
+ with patch('meta_ads_mcp.core.api.get_current_access_token', new_callable=AsyncMock) as mock_auth:
+ mock_auth.return_value = "test_access_token"
+
+ result = await get_account_info(account_id=None)
+
+ # Handle both string and dict return formats
+ if isinstance(result, str):
+ result_data = json.loads(result)
+ else:
+ result_data = result
+
+ # Verify error message
+ assert "error" in result_data
+ assert "Account ID is required" in result_data["error"]["message"]
+ assert "Please specify an account_id parameter" in result_data["error"]["details"]
+
+ @pytest.mark.asyncio
+ async def test_account_info_act_prefix_handling(self):
+ """Test that account_id prefix handling works correctly"""
+
+ mock_account_response = {
+ "id": "act_123456789",
+ "name": "Test Account",
+ "account_id": "123456789"
+ }
+
+ with patch('meta_ads_mcp.core.accounts.make_api_request', new_callable=AsyncMock) as mock_api:
+ with patch('meta_ads_mcp.core.api.get_current_access_token', new_callable=AsyncMock) as mock_auth:
+ mock_auth.return_value = "test_access_token"
+ mock_api.return_value = mock_account_response
+
+ # Test with account ID without act_ prefix
+ result = await get_account_info(account_id="123456789")
+
+ # Verify the API was called with the act_ prefix added
+ mock_api.assert_called_once_with(
+ "act_123456789", # Should have act_ prefix added
+ "test_access_token",
+ {
+ "fields": "id,name,account_id,account_status,amount_spent,balance,currency,age,business_city,business_country_code,timezone_name"
+ }
+ )
+
+ @pytest.mark.asyncio
+ async def test_account_info_european_dsa_detection(self):
+ """Test that DSA requirements are properly detected for European accounts"""
+
+ # Mock account response for German business
+ mock_account_response = {
+ "id": "act_999888777",
+ "name": "German Test Account",
+ "account_id": "999888777",
+ "business_country_code": "DE" # Germany - should trigger DSA
+ }
+
+ with patch('meta_ads_mcp.core.accounts.make_api_request', new_callable=AsyncMock) as mock_api:
+ with patch('meta_ads_mcp.core.api.get_current_access_token', new_callable=AsyncMock) as mock_auth:
+ mock_auth.return_value = "test_access_token"
+ mock_api.return_value = mock_account_response
+
+ result = await get_account_info(account_id="999888777")
+
+ # Handle both string and dict return formats
+ if isinstance(result, str):
+ result_data = json.loads(result)
+ else:
+ result_data = result
+
+ # Verify DSA requirements were properly detected
+ assert "dsa_required" in result_data
+ assert result_data["dsa_required"] is True # DE is European
+ assert "dsa_compliance_note" in result_data
+ assert "European DSA" in result_data["dsa_compliance_note"]
+
+
+class TestAccountInfoAccessRegression:
+ """Regression tests to ensure the fix doesn't break existing functionality"""
+
+ @pytest.mark.asyncio
+ async def test_regression_basic_account_info_still_works(self):
+ """Regression test: ensure basic account info functionality still works"""
+
+ mock_account_response = {
+ "id": "act_123456789",
+ "name": "Basic Test Account",
+ "account_id": "123456789",
+ "account_status": 1,
+ "currency": "USD",
+ "business_country_code": "US"
+ }
+
+ with patch('meta_ads_mcp.core.accounts.make_api_request', new_callable=AsyncMock) as mock_api:
+ with patch('meta_ads_mcp.core.api.get_current_access_token', new_callable=AsyncMock) as mock_auth:
+ mock_auth.return_value = "test_access_token"
+ mock_api.return_value = mock_account_response
+
+ result = await get_account_info(account_id="act_123456789")
+
+ # Handle both string and dict return formats
+ if isinstance(result, str):
+ result_data = json.loads(result)
+ else:
+ result_data = result
+
+ # Verify basic functionality works
+ assert "error" not in result_data
+ assert result_data["id"] == "act_123456789"
+ assert result_data["name"] == "Basic Test Account"
+
+ def test_account_info_fix_comparison(self):
+ """
+ Documentation test: explains what the fix changed
+
+ BEFORE: get_account_info checked accessibility first against limited list (50 accounts)
+ AFTER: get_account_info tries direct API call first, only shows error if API fails
+
+ This allows accounts visible through business manager (like 414174661097171)
+ to work properly even if they're not in the limited direct accessibility list.
+ """
+
+ # This is a documentation test - no actual code execution
+ old_behavior = "Pre-check accessibility against limited 50 account list"
+ new_behavior = "Try direct API call first, handle permission errors gracefully"
+
+ assert old_behavior != new_behavior
+
+ # The key insight: get_ad_accounts shows 107 accounts through business manager,
+ # but "me/adaccounts" only shows 50 directly accessible accounts
+ total_visible_accounts = 107
+ directly_accessible_accounts = 50
+
+ assert total_visible_accounts > directly_accessible_accounts
+
+ # Account 414174661097171 was in the 107 but not in the 50
+ # The fix allows get_account_info to work for such accounts
\ No newline at end of file
diff --git a/tests/test_dsa_beneficiary.py b/tests/test_dsa_beneficiary.py
index 05bd6fa..3230360 100644
--- a/tests/test_dsa_beneficiary.py
+++ b/tests/test_dsa_beneficiary.py
@@ -122,7 +122,16 @@ class TestDSABeneficiaryDetection:
async def test_account_info_inaccessible_account_error(self):
"""Test that get_account_info provides helpful error for inaccessible accounts"""
- # Mock accessible accounts response
+ # Mock permission error for direct account access (first API call)
+ mock_permission_error = {
+ "error": {
+ "message": "Insufficient access privileges",
+ "type": "OAuthException",
+ "code": 200
+ }
+ }
+
+ # Mock accessible accounts response (second API call)
mock_accessible_accounts = {
"data": [
{"id": "act_123", "name": "Test Account 1"},
@@ -133,7 +142,8 @@ class TestDSABeneficiaryDetection:
with patch('meta_ads_mcp.core.accounts.make_api_request', new_callable=AsyncMock) as mock_api:
with patch('meta_ads_mcp.core.api.get_current_access_token', new_callable=AsyncMock) as mock_auth:
mock_auth.return_value = "test_access_token"
- mock_api.return_value = mock_accessible_accounts
+ # First call returns permission error, second call returns accessible accounts
+ mock_api.side_effect = [mock_permission_error, mock_accessible_accounts]
result = await get_account_info(account_id="act_inaccessible")
diff --git a/tests/test_dsa_integration.py b/tests/test_dsa_integration.py
index 0066e30..3bb945e 100644
--- a/tests/test_dsa_integration.py
+++ b/tests/test_dsa_integration.py
@@ -420,7 +420,16 @@ class TestDSAIntegration:
async def test_account_info_inaccessible_account_error(self):
"""Test that get_account_info provides helpful error for inaccessible accounts"""
- # Mock accessible accounts response
+ # Mock permission error for direct account access (first API call)
+ mock_permission_error = {
+ "error": {
+ "message": "Insufficient access privileges",
+ "type": "OAuthException",
+ "code": 200
+ }
+ }
+
+ # Mock accessible accounts response (second API call)
mock_accessible_accounts = {
"data": [
{"id": "act_123", "name": "Test Account 1"},
@@ -431,7 +440,8 @@ class TestDSAIntegration:
with patch('meta_ads_mcp.core.accounts.make_api_request', new_callable=AsyncMock) as mock_api:
with patch('meta_ads_mcp.core.api.get_current_access_token', new_callable=AsyncMock) as mock_auth:
mock_auth.return_value = "test_access_token"
- mock_api.return_value = mock_accessible_accounts
+ # First call returns permission error, second call returns accessible accounts
+ mock_api.side_effect = [mock_permission_error, mock_accessible_accounts]
result = await get_account_info(account_id="act_inaccessible")