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(auth): distinguish policy-blocked errors from token expiry (1.0.113) (#134)
Yves Junqueirae4f872bbba49
diff --git a/meta_ads_mcp/__init__.py b/meta_ads_mcp/__init__.pyindex 62c2fe3..bcbae37 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.112"+__version__ = "1.0.113"__all__ = ['get_ad_accounts',diff --git a/meta_ads_mcp/core/api.py b/meta_ads_mcp/core/api.pyindex 240dd0a..f6bbe43 100644--- a/meta_ads_mcp/core/api.py+++ b/meta_ads_mcp/core/api.py@@ -71,22 +71,58 @@ logger.info(f"Graph API Version: {META_GRAPH_API_VERSION}")logger.info(f"META_APP_ID env var present: {'Yes' if os.environ.get('META_APP_ID') else 'No'}")logger.info(f"META_APP_SECRET env var present (appsecret_proof will be {'enabled' if os.environ.get('META_APP_SECRET') else 'disabled'})")+def _is_account_disabled_error(error_code: Any, error_subcode: Any) -> bool:+ """Return True when a Graph error indicates the ad account / action is+ blocked by Meta policy rather than the token being invalid.++ Currently covers:+ - code 368: "The action attempted has been deemed abusive or is otherwise+ disallowed." Token is still valid; the specific action was rejected.+ - code 190 + subcode 459: user has been checkpointed by Facebook+ security. Token is not expired; the user must clear the checkpoint on+ Facebook before further calls succeed. Telling them to reconnect on+ Pipeboard does not unblock them.++ Other code 190 subcodes (458, 460, 463, 464, 467) are genuine session /+ credential errors — keep the existing invalidate-token behavior for those.+ """+ if error_code == 368:+ return True+ if error_code == 190 and error_subcode == 459:+ return True+ return False++class GraphAPIError(Exception):"""Exception raised for errors from the Graph API."""def __init__(self, error_data: Dict[str, Any]):self.error_data = error_dataself.message = error_data.get('message', 'Unknown Graph API error')super().__init__(self.message)-+# Log error detailslogger.error(f"Graph API Error: {self.message}")logger.debug(f"Error details: {error_data}")-++ code = error_data.get("code")+ subcode = error_data.get("error_subcode")+# Check if this is an auth error (code 4 is rate limiting, NOT auth)- if "code" in error_data and error_data["code"] in [190, 102]:- logger.warning(f"Auth error detected (code: {error_data['code']}). Invalidating token.")- auth_manager.invalidate_token()- elif "code" in error_data and error_data["code"] == 4:+ if code in [190, 102]:+ if _is_account_disabled_error(code, subcode):+ logger.warning(+ f"Account/action policy block (code={code}, subcode={subcode}). "+ f"Token is still valid — NOT invalidating."+ )+ else:+ logger.warning(f"Auth error detected (code: {code}). Invalidating token.")+ auth_manager.invalidate_token()+ elif code == 368:+ logger.warning(+ f"Action disallowed (code=368, subcode={subcode}). "+ f"Token is still valid — NOT invalidating."+ )+ elif code == 4:logger.warning(f"Rate limit error detected (code: 4, subcode: {error_data.get('error_subcode', 'N/A')}). Token is still valid — NOT invalidating.")@@ -258,17 +294,31 @@ async def make_api_request(# Check for rate limit errors vs authentication errors.# Code 4 is a rate limit (NOT auth) — do NOT invalidate token.+ error_code = None+ error_subcode = None+ is_account_disabled = Falseif "error" in error_info:error_obj = error_info.get("error", {})- error_code = error_obj.get("code") if isinstance(error_obj, dict) else None+ if isinstance(error_obj, dict):+ error_code = error_obj.get("code")+ error_subcode = error_obj.get("error_subcode")if error_code == 4:# Application-level rate limit — token is still validlogger.warning(- f"Facebook API rate limit (code=4, subcode={error_obj.get('error_subcode', 'N/A')}, "+ f"Facebook API rate limit (code=4, subcode={error_subcode}, "f"msg={error_obj.get('error_user_msg', error_obj.get('message', 'N/A'))}). "f"Token is still valid — NOT invalidating.")+ elif _is_account_disabled_error(error_code, error_subcode):+ # Policy-side block (account or action). Token is still+ # valid; surface a distinct flag so callers can branch+ # without treating this as a stale-token reconnect.+ is_account_disabled = True+ logger.warning(+ f"Account/action policy block (code={error_code}, subcode={error_subcode}). "+ f"Token is still valid — NOT invalidating."+ )elif error_code in [190, 102, 200, 10]:logger.warning(f"Detected Facebook API auth error: {error_code}")if error_code == 200 and "Provide valid app ID" in error_obj.get("message", ""):@@ -288,7 +338,7 @@ async def make_api_request(elif e.response.status_code in [401, 403]:logger.warning(f"Detected authentication error ({e.response.status_code})")auth_manager.invalidate_token()-+# Include full details for technical users. URLs are scrubbed of# access_token/appsecret_proof — see GHSA-9gw6-46qc-99vr.full_response = {@@ -299,15 +349,20 @@ async def make_api_request("request_method": e.request.method,"request_url": _redact_url(str(e.request.url))}-+# Return a properly structured error object- return {- "error": {- "message": f"HTTP Error: {e.response.status_code}",- "details": error_info,- "full_response": full_response- }+ error_payload: Dict[str, Any] = {+ "message": f"HTTP Error: {e.response.status_code}",+ "details": error_info,+ "full_response": full_response,}+ if is_account_disabled:+ error_payload["is_account_disabled"] = True+ if error_code is not None:+ error_payload["error_code"] = error_code+ if error_subcode is not None:+ error_payload["error_subcode"] = error_subcode+ return {"error": error_payload}except Exception as e:logger.error(f"Request Error: {str(e)}")diff --git a/pyproject.toml b/pyproject.tomlindex 2d033cc..fc145dc 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -4,7 +4,7 @@ build-backend = "hatchling.build"[project]name = "meta-ads-mcp"-version = "1.0.112"+version = "1.0.113"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 960d0ef..bf95fd5 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.112",+ "version": "1.0.113","remotes": [{"type": "streamable-http",diff --git a/tests/test_account_disabled_error.py b/tests/test_account_disabled_error.pynew file mode 100644index 0000000..5b6f70b--- /dev/null+++ b/tests/test_account_disabled_error.py@@ -0,0 +1,219 @@+"""Tests for distinguishing policy-blocked errors from token-expiry errors.++Meta returns code 368 ("action disallowed") and code 190 / subcode 459+("user checkpointed") for cases where the access token is still valid but+the requested action / account is restricted. The library must NOT+invalidate the token in those cases and MUST surface a distinct+is_account_disabled flag so callers can branch on it.++Other code 190 subcodes (458, 460, 463, 464, 467) are genuine session+errors and keep the existing invalidate-token + reauth path.+"""++import httpx+import pytest+from unittest.mock import AsyncMock, MagicMock, patch++from meta_ads_mcp.core import api as api_module+from meta_ads_mcp.core.api import (+ GraphAPIError,+ _is_account_disabled_error,+ make_api_request,+)+++class TestIsAccountDisabledError:+ """Pure helper — covers the code/subcode classification."""++ def test_code_368_is_account_disabled(self):+ assert _is_account_disabled_error(368, None) is True+ assert _is_account_disabled_error(368, 1404082) is True++ def test_code_190_subcode_459_is_account_disabled(self):+ assert _is_account_disabled_error(190, 459) is True++ @pytest.mark.parametrize("subcode", [458, 460, 463, 464, 467])+ def test_code_190_other_subcodes_are_not_account_disabled(self, subcode):+ # Genuine session errors — keep the reauth path+ assert _is_account_disabled_error(190, subcode) is False++ def test_code_190_no_subcode_is_not_account_disabled(self):+ assert _is_account_disabled_error(190, None) is False++ def test_unrelated_codes_are_not_account_disabled(self):+ assert _is_account_disabled_error(4, None) is False+ assert _is_account_disabled_error(102, None) is False+ assert _is_account_disabled_error(100, 33) is False+ assert _is_account_disabled_error(None, None) is False+++class TestGraphAPIError:+ """The exception type checks codes at __init__ time and decides whether+ to invalidate the token."""++ def test_code_368_does_not_invalidate_token(self):+ with patch.object(api_module.auth_manager, "invalidate_token") as mock_inv:+ GraphAPIError({+ "code": 368,+ "message": "The action attempted has been deemed abusive",+ })+ mock_inv.assert_not_called()++ def test_code_190_subcode_459_does_not_invalidate_token(self):+ with patch.object(api_module.auth_manager, "invalidate_token") as mock_inv:+ GraphAPIError({+ "code": 190,+ "error_subcode": 459,+ "message": "User has been checkpointed",+ })+ mock_inv.assert_not_called()++ def test_code_190_subcode_463_still_invalidates_token(self):+ with patch.object(api_module.auth_manager, "invalidate_token") as mock_inv:+ GraphAPIError({+ "code": 190,+ "error_subcode": 463,+ "message": "Session has expired",+ })+ mock_inv.assert_called_once()++ def test_code_190_no_subcode_still_invalidates_token(self):+ with patch.object(api_module.auth_manager, "invalidate_token") as mock_inv:+ GraphAPIError({+ "code": 190,+ "message": "Error validating access token",+ })+ mock_inv.assert_called_once()++ def test_code_4_does_not_invalidate_token(self):+ with patch.object(api_module.auth_manager, "invalidate_token") as mock_inv:+ GraphAPIError({+ "code": 4,+ "error_subcode": 1504022,+ "message": "Application request limit reached",+ })+ mock_inv.assert_not_called()+++def _build_http_error(status: int, body: dict) -> httpx.HTTPStatusError:+ request = httpx.Request("GET", "https://graph.facebook.com/v24.0/act_123/insights")+ response = httpx.Response(status, request=request, json=body)+ return httpx.HTTPStatusError("error", request=request, response=response)+++class TestMakeApiRequestHttpErrors:+ """End-to-end on the HTTP error handler: account-disabled errors flow+ through with the is_account_disabled flag, token errors trigger+ invalidate_token and DO NOT set the flag."""++ @pytest.mark.asyncio+ async def test_code_368_returns_is_account_disabled_flag(self):+ body = {+ "error": {+ "message": "The action attempted has been deemed abusive",+ "type": "OAuthException",+ "code": 368,+ "error_subcode": 1404082,+ "fbtrace_id": "abc",+ }+ }+ http_err = _build_http_error(400, body)++ client = MagicMock()+ client.__aenter__ = AsyncMock(return_value=client)+ client.__aexit__ = AsyncMock(return_value=False)+ client.get = AsyncMock(side_effect=http_err)++ with patch.object(api_module.auth_manager, "invalidate_token") as mock_inv, \+ patch.object(api_module, "httpx") as mock_httpx:+ mock_httpx.AsyncClient = MagicMock(return_value=client)+ mock_httpx.HTTPStatusError = httpx.HTTPStatusError+ result = await make_api_request("act_123/insights", "tok")++ assert isinstance(result, dict)+ assert "error" in result+ assert result["error"].get("is_account_disabled") is True+ assert result["error"].get("error_code") == 368+ assert result["error"].get("error_subcode") == 1404082+ # Original Meta error details preserved+ assert result["error"]["details"]["error"]["code"] == 368+ mock_inv.assert_not_called()++ @pytest.mark.asyncio+ async def test_code_190_subcode_459_returns_is_account_disabled_flag(self):+ body = {+ "error": {+ "message": "User has been checkpointed",+ "type": "OAuthException",+ "code": 190,+ "error_subcode": 459,+ }+ }+ http_err = _build_http_error(400, body)++ client = MagicMock()+ client.__aenter__ = AsyncMock(return_value=client)+ client.__aexit__ = AsyncMock(return_value=False)+ client.get = AsyncMock(side_effect=http_err)++ with patch.object(api_module.auth_manager, "invalidate_token") as mock_inv, \+ patch.object(api_module, "httpx") as mock_httpx:+ mock_httpx.AsyncClient = MagicMock(return_value=client)+ mock_httpx.HTTPStatusError = httpx.HTTPStatusError+ result = await make_api_request("act_123/insights", "tok")++ assert result["error"].get("is_account_disabled") is True+ assert result["error"].get("error_code") == 190+ assert result["error"].get("error_subcode") == 459+ mock_inv.assert_not_called()++ @pytest.mark.asyncio+ async def test_code_190_subcode_463_does_not_set_flag_and_invalidates(self):+ body = {+ "error": {+ "message": "Session has expired",+ "type": "OAuthException",+ "code": 190,+ "error_subcode": 463,+ }+ }+ http_err = _build_http_error(400, body)++ client = MagicMock()+ client.__aenter__ = AsyncMock(return_value=client)+ client.__aexit__ = AsyncMock(return_value=False)+ client.get = AsyncMock(side_effect=http_err)++ with patch.object(api_module.auth_manager, "invalidate_token") as mock_inv, \+ patch.object(api_module, "httpx") as mock_httpx:+ mock_httpx.AsyncClient = MagicMock(return_value=client)+ mock_httpx.HTTPStatusError = httpx.HTTPStatusError+ result = await make_api_request("act_123/insights", "tok")++ assert "is_account_disabled" not in result["error"]+ mock_inv.assert_called_once()++ @pytest.mark.asyncio+ async def test_code_190_no_subcode_does_not_set_flag_and_invalidates(self):+ body = {+ "error": {+ "message": "Error validating access token",+ "type": "OAuthException",+ "code": 190,+ }+ }+ http_err = _build_http_error(400, body)++ client = MagicMock()+ client.__aenter__ = AsyncMock(return_value=client)+ client.__aexit__ = AsyncMock(return_value=False)+ client.get = AsyncMock(side_effect=http_err)++ with patch.object(api_module.auth_manager, "invalidate_token") as mock_inv, \+ patch.object(api_module, "httpx") as mock_httpx:+ mock_httpx.AsyncClient = MagicMock(return_value=client)+ mock_httpx.HTTPStatusError = httpx.HTTPStatusError+ result = await make_api_request("act_123/insights", "tok")++ assert "is_account_disabled" not in result["error"]+ mock_inv.assert_called_once()