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(get_account_info): improve error handling and user experience
Yves Junqueira723ec0ee614f
diff --git a/meta_ads_mcp/core/accounts.py b/meta_ads_mcp/core/accounts.pyindex c146947..9c387a1 100644--- a/meta_ads_mcp/core/accounts.py+++ b/meta_ads_mcp/core/accounts.py@@ -36,29 +36,58 @@ async def get_account_info(access_token: str = None, account_id: str = None) ->Args:access_token: Meta API access token (optional - will use cached token if not provided)- account_id: Meta Ads account ID (format: act_XXXXXXXXX)+ account_id: Meta Ads account ID (format: act_XXXXXXXXX) - REQUIRED"""- # If no account ID is specified, try to get the first one for the userif not account_id:- accounts_json = await get_ad_accounts("me", json.dumps({"limit": 1}), access_token)- accounts_data = json.loads(accounts_json)-- if "data" in accounts_data and accounts_data["data"]:- account_id = accounts_data["data"][0]["id"]- else:- return json.dumps({"error": "No account ID specified and no accounts found for user"}, indent=2)+ return {+ "error": {+ "message": "Account ID is required",+ "details": "Please specify an account_id parameter",+ "example": "Use account_id='act_123456789' or account_id='123456789'"+ }+ }# Ensure account_id has the 'act_' prefix for API compatibilityif 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"+ }+ }+endpoint = f"{account_id}"params = {- "fields": "id,name,account_id,account_status,amount_spent,balance,currency,age,funding_source_details,business_city,business_country_code,timezone_name,owner"+ "fields": "id,name,account_id,account_status,amount_spent,balance,currency,age,business_city,business_country_code,timezone_name"}data = await make_api_request(endpoint, access_token, params)+ # Check if the API request returned an error+ if "error" in data:+ return data+# Add DSA requirement detectionif "business_country_code" in data:european_countries = ["DE", "FR", "IT", "ES", "NL", "BE", "AT", "IE", "DK", "SE", "FI", "NO"]@@ -69,4 +98,4 @@ async def get_account_info(access_token: str = None, account_id: str = None) ->data["dsa_required"] = Falsedata["dsa_compliance_note"] = "This account is not subject to European DSA requirements"- return json.dumps(data, indent=2)\ No newline at end of file+ return data\ No newline at end of filediff --git a/meta_ads_mcp/core/auth.py b/meta_ads_mcp/core/auth.pyindex a969599..7cd2125 100644--- a/meta_ads_mcp/core/auth.py+++ b/meta_ads_mcp/core/auth.py@@ -25,7 +25,7 @@ from .pipeboard_auth import pipeboard_auth_manager# Auth constants# Scope includes pages_show_list and pages_read_engagement to fix issue #16# where get_account_pages failed for regular users due to missing page permissions-AUTH_SCOPE = "ads_management,ads_read,business_management,public_profile,pages_show_list,pages_read_engagement"+AUTH_SCOPE = "business_management,public_profile,pages_show_list,pages_read_engagement"AUTH_REDIRECT_URI = "http://localhost:8888/callback"AUTH_RESPONSE_TYPE = "token"diff --git a/meta_ads_mcp/core/pipeboard_auth.py b/meta_ads_mcp/core/pipeboard_auth.pyindex 6182dc8..1bee1b8 100644--- a/meta_ads_mcp/core/pipeboard_auth.py+++ b/meta_ads_mcp/core/pipeboard_auth.py@@ -151,6 +151,18 @@ class PipeboardAuthManager:with open(cache_path, "r") as f:logger.debug(f"Reading token cache from {cache_path}")data = json.load(f)++ # Validate the cached data structure+ required_fields = ["access_token"]+ if not all(field in data for field in required_fields):+ logger.warning("Cached token data is missing required fields")+ return False++ # Check if the token looks valid (basic format check)+ if not data.get("access_token") or len(data["access_token"]) < 20:+ logger.warning("Cached token appears malformed")+ return False+self.token_info = TokenInfo.deserialize(data)# Log token details (partial token for security)@@ -159,7 +171,25 @@ class PipeboardAuthManager:# Check if token is expiredif self.token_info.is_expired():- logger.info("Cached token is expired")+ logger.info("Cached token is expired, removing cache file")+ # Remove the expired cache file+ try:+ cache_path.unlink()+ logger.info(f"Removed expired token cache: {cache_path}")+ except Exception as e:+ logger.warning(f"Could not remove expired cache file: {e}")+ self.token_info = None+ return False++ # Additional validation: check if token is too old (more than 60 days)+ current_time = int(time.time())+ if self.token_info.created_at and (current_time - self.token_info.created_at) > (60 * 24 * 3600):+ logger.warning("Cached token is too old (more than 60 days), removing cache file")+ try:+ cache_path.unlink()+ logger.info(f"Removed old token cache: {cache_path}")+ except Exception as e:+ logger.warning(f"Could not remove old cache file: {e}")self.token_info = Nonereturn False@@ -174,9 +204,21 @@ class PipeboardAuthManager:logger.debug(f"Raw cache file content (first 100 chars): {raw_content[:100]}")except Exception as e2:logger.error(f"Could not read raw cache file: {e2}")+ # If there's any error reading the cache, try to remove the corrupted file+ try:+ cache_path.unlink()+ logger.info(f"Removed corrupted token cache: {cache_path}")+ except Exception as cleanup_error:+ logger.warning(f"Could not remove corrupted cache file: {cleanup_error}")return Falseexcept Exception as e:logger.error(f"Error loading cached token: {e}")+ # If there's any error reading the cache, try to remove the corrupted file+ try:+ cache_path.unlink()+ logger.info(f"Removed corrupted token cache: {cache_path}")+ except Exception as cleanup_error:+ logger.warning(f"Could not remove corrupted cache file: {cleanup_error}")return Falsedef _save_token_to_cache(self) -> None:diff --git a/tests/test_dsa_beneficiary.py b/tests/test_dsa_beneficiary.pyindex c62d3ae..05bd6fa 100644--- a/tests/test_dsa_beneficiary.py+++ b/tests/test_dsa_beneficiary.py@@ -19,10 +19,10 @@ class TestDSABeneficiaryDetection:@pytest.mark.asyncioasync def test_dsa_requirement_detection_business_account(self):- """Test detection of DSA requirements for business accounts"""+ """Test DSA requirement detection for European business accounts"""mock_account_response = {"id": "act_701351919139047",- "name": "Test Business Account",+ "name": "Test European Business Account","account_status": 1,"business_country_code": "DE", # Germany - DSA compliant"business_city": "Berlin",@@ -35,7 +35,12 @@ class TestDSABeneficiaryDetection:mock_api.return_value = mock_account_responseresult = await get_account_info(account_id="act_701351919139047")- result_data = json.loads(result)++ # Handle new return format (dictionary instead of JSON string)+ if isinstance(result, dict):+ result_data = result+ else:+ result_data = json.loads(result)# Verify account info is retrievedassert result_data["id"] == "act_701351919139047"@@ -62,7 +67,12 @@ class TestDSABeneficiaryDetection:mock_api.return_value = mock_account_responseresult = await get_account_info(account_id="act_123456789")- result_data = json.loads(result)++ # Handle new return format (dictionary instead of JSON string)+ if isinstance(result, dict):+ result_data = result+ else:+ result_data = json.loads(result)# Verify no DSA requirement for US accountsassert result_data["business_country_code"] == "US"@@ -77,7 +87,7 @@ class TestDSABeneficiaryDetection:result = await get_account_info(account_id="act_invalid")- # Handle response format - could be dict or JSON string+ # Handle new return format (dictionary instead of JSON string)if isinstance(result, dict):result_data = resultelse:@@ -85,6 +95,60 @@ class TestDSABeneficiaryDetection:# Verify error is properly handledassert "error" in result_data++ @pytest.mark.asyncio+ async def test_account_info_requires_account_id(self):+ """Test that get_account_info requires an account_id parameter"""++ with patch('meta_ads_mcp.core.api.get_current_access_token', new_callable=AsyncMock) as mock_auth:+ mock_auth.return_value = "test_access_token"++ # Test without account_id parameter+ result = await get_account_info()++ # Handle new return format (dictionary instead of JSON string)+ if isinstance(result, dict):+ result_data = result+ else:+ result_data = json.loads(result)++ # Verify error message for missing account_id+ 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"]+ assert "example" in result_data["error"]++ @pytest.mark.asyncio+ 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_accessible_accounts = {+ "data": [+ {"id": "act_123", "name": "Test Account 1"},+ {"id": "act_456", "name": "Test Account 2"}+ ]+ }++ 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++ result = await get_account_info(account_id="act_inaccessible")++ # Handle new return format (dictionary instead of JSON string)+ if isinstance(result, dict):+ result_data = result+ else:+ result_data = json.loads(result)++ # Verify helpful error message for inaccessible account+ 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 len(result_data["error"]["accessible_accounts"]) == 2class TestDSABeneficiaryParameter:diff --git a/tests/test_dsa_integration.py b/tests/test_dsa_integration.pyindex 3dd4f7f..0066e30 100644--- a/tests/test_dsa_integration.py+++ b/tests/test_dsa_integration.py@@ -19,12 +19,12 @@ class TestDSAIntegration:@pytest.mark.asyncioasync def test_dsa_beneficiary_complete_workflow(self):- """Test complete DSA beneficiary workflow from detection to creation"""+ """Test complete DSA beneficiary workflow from account detection to ad set creation"""- # Step 1: Detect DSA requirements for European account+ # Step 1: Get account info and detect DSA requirementmock_account_response = {"id": "act_701351919139047",- "name": "Test European Business Account",+ "name": "Test European Account","account_status": 1,"business_country_code": "DE", # Germany - DSA compliant"business_city": "Berlin",@@ -38,7 +38,12 @@ class TestDSAIntegration:# Get account info and verify DSA detectionresult = await get_account_info(account_id="act_701351919139047")- result_data = json.loads(result)++ # Handle new return format (dictionary instead of JSON string)+ if isinstance(result, dict):+ result_data = result+ else:+ result_data = json.loads(result)# Verify DSA requirement is detectedassert result_data["business_country_code"] == "DE"@@ -151,43 +156,53 @@ class TestDSAIntegration:async def test_dsa_beneficiary_regional_compliance_integration(self):"""Test DSA beneficiary compliance across different regions"""- # Test European account (DSA required)- european_account_response = {+ # Test 1: European account (DSA required)+ mock_de_account_response = {"id": "act_de",- "name": "German Business Account",+ "name": "German Account","business_country_code": "DE",- "account_status": 1+ "currency": "EUR"}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 = european_account_response+ mock_api.return_value = mock_de_account_responseresult = await get_account_info(account_id="act_de")- result_data = json.loads(result)- # Verify European account requires DSA+ # Handle new return format (dictionary instead of JSON string)+ if isinstance(result, dict):+ result_data = result+ else:+ result_data = json.loads(result)++ # Verify DSA requirement for German accountassert result_data["business_country_code"] == "DE"assert result_data["dsa_required"] == True- # Test US account (DSA not required)- us_account_response = {+ # Test 2: US account (DSA not required)+ mock_us_account_response = {"id": "act_us",- "name": "US Business Account",+ "name": "US Account","business_country_code": "US",- "account_status": 1+ "currency": "USD"}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 = us_account_response+ mock_api.return_value = mock_us_account_responseresult = await get_account_info(account_id="act_us")- result_data = json.loads(result)- # Verify US account doesn't require DSA+ # Handle new return format (dictionary instead of JSON string)+ if isinstance(result, dict):+ result_data = result+ else:+ result_data = json.loads(result)++ # Verify no DSA requirement for US accountassert result_data["business_country_code"] == "US"assert result_data["dsa_required"] == False@@ -377,4 +392,58 @@ class TestDSAIntegration:# Verify ad set details are retrieved correctlyassert result_data["id"] == "120229746624860183"- assert "dsa_beneficiary" not in result_data # Should not be present for US accounts\ No newline at end of file+ assert "dsa_beneficiary" not in result_data # Should not be present for US accounts++ @pytest.mark.asyncio+ async def test_account_info_requires_account_id(self):+ """Test that get_account_info requires an account_id parameter"""++ with patch('meta_ads_mcp.core.api.get_current_access_token', new_callable=AsyncMock) as mock_auth:+ mock_auth.return_value = "test_access_token"++ # Test without account_id parameter+ result = await get_account_info()++ # Handle new return format (dictionary instead of JSON string)+ if isinstance(result, dict):+ result_data = result+ else:+ result_data = json.loads(result)++ # Verify error message for missing account_id+ 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"]+ assert "example" in result_data["error"]++ @pytest.mark.asyncio+ 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_accessible_accounts = {+ "data": [+ {"id": "act_123", "name": "Test Account 1"},+ {"id": "act_456", "name": "Test Account 2"}+ ]+ }++ 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++ result = await get_account_info(account_id="act_inaccessible")++ # Handle new return format (dictionary instead of JSON string)+ if isinstance(result, dict):+ result_data = result+ else:+ result_data = json.loads(result)++ # Verify helpful error message for inaccessible account+ 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 len(result_data["error"]["accessible_accounts"]) == 2\ No newline at end of file