Skip to main content
Glama

search_ads_archive

Search the Facebook Ads Library archive by keywords, country, and ad type to retrieve ad details including spend, impressions, and creative content.

Instructions

    Search the Facebook Ads Library archive.

    Args:
        search_terms: The search query for ads.
        ad_reached_countries: List of country codes (e.g., ["US", "GB"]).
        access_token: Meta API access token (optional - will use cached token if not provided).
        ad_type: Type of ads to search for (e.g., POLITICAL_AND_ISSUE_ADS, HOUSING_ADS, ALL).
        limit: Maximum number of ads to return.
        fields: Comma-separated string of fields to retrieve for each ad.

    Example Usage via curl equivalent:
        curl -G \
        -d "search_terms='california'" \
        -d "ad_type=POLITICAL_AND_ISSUE_ADS" \
        -d "ad_reached_countries=['US']" \
        -d "fields=ad_snapshot_url,spend" \
        -d "access_token=<ACCESS_TOKEN>" \
        "https://graph.facebook.com/<API_VERSION>/ads_archive"
    

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
search_termsYes
ad_reached_countriesYes
access_tokenNo
ad_typeNoALL
limitNo
fieldsNoad_creation_time,ad_creative_body,ad_creative_link_caption,ad_creative_link_description,ad_creative_link_title,ad_delivery_start_time,ad_delivery_stop_time,ad_snapshot_url,currency,demographic_distribution,funding_entity,impressions,page_id,page_name,publisher_platform,region_distribution,spend

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The main handler function for the 'search_ads_archive' tool. It is an async function decorated with @mcp_server.tool() and @meta_api_tool. It accepts search_terms, ad_reached_countries, access_token, ad_type, limit, and fields as parameters, then constructs a request to the Meta Graph API 'ads_archive' endpoint via make_api_request.
    async def search_ads_archive(
        search_terms: str,
        ad_reached_countries: List[str],
        access_token: Optional[str] = None,
        ad_type: str = "ALL",
        limit: int = 25,  # Default limit, adjust as needed
        fields: str = "ad_creation_time,ad_creative_body,ad_creative_link_caption,ad_creative_link_description,ad_creative_link_title,ad_delivery_start_time,ad_delivery_stop_time,ad_snapshot_url,currency,demographic_distribution,funding_entity,impressions,page_id,page_name,publisher_platform,region_distribution,spend"
    ) -> str:
        """
        Search the Facebook Ads Library archive.
    
        Args:
            search_terms: The search query for ads.
            ad_reached_countries: List of country codes (e.g., ["US", "GB"]).
            access_token: Meta API access token (optional - will use cached token if not provided).
            ad_type: Type of ads to search for (e.g., POLITICAL_AND_ISSUE_ADS, HOUSING_ADS, ALL).
            limit: Maximum number of ads to return.
            fields: Comma-separated string of fields to retrieve for each ad.
    
        Example Usage via curl equivalent:
            curl -G \\
            -d "search_terms='california'" \\
            -d "ad_type=POLITICAL_AND_ISSUE_ADS" \\
            -d "ad_reached_countries=['US']" \\
            -d "fields=ad_snapshot_url,spend" \\
            -d "access_token=<ACCESS_TOKEN>" \\
            "https://graph.facebook.com/<API_VERSION>/ads_archive"
        """
        if not access_token:
            # Attempt to get token implicitly if not provided - meta_api_tool handles this
            pass
    
        if not search_terms:
            return json.dumps({"error": "search_terms parameter is required"}, indent=2)
    
        if not ad_reached_countries:
            return json.dumps({"error": "ad_reached_countries parameter is required"}, indent=2)
    
        endpoint = "ads_archive"
        params = {
            "search_terms": search_terms,
            "ad_type": ad_type,
            "ad_reached_countries": json.dumps(ad_reached_countries), # API expects a JSON array string
            "limit": limit,
            "fields": fields,
        }
    
        try:
            data = await make_api_request(endpoint, access_token, params, method="GET")
            return json.dumps(data, indent=2)
        except Exception as e:
            error_msg = str(e)
            # Consider logging the full error for debugging
            # print(f"Error calling Ads Library API: {error_msg}")
            return json.dumps({
                "error": "Failed to search ads archive",
                "details": error_msg,
                "params_sent": {k: v for k, v in params.items() if k != 'access_token'} # Avoid logging token
            }, indent=2) 
  • The function signature and docstring (lines 16-43) serve as the input schema and contract for this tool, defining required parameters (search_terms, ad_reached_countries) and optional parameters (access_token, ad_type, limit, fields) with their types and descriptions.
    async def search_ads_archive(
        search_terms: str,
        ad_reached_countries: List[str],
        access_token: Optional[str] = None,
        ad_type: str = "ALL",
        limit: int = 25,  # Default limit, adjust as needed
        fields: str = "ad_creation_time,ad_creative_body,ad_creative_link_caption,ad_creative_link_description,ad_creative_link_title,ad_delivery_start_time,ad_delivery_stop_time,ad_snapshot_url,currency,demographic_distribution,funding_entity,impressions,page_id,page_name,publisher_platform,region_distribution,spend"
    ) -> str:
        """
        Search the Facebook Ads Library archive.
    
        Args:
            search_terms: The search query for ads.
            ad_reached_countries: List of country codes (e.g., ["US", "GB"]).
            access_token: Meta API access token (optional - will use cached token if not provided).
            ad_type: Type of ads to search for (e.g., POLITICAL_AND_ISSUE_ADS, HOUSING_ADS, ALL).
            limit: Maximum number of ads to return.
            fields: Comma-separated string of fields to retrieve for each ad.
    
        Example Usage via curl equivalent:
            curl -G \\
            -d "search_terms='california'" \\
            -d "ad_type=POLITICAL_AND_ISSUE_ADS" \\
            -d "ad_reached_countries=['US']" \\
            -d "fields=ad_snapshot_url,spend" \\
            -d "access_token=<ACCESS_TOKEN>" \\
            "https://graph.facebook.com/<API_VERSION>/ads_archive"
        """
        if not access_token:
            # Attempt to get token implicitly if not provided - meta_api_tool handles this
            pass
    
        if not search_terms:
            return json.dumps({"error": "search_terms parameter is required"}, indent=2)
    
        if not ad_reached_countries:
            return json.dumps({"error": "ad_reached_countries parameter is required"}, indent=2)
    
        endpoint = "ads_archive"
        params = {
            "search_terms": search_terms,
            "ad_type": ad_type,
            "ad_reached_countries": json.dumps(ad_reached_countries), # API expects a JSON array string
            "limit": limit,
            "fields": fields,
        }
    
        try:
            data = await make_api_request(endpoint, access_token, params, method="GET")
            return json.dumps(data, indent=2)
        except Exception as e:
            error_msg = str(e)
            # Consider logging the full error for debugging
            # print(f"Error calling Ads Library API: {error_msg}")
            return json.dumps({
                "error": "Failed to search ads archive",
                "details": error_msg,
                "params_sent": {k: v for k, v in params.items() if k != 'access_token'} # Avoid logging token
            }, indent=2) 
  • Registration of the tool on the MCP server. The @mcp_server.tool() decorator registers 'search_ads_archive' as an MCP tool. This registration is conditional on the environment variable META_ADS_DISABLE_ADS_LIBRARY not being set (line 10-13).
    if not DISABLE_ADS_LIBRARY:
        @mcp_server.tool()
  • The __init__.py imports ads_library module to trigger conditional registration of the search_ads_archive tool when the package is loaded.
    from . import ads_library  # Import module to register conditional tools
  • The server module also imports ads_library to ensure the tool is registered for HTTP transport.
    from . import accounts, campaigns, adsets, ads, insights, authentication
    from . import ads_library, budget_schedules, reports, openai_deep_research
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden. It mentions that access_token is optional and will use a cached token, which is a useful behavioral detail. However, it does not disclose rate limits, data freshness, or error handling.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is structured with bullet points and a curl example, but it is somewhat verbose. It could be more concise while retaining clarity.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

The presence of an output schema reduces the burden, but the description lacks details on pagination, result limits, and error responses. It is moderately complete for a search tool.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters5/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The description explicitly defines each parameter (e.g., 'search_terms: The search query for ads'), adding meaning beyond the schema's type and title. All 6 parameters are covered with clear descriptions.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states 'Search the Facebook Ads Library archive' and includes a curl example, making the purpose unambiguous. It distinguishes itself from sibling search tools by specifying the Facebook Ads Library.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides an example and lists parameters but offers no guidance on when to use this tool versus alternatives like 'search' or 'search_behaviors'. No when-not-to-use or context for selection.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

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