Skip to main content
Glama

get_campaigns

Retrieve and filter Meta Ads campaigns by status or objective to monitor and manage advertising performance.

Instructions

Get campaigns for a Meta Ads account with optional filtering.

Note: By default, the Meta API returns a subset of available fields. 
Other fields like 'effective_status', 'special_ad_categories', 
'lifetime_budget', 'spend_cap', 'budget_remaining', 'promoted_object', 
'source_campaign_id', etc., might be available but require specifying them
in the API call (currently not exposed by this tool's parameters).

Args:
    account_id: Meta Ads account ID (format: act_XXXXXXXXX)
    access_token: Meta API access token (optional - will use cached token if not provided)
    limit: Maximum number of campaigns to return (default: 10)
    status_filter: Filter by effective status (e.g., 'ACTIVE', 'PAUSED', 'ARCHIVED').
                   Maps to the 'effective_status' API parameter, which expects an array
                   (this function handles the required JSON formatting). Leave empty for all statuses.
    objective_filter: Filter by campaign objective(s). Can be a single objective string or a list of objectives.
                     Valid objectives: 'OUTCOME_AWARENESS', 'OUTCOME_TRAFFIC', 'OUTCOME_ENGAGEMENT',
                     'OUTCOME_LEADS', 'OUTCOME_SALES', 'OUTCOME_APP_PROMOTION'.
                     Examples: 'OUTCOME_LEADS' or ['OUTCOME_LEADS', 'OUTCOME_SALES'].
                     Leave empty for all objectives.
    after: Pagination cursor to get the next set of results

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
account_idYes
access_tokenNo
limitNo
status_filterNo
objective_filterNo
afterNo

Implementation Reference

  • Primary MCP tool handler for fetching Meta Ads campaigns with filtering by status, objective, limit, and pagination. Uses Meta Ads API via make_api_request. Decorated with @mcp_server.tool() for automatic registration and @meta_api_tool for API handling.
    @mcp_server.tool()
    @meta_api_tool
    async def get_campaigns(
        account_id: str, 
        access_token: Optional[str] = None, 
        limit: int = 10, 
        status_filter: str = "", 
        objective_filter: Union[str, List[str]] = "", 
        after: str = ""
    ) -> str:
        """
        Get campaigns for a Meta Ads account with optional filtering.
        
        Note: By default, the Meta API returns a subset of available fields. 
        Other fields like 'effective_status', 'special_ad_categories', 
        'lifetime_budget', 'spend_cap', 'budget_remaining', 'promoted_object', 
        'source_campaign_id', etc., might be available but require specifying them
        in the API call (currently not exposed by this tool's parameters).
        
        Args:
            account_id: Meta Ads account ID (format: act_XXXXXXXXX)
            access_token: Meta API access token (optional - will use cached token if not provided)
            limit: Maximum number of campaigns to return (default: 10)
            status_filter: Filter by effective status (e.g., 'ACTIVE', 'PAUSED', 'ARCHIVED').
                           Maps to the 'effective_status' API parameter, which expects an array
                           (this function handles the required JSON formatting). Leave empty for all statuses.
            objective_filter: Filter by campaign objective(s). Can be a single objective string or a list of objectives.
                             Valid objectives: 'OUTCOME_AWARENESS', 'OUTCOME_TRAFFIC', 'OUTCOME_ENGAGEMENT',
                             'OUTCOME_LEADS', 'OUTCOME_SALES', 'OUTCOME_APP_PROMOTION'.
                             Examples: 'OUTCOME_LEADS' or ['OUTCOME_LEADS', 'OUTCOME_SALES'].
                             Leave empty for all objectives.
            after: Pagination cursor to get the next set of results
        """
        # Require explicit account_id
        if not account_id:
            return json.dumps({"error": "No account ID specified"}, indent=2)
        
        endpoint = f"{account_id}/campaigns"
        params = {
            "fields": "id,name,objective,status,daily_budget,lifetime_budget,buying_type,start_time,stop_time,created_time,updated_time,bid_strategy",
            "limit": limit
        }
        
        # Build filtering array for complex filtering
        filters = []
        
        if status_filter:
            # API expects an array, encode it as a JSON string
            params["effective_status"] = json.dumps([status_filter])
        
        # Handle objective filtering - supports both single string and list of objectives
        if objective_filter:
            # Convert single string to list for consistent handling
            objectives = [objective_filter] if isinstance(objective_filter, str) else objective_filter
            
            # Filter out empty strings
            objectives = [obj for obj in objectives if obj]
            
            if objectives:
                filters.append({
                    "field": "objective",
                    "operator": "IN",
                    "value": objectives
                })
        
        # Add filtering parameter if we have filters
        if filters:
            params["filtering"] = json.dumps(filters)
        
        if after:
            params["after"] = after
        
        data = await make_api_request(endpoint, access_token, params)
        
        return json.dumps(data, indent=2)
  • Private helper method in MetaAdsDataManager class used by OpenAI Deep Research tools (search/fetch) to retrieve campaigns for a specific ad account. Fetches basic campaign fields without advanced filtering.
    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 []
  • Import statement that loads the get_campaigns function (triggering its @mcp_server.tool() decorator for MCP tool registration) and includes it in __all__ for export.
    from .campaigns import get_campaigns, get_campaign_details, create_campaign
    from .adsets import get_adsets, get_adset_details, update_adset
    from .ads import get_ads, get_ad_details, get_ad_creatives, get_ad_image, update_ad
    from .insights import get_insights
    from . import authentication  # Import module to register conditional auth tools
    from .server import login_cli, main
    from .auth import login
    from . import ads_library  # Import module to register conditional tools
    from .budget_schedules import create_budget_schedule
    from .targeting import search_interests, get_interest_suggestions, estimate_audience_size, search_behaviors, search_demographics, search_geo_locations
    from . import reports  # Import module to register conditional tools
    from . import duplication  # Import module to register conditional duplication tools
    from .openai_deep_research import search, fetch  # OpenAI MCP Deep Research tools
    
    __all__ = [
        'mcp_server',
        'get_ad_accounts',
        'get_account_info',
        'get_campaigns',

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/pipeboard-co/meta-ads-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server