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.

Update authentication handling and dependencies in MCP

Yves Junqueira9a7f15631261
diff --git a/examples/example_http_client.py b/examples/example_http_client.py
index 26b46d2..b56294d 100644
--- a/examples/example_http_client.py
+++ b/examples/example_http_client.py
@@ -41,7 +41,7 @@ class MetaAdsMCPClient:
# Add authentication
if pipeboard_token:
- self.headers["X-PIPEBOARD-API-TOKEN"] = pipeboard_token
+ self.headers["Authentication"] = f"Bearer {pipeboard_token}"
print(f"✅ Using Pipeboard authentication")
elif meta_access_token:
self.headers["X-META-ACCESS-TOKEN"] = meta_access_token
diff --git a/meta_ads_mcp/core/http_auth_integration.py b/meta_ads_mcp/core/http_auth_integration.py
index 235639c..7e8ce86 100644
--- a/meta_ads_mcp/core/http_auth_integration.py
+++ b/meta_ads_mcp/core/http_auth_integration.py
@@ -9,6 +9,7 @@ import asyncio
import contextvars
from typing import Optional
from .utils import logger
+import json
# Use context variables instead of thread-local storage for better async support
_auth_token: contextvars.ContextVar[Optional[str]] = contextvars.ContextVar('auth_token', default=None)
@@ -24,7 +25,6 @@ class FastMCPAuthIntegration:
token: Access token to use for this request
"""
_auth_token.set(token)
- logger.debug(f"Set auth token in context: {token[:10]}...")
@staticmethod
def get_auth_token() -> Optional[str]:
@@ -39,7 +39,6 @@ class FastMCPAuthIntegration:
def clear_auth_token() -> None:
"""Clear authentication token for the current context"""
_auth_token.set(None)
- logger.debug("Cleared auth token from context")
@staticmethod
def extract_token_from_headers(headers: dict) -> Optional[str]:
@@ -51,18 +50,22 @@ class FastMCPAuthIntegration:
Returns:
Token if found, None otherwise
"""
- # Check for Pipeboard token (primary method)
- pipeboard_token = headers.get('X-PIPEBOARD-API-TOKEN') or headers.get('x-pipeboard-api-token')
- if pipeboard_token:
- logger.debug("Found Pipeboard token in headers")
- return pipeboard_token
+ # Check for Bearer token in Authentication header (primary method)
+ auth_header = headers.get('Authentication') or headers.get('authentication') or headers.get('authorization')
+ if auth_header and auth_header.lower().startswith('bearer '):
+ token = auth_header[7:].strip()
+ return token
# Check for direct Meta access token
meta_token = headers.get('X-META-ACCESS-TOKEN') or headers.get('x-meta-access-token')
if meta_token:
- logger.debug("Found Meta access token in headers")
return meta_token
+ # Check for Pipeboard token (legacy support, to be removed)
+ pipeboard_token = headers.get('X-PIPEBOARD-API-TOKEN') or headers.get('x-pipeboard-api-token')
+ if pipeboard_token:
+ return pipeboard_token
+
return None
def patch_fastmcp_server(mcp_server):
@@ -78,10 +81,10 @@ def patch_fastmcp_server(mcp_server):
def patched_run(transport="stdio", **kwargs):
"""Enhanced run method that sets up HTTP auth integration"""
- logger.info(f"Starting FastMCP with transport: {transport}")
+ logger.debug(f"Starting FastMCP with transport: {transport}")
if transport == "streamable-http":
- logger.info("Setting up HTTP authentication for streamable-http transport")
+ logger.debug("Setting up HTTP authentication for streamable-http transport")
setup_http_auth_patching()
# Call the original run method
@@ -109,7 +112,6 @@ def setup_http_auth_patching():
# Check for context-scoped token first
context_token = FastMCPAuthIntegration.get_auth_token()
if context_token:
- logger.debug("Using token from HTTP context")
return context_token
# Fall back to original implementation
@@ -125,6 +127,10 @@ def setup_http_auth_patching():
# Global instance for easy access
fastmcp_auth = FastMCPAuthIntegration()
+# Forward declaration of setup_starlette_middleware
+def setup_starlette_middleware(app):
+ pass
+
def setup_fastmcp_http_auth(mcp_server):
"""Setup HTTP authentication integration with FastMCP
@@ -133,69 +139,109 @@ def setup_fastmcp_http_auth(mcp_server):
"""
logger.info("Setting up FastMCP HTTP authentication integration")
- # Patch the server to handle HTTP authentication
- patch_fastmcp_server(mcp_server)
+ # 1. Patch FastMCP's run method to ensure our get_current_access_token patch is applied
+ # This remains crucial for the token to be picked up by tool calls.
+ patch_fastmcp_server(mcp_server) # This patches mcp_server.run
- # Try to patch the actual HTTP request handling if we can access it
- try:
- # This is experimental - try to hook into FastMCP's internal request processing
- setup_request_middleware(mcp_server)
- except Exception as e:
- logger.warning(f"Could not setup request middleware: {e}")
- logger.info("Using fallback authentication approach")
-
- logger.info("FastMCP HTTP authentication integration ready")
+ # 2. Patch the methods that provide the Starlette app instance
+ # This ensures our middleware is added to the app Uvicorn will actually serve.
-def setup_request_middleware(mcp_server):
- """Setup middleware to inject authentication into request context
-
- Args:
- mcp_server: FastMCP server instance
- """
- logger.info("Setting up request middleware for authentication injection")
-
- # This is where we'd hook into FastMCP's request processing
- # For now, we'll use the context variable approach with manual injection
+ app_provider_methods = []
+ if mcp_server.settings.json_response:
+ if hasattr(mcp_server, "streamable_http_app") and callable(mcp_server.streamable_http_app):
+ app_provider_methods.append("streamable_http_app")
+ else:
+ logger.warning("mcp_server.streamable_http_app not found or not callable, cannot patch for JSON responses.")
+ else: # SSE
+ if hasattr(mcp_server, "sse_app") and callable(mcp_server.sse_app):
+ app_provider_methods.append("sse_app")
+ else:
+ logger.warning("mcp_server.sse_app not found or not callable, cannot patch for SSE responses.")
+
+ if not app_provider_methods:
+ logger.error("No suitable app provider method (streamable_http_app or sse_app) found on mcp_server. Cannot add HTTP Auth middleware.")
+ # Fallback or error handling might be needed here if this is critical
- # Try to access FastMCP's internal app/server
- if hasattr(mcp_server, '_app') or hasattr(mcp_server, 'app'):
- app = getattr(mcp_server, '_app', None) or getattr(mcp_server, 'app', None)
+ for method_name in app_provider_methods:
+ original_app_provider_method = getattr(mcp_server, method_name)
- if app:
- logger.info("Found FastMCP app instance, attempting middleware injection")
- try:
- setup_starlette_middleware(app)
- except Exception as e:
- logger.warning(f"Starlette middleware setup failed: {e}")
-
- logger.info("Request middleware setup complete")
+ def new_patched_app_provider_method(*args, **kwargs):
+ # Call the original method to get/create the Starlette app
+ app = original_app_provider_method(*args, **kwargs)
+ if app:
+ logger.debug(f"Original {method_name} returned app: {type(app)}. Adding AuthInjectionMiddleware.")
+ # Now, add our middleware to this specific app instance
+ setup_starlette_middleware(app)
+ else:
+ logger.error(f"Original {method_name} returned None or a non-app object.")
+ return app
+
+ setattr(mcp_server, method_name, new_patched_app_provider_method)
+ logger.debug(f"Patched mcp_server.{method_name} to inject AuthInjectionMiddleware.")
+
+ # The old setup_request_middleware call is no longer needed here,
+ # as middleware addition is now handled by patching the app provider methods.
+ # try:
+ # setup_request_middleware(mcp_server)
+ # except Exception as e:
+ # logger.warning(f"Could not setup request middleware: {e}")
+
+ logger.info("FastMCP HTTP authentication integration setup attempt complete.")
+
+# Remove the old setup_request_middleware function as its logic is integrated above
+# def setup_request_middleware(mcp_server): ... (delete this function)
+
+# --- AuthInjectionMiddleware definition ---
+from starlette.middleware.base import BaseHTTPMiddleware
+from starlette.requests import Request
+import json # Ensure json is imported if not already at the top
+
+class AuthInjectionMiddleware(BaseHTTPMiddleware):
+ async def dispatch(self, request: Request, call_next):
+ logger.info(f"HTTP Auth Middleware: Processing request to {request.url.path}")
+ logger.info(f"HTTP Auth Middleware: Request headers: {list(request.headers.keys())}")
+ logger.info(f"HTTP Auth Middleware: Full headers: {json.dumps(dict(request.headers), indent=2)}")
+
+ token = FastMCPAuthIntegration.extract_token_from_headers(dict(request.headers))
+
+ if token:
+ logger.info(f"HTTP Auth Middleware: Extracted token: {token[:10]}...")
+ logger.debug("Injecting auth token into request context")
+ FastMCPAuthIntegration.set_auth_token(token)
+ else:
+ logger.warning("HTTP Auth Middleware: No authentication token found in headers")
+
+ try:
+ response = await call_next(request)
+ return response
+ finally:
+ if token: # Clear only if a token was set for this request
+ FastMCPAuthIntegration.clear_auth_token()
def setup_starlette_middleware(app):
- """Setup Starlette middleware for authentication
+ """Add AuthInjectionMiddleware to the Starlette app if not already present.
Args:
app: Starlette app instance
"""
- from starlette.middleware.base import BaseHTTPMiddleware
- from starlette.requests import Request
-
- class AuthInjectionMiddleware(BaseHTTPMiddleware):
- async def dispatch(self, request: Request, call_next):
- # Extract auth token from headers
- token = FastMCPAuthIntegration.extract_token_from_headers(dict(request.headers))
-
- if token:
- logger.debug("Injecting auth token into request context")
- FastMCPAuthIntegration.set_auth_token(token)
+ if not app:
+ logger.error("Cannot setup Starlette middleware, app is None.")
+ return
+
+ # Check if our specific middleware class is already in the stack
+ already_added = False
+ # Starlette's app.middleware is a list of Middleware objects.
+ # app.user_middleware contains middleware added by app.add_middleware()
+ for middleware_item in app.user_middleware:
+ if middleware_item.cls == AuthInjectionMiddleware:
+ already_added = True
+ break
- try:
- response = await call_next(request)
- return response
- finally:
- # Clean up after request
- if token:
- FastMCPAuthIntegration.clear_auth_token()
-
- # Add our middleware to the app
- app.add_middleware(AuthInjectionMiddleware)
- logger.info("Starlette auth middleware added successfully")
\ No newline at end of file
+ if not already_added:
+ try:
+ app.add_middleware(AuthInjectionMiddleware)
+ logger.info("AuthInjectionMiddleware added to Starlette app successfully.")
+ except Exception as e:
+ logger.error(f"Failed to add AuthInjectionMiddleware to Starlette app: {e}", exc_info=True)
+ else:
+ logger.debug("AuthInjectionMiddleware already present in Starlette app's middleware stack.")
\ No newline at end of file
diff --git a/meta_ads_mcp/core/server.py b/meta_ads_mcp/core/server.py
index 98b56af..1198a26 100644
--- a/meta_ads_mcp/core/server.py
+++ b/meta_ads_mcp/core/server.py
@@ -26,7 +26,7 @@ class StreamableHTTPHandler:
def __init__(self):
"""Initialize handler with no session storage - all auth per request"""
- logger.info("StreamableHTTPHandler initialized for stateless operation")
+ logger.debug("StreamableHTTPHandler initialized for stateless operation")
def handle_request(self, request_headers: Dict[str, str], request_body: Dict[str, Any]) -> Dict[str, Any]:
"""Handle individual request with authentication
@@ -38,16 +38,14 @@ class StreamableHTTPHandler:
Returns:
JSON response with auth status and any tool results
"""
- logger.info(f"Handling request with headers: {list(request_headers.keys())}")
-
try:
# Extract authentication configuration from headers
auth_config = self.get_auth_config_from_headers(request_headers)
- logger.info(f"Auth method detected: {auth_config['auth_method']}")
+ logger.debug(f"Auth method detected: {auth_config['auth_method']}")
# Handle based on auth method
- if auth_config['auth_method'] == 'pipeboard':
- return self.handle_pipeboard_request(auth_config, request_body)
+ if auth_config['auth_method'] == 'bearer':
+ return self.handle_bearer_request(auth_config, request_body)
elif auth_config['auth_method'] == 'custom_meta_app':
return self.handle_custom_app_request(auth_config, request_body)
else:
@@ -82,20 +80,21 @@ class StreamableHTTPHandler:
'meta_access_token': False, # ❌ Use proper auth flows instead
}
- # PRIMARY: Check for Pipeboard token (handles 90%+ of cases)
- pipeboard_token = request_headers.get('X-PIPEBOARD-API-TOKEN') or request_headers.get('x-pipeboard-api-token')
- if pipeboard_token:
- logger.info("Pipeboard authentication detected (primary path)")
+ # PRIMARY: Check for Bearer token in Authentication header (handles 90%+ of cases)
+ auth_header = request_headers.get('Authentication') or request_headers.get('authentication')
+ if auth_header and auth_header.lower().startswith('bearer '):
+ token = auth_header[7:].strip()
+ logger.debug("Bearer authentication detected (primary path)")
return {
- 'auth_method': 'pipeboard',
- 'pipeboard_api_token': pipeboard_token,
+ 'auth_method': 'bearer',
+ 'bearer_token': token,
'requires_oauth': False # Simple token-based auth
}
# FALLBACK: Custom Meta app (minority of users)
meta_app_id = request_headers.get('X-META-APP-ID') or request_headers.get('x-meta-app-id')
if meta_app_id:
- logger.info("Custom Meta app authentication detected (fallback path)")
+ logger.debug("Custom Meta app authentication detected (fallback path)")
return {
'auth_method': 'custom_meta_app',
'meta_app_id': meta_app_id,
@@ -109,8 +108,8 @@ class StreamableHTTPHandler:
'requires_oauth': False
}
- def handle_pipeboard_request(self, auth_config: Dict[str, Any], request_body: Dict[str, Any]) -> Dict[str, Any]:
- """Handle request with Pipeboard token (primary path)
+ def handle_bearer_request(self, auth_config: Dict[str, Any], request_body: Dict[str, Any]) -> Dict[str, Any]:
+ """Handle request with Bearer token (primary path)
Args:
auth_config: Authentication configuration from headers
@@ -119,8 +118,8 @@ class StreamableHTTPHandler:
Returns:
JSON response ready for tool execution
"""
- logger.info("Processing Pipeboard authenticated request")
- token = auth_config['pipeboard_api_token']
+ logger.debug("Processing Bearer authenticated request")
+ token = auth_config['bearer_token']
# Token is ready to use immediately for API calls
# TODO: In next phases, this will execute the actual tool call
@@ -128,9 +127,9 @@ class StreamableHTTPHandler:
'jsonrpc': '2.0',
'result': {
'status': 'ready',
- 'auth_method': 'pipeboard',
- 'message': 'Authentication successful with Pipeboard token',
- 'token_source': 'pipeboard_header'
+ 'auth_method': 'bearer',
+ 'message': 'Authentication successful with Bearer token',
+ 'token_source': 'bearer_header'
},
'id': request_body.get('id')
}
@@ -145,7 +144,7 @@ class StreamableHTTPHandler:
Returns:
JSON response indicating OAuth flow is required
"""
- logger.info("Processing custom Meta app request (OAuth required)")
+ logger.debug("Processing custom Meta app request (OAuth required)")
# This may require OAuth flow initiation
# Each request is independent - no session state
@@ -179,7 +178,7 @@ class StreamableHTTPHandler:
'message': 'Authentication required',
'data': {
'supported_methods': [
- 'X-PIPEBOARD-API-TOKEN: Pipeboard token (recommended)',
+ 'Authentication: Bearer <token> (recommended)',
'X-META-APP-ID: Custom Meta app OAuth (advanced users)'
],
'documentation': 'https://github.com/pipeboard-co/meta-ads-mcp'
@@ -204,8 +203,8 @@ def main():
"""Main entry point for the package"""
# Log startup information
logger.info("Meta Ads MCP server starting")
- logger.info(f"Python version: {sys.version}")
- logger.info(f"Args: {sys.argv}")
+ logger.debug(f"Python version: {sys.version}")
+ logger.debug(f"Args: {sys.argv}")
# Initialize argument parser
parser = argparse.ArgumentParser(
@@ -228,8 +227,8 @@ def main():
help="Use SSE response format instead of JSON (default: JSON, only used with --transport streamable-http)")
args = parser.parse_args()
- logger.info(f"Parsed args: login={args.login}, app_id={args.app_id}, version={args.version}")
- logger.info(f"Transport args: transport={args.transport}, port={args.port}, host={args.host}, sse_response={args.sse_response}")
+ logger.debug(f"Parsed args: login={args.login}, app_id={args.app_id}, version={args.version}")
+ logger.debug(f"Transport args: transport={args.transport}, port={args.port}, host={args.host}, sse_response={args.sse_response}")
# Validate CLI argument combinations
if args.transport == "stdio" and (args.port != 8080 or args.host != "localhost" or args.sse_response):
@@ -242,7 +241,7 @@ def main():
# Check environment variable first (early init)
env_app_id = os.environ.get("META_APP_ID")
if env_app_id:
- logger.info(f"Found META_APP_ID in environment: {env_app_id}")
+ logger.debug(f"Found META_APP_ID in environment: {env_app_id}")
else:
logger.warning("META_APP_ID not found in environment variables")
@@ -319,13 +318,13 @@ def main():
logger.info(f"Starting MCP server with Streamable HTTP transport on {args.host}:{args.port}")
logger.info("Mode: Stateless (no session persistence)")
logger.info(f"Response format: {'SSE' if args.sse_response else 'JSON'}")
- logger.info("Primary auth method: Pipeboard API Token (recommended)")
+ logger.info("Primary auth method: Bearer Token (recommended)")
logger.info("Fallback auth method: Custom Meta App OAuth (complex setup)")
print(f"Starting Meta Ads MCP server with Streamable HTTP transport")
print(f"Server will listen on {args.host}:{args.port}")
print(f"Response format: {'SSE' if args.sse_response else 'JSON'}")
- print("Primary authentication: Pipeboard API Token (via X-PIPEBOARD-API-TOKEN header)")
+ print("Primary authentication: Bearer Token (via Authentication: Bearer <token> header)")
print("Fallback authentication: Custom Meta App OAuth (via X-META-APP-ID header)")
# Configure the existing server with streamable HTTP settings
@@ -348,7 +347,6 @@ def main():
setup_fastmcp_http_auth(mcp_server)
logger.info("FastMCP HTTP authentication integration setup successful")
print("✅ FastMCP HTTP authentication integration enabled")
- print(" - Pipeboard tokens via X-PIPEBOARD-API-TOKEN header")
print(" - Direct Meta tokens via X-META-ACCESS-TOKEN header")
print(" - Context-aware authentication for all tools")
diff --git a/tests/conftest.py b/tests/conftest.py
index 0c64500..fe51ce9 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -50,7 +50,7 @@ def test_headers():
def pipeboard_auth_headers(test_headers):
"""Headers with Pipeboard authentication token"""
headers = test_headers.copy()
- headers["X-PIPEBOARD-API-TOKEN"] = "test_pipeboard_token_12345"
+ headers["Authentication"] = "Bearer test_pipeboard_token_12345"
return headers
diff --git a/tests/test_http_transport.py b/tests/test_http_transport.py
index 0355eba..9ba8df7 100644
--- a/tests/test_http_transport.py
+++ b/tests/test_http_transport.py
@@ -207,8 +207,8 @@ class HTTPTransportTester:
"headers": None
},
{
- "name": "Pipeboard Token (Primary Path)",
- "headers": {"X-PIPEBOARD-API-TOKEN": "test_pipeboard_token_12345"}
+ "name": "Bearer Token (Primary Path)",
+ "headers": {"Authentication": "Bearer test_pipeboard_token_12345"}
},
{
"name": "Custom Meta App ID (Fallback Path)",
@@ -217,7 +217,7 @@ class HTTPTransportTester:
{
"name": "Both Auth Methods",
"headers": {
- "X-PIPEBOARD-API-TOKEN": "test_pipeboard_token_12345",
+ "Authentication": "Bearer test_pipeboard_token_12345",
"X-META-APP-ID": "123456789012345"
}
}
diff --git a/uv.lock b/uv.lock
index 8da9e18..ec7f6d5 100644
--- a/uv.lock
+++ b/uv.lock
@@ -198,7 +198,7 @@ wheels = [
[[package]]
name = "mcp"
-version = "1.6.0"
+version = "1.9.2"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "anyio" },
@@ -206,13 +206,14 @@ dependencies = [
{ name = "httpx-sse" },
{ name = "pydantic" },
{ name = "pydantic-settings" },
+ { name = "python-multipart" },
{ name = "sse-starlette" },
{ name = "starlette" },
- { name = "uvicorn" },
+ { name = "uvicorn", marker = "sys_platform != 'emscripten'" },
]
-sdist = { url = "https://files.pythonhosted.org/packages/95/d2/f587cb965a56e992634bebc8611c5b579af912b74e04eb9164bd49527d21/mcp-1.6.0.tar.gz", hash = "sha256:d9324876de2c5637369f43161cd71eebfd803df5a95e46225cab8d280e366723", size = 200031 }
+sdist = { url = "https://files.pythonhosted.org/packages/ea/03/77c49cce3ace96e6787af624611b627b2828f0dca0f8df6f330a10eea51e/mcp-1.9.2.tar.gz", hash = "sha256:3c7651c053d635fd235990a12e84509fe32780cd359a5bbef352e20d4d963c05", size = 333066 }
wheels = [
- { url = "https://files.pythonhosted.org/packages/10/30/20a7f33b0b884a9d14dd3aa94ff1ac9da1479fe2ad66dd9e2736075d2506/mcp-1.6.0-py3-none-any.whl", hash = "sha256:7bd24c6ea042dbec44c754f100984d186620d8b841ec30f1b19eda9b93a634d0", size = 76077 },
+ { url = "https://files.pythonhosted.org/packages/5d/a6/8f5ee9da9f67c0fd8933f63d6105f02eabdac8a8c0926728368ffbb6744d/mcp-1.9.2-py3-none-any.whl", hash = "sha256:bc29f7fd67d157fef378f89a4210384f5fecf1168d0feb12d22929818723f978", size = 131083 },
]
[package.optional-dependencies]
@@ -247,7 +248,7 @@ dependencies = [
[package.metadata]
requires-dist = [
{ name = "httpx", specifier = ">=0.26.0" },
- { name = "mcp", extras = ["cli"], specifier = ">=1.6.0" },
+ { name = "mcp", extras = ["cli"], specifier = ">=1.9.0" },
{ name = "pathlib", specifier = ">=1.0.1" },
{ name = "pillow", specifier = ">=10.0.0" },
{ name = "python-dateutil", specifier = ">=2.8.2" },
@@ -476,6 +477,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/1e/18/98a99ad95133c6a6e2005fe89faedf294a748bd5dc803008059409ac9b1e/python_dotenv-1.1.0-py3-none-any.whl", hash = "sha256:d7c01d9e2293916c18baf562d95698754b0dbbb5e74d457c45d4f6561fb9d55d", size = 20256 },
]
+[[package]]
+name = "python-multipart"
+version = "0.0.20"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/f3/87/f44d7c9f274c7ee665a29b885ec97089ec5dc034c7f3fafa03da9e39a09e/python_multipart-0.0.20.tar.gz", hash = "sha256:8dd0cab45b8e23064ae09147625994d090fa46f5b0d1e13af944c331a7fa9d13", size = 37158 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/45/58/38b5afbc1a800eeea951b9285d3912613f2603bdf897a4ab0f4bd7f405fc/python_multipart-0.0.20-py3-none-any.whl", hash = "sha256:8a62d3a8335e06589fe01f2a3e178cdcc632f3fbe0d492ad9ee0ec35aab1f104", size = 24546 },
+]
+
[[package]]
name = "requests"
version = "2.32.3"