← Back to blog

July 31, 2026 · 18 min read

How to use the Meta Ads Library API for AI agents

Connect AI agents to the Meta Ads Library API for programmatic competitor ad research. Setup guide, MCP server options, query parameters, and coverage limits.

How to use the Meta Ads Library API for AI agents

The Meta Ad Library holds millions of ads from Facebook and Instagram. For performance marketers, that archive is a goldmine of competitive intelligence: who is running what, how often they refresh creative, and which formats they are betting on. But clicking through ads one by one in the web interface is not how you build a competitive research pipeline. You need programmatic access. That is where the Meta Ads Library API comes in, and that is where AI agents change the game.

This post covers what the API actually returns (not what you wish it returned), how to set up access, which MCP servers wrap it for agent use, and how to build an agent workflow that pulls competitive ad data at scale. No fluff. Just the mechanics.

What the Meta Ads Library API actually is

The Meta Ads Library API is a Graph API endpoint called ads_archive. It lets you query Meta's public ad archive programmatically and get results back as structured JSON. It is completely separate from the Marketing API, which manages your own campaigns. The Ad Library API is read-only and built for transparency, not ad operations.

The API is free. There is no paid tier. You do not need to submit your app for review. You do need to verify your identity with Meta (government ID and a selfie), create a developer app, and generate an access token. That verification is the only gate.

The critical thing to understand: the Ad Library is not a universal ad spy tool. It has a specific scope driven by transparency regulations. Ads delivered in the UK or European Union in the past year are archived regardless of category. Political and issue ads are archived globally for 7 years. A regular commercial ad running only in the United States and not touching Europe will not appear anywhere in the archive. This scope limitation shapes everything you build on top of it.

What data the API returns (and what it does not)

Every ad record includes a basic set of fields: the ad creative body text, headline and link description, the CTA caption, media type (image, video, meme), a snapshot URL that shows the ad as it appeared, the advertiser's Page name and numeric ID, delivery start and end dates in UTC, active or inactive status, and which platforms the ad ran on (Facebook, Instagram, Messenger, Audience Network).

For political ads and any ads delivered in the EU or UK, you get additional fields: spend range estimates in predefined buckets, impressions ranges, high-level demographic reach (age and gender percentages), and geographic breakdowns. EU ads also expose some targeting parameters: target age range, target gender, and target locations. None of this is exact. Spend comes as ranges like "$1K-5K" or "$100K-1M," broken into 8 buckets from under $100 to over $1M.

What you do not get is equally important. No click-through rates, no conversion data, no return on ad spend. No granular targeting details like interest categories or custom audiences. No user-level data of any kind. No direct image or video file downloads from the API response. The API gives you a snapshot URL that points to an archived preview page, not the media file itself. If you need to download creatives in bulk, you will need to script something that hits those snapshot URLs individually. That may violate Meta's terms.

A 2026 benchmark by AdManage found that the typical result set from a single page ID query returns 25 to 2,000 ads depending on the advertiser's size. Apple's Facebook Page, for example, returns 5,825 active ads in a single query against the library. Most mid-sized competitors return 30 to 200.

Historical data has limits. Non-political commercial ads stay in the archive for one year from their last impression. Political ads stay for 7 years. If you are researching a competitor's holiday campaign from two years ago and it was not political, that data is gone. This makes the API a snapshot of the recent past, not a permanent research database.

How to get access: identity verification is the only real gate

The setup process has three steps. None of them cost money. The one people trip on is identity verification.

Step 1: confirm your identity. Go to Facebook's identity confirmation page at facebook.com/ID. Upload a government-issued ID, take a selfie, and provide proof of residency if asked. This takes anywhere from a few hours to a couple of days. Once approved, your Facebook account is authorized to access the Ad Library API. This is a one-time process.

Step 2: create a Meta developer account and app. Sign up at developers.facebook.com and create a new app. Choose the simplest app type (a Consumer app with no specialized products). This gives you an App ID and a container for API usage.

Step 3: generate an access token. The easiest path is through the Graph API Explorer tool in the developer dashboard. Navigate to Tools, then Graph API Explorer, select your app, and generate a user token. For Ad Library queries, a basic user token with default public data access works. No special permissions like ads_read are required.

The token you get from Graph API Explorer is short-lived: about 1 to 2 hours. For production use, extend it to a long-lived token (up to 60 days) through the Access Token Tools in the developer portal. After 60 days, you will need to refresh or regenerate it. There is no permanent access token. Build token rotation into your agent's workflow from day one, or your queries will silently fail with OAuth errors.

Important: You do NOT need to submit your app for App Review to use the Ad Library API. Since you are accessing public archive data (not private user information or ad account data), the standard App Review process does not apply. Identity verification is the only hard requirement.

How to query the API: the parameters that matter

The API lives at:

https://graph.facebook.com/v24.0/ads_archive

Replace v24.0 with the latest Graph API version. As of mid-2026, Meta ships new versions a few times a year. Always use the latest one for new projects.

Every query needs two required parameters: access_token (your user token) and ad_reached_countries (an array of country codes or "ALL"). The country parameter is mandatory because the archive is segmented by region. If you set it to ["US"] and do not filter for political ads, you will get zero results because US-only commercial ads are not in the archive.

The parameters you will use most often:

search_terms accepts keywords or phrases. Multiple words without quotes are treated as an unordered AND query. Use search_type=KEYWORD_EXACT_PHRASE for exact match. Separate phrases with commas for OR logic.

search_page_ids takes an array of up to 10 numeric Facebook Page IDs. This is the most targeted filter. If you know your competitor's Page ID, you can pull all of their archived ads in one query. Find Page IDs using the Graph API or tools like findmyfbid.com.

ad_active_status can be ACTIVE, INACTIVE, or ALL. The default is ACTIVE. For competitive research, set it to ALL so you capture ads that have already stopped running. You want the full picture, not just what is live right now.

ad_type filters by category: POLITICAL_AND_ISSUE_ADS, HOUSING_ADS, EMPLOYMENT_ADS, FINANCIAL_PRODUCTS_AND_SERVICES_ADS, or ALL. Default is ALL, which is what you want for most competitive research.

ad_delivery_date_min and ad_delivery_date_max take YYYY-MM-DD format. Use these to slice data into weekly or monthly chunks. Pulling a full year in one query is usually impractical. Slice by month for cleaner data handling.

media_type filters by IMAGE, VIDEO, MEME, or ALL. Useful if you only want to analyze video creative strategy.

publisher_platforms narrows to FACEBOOK, INSTAGRAM, AUDIENCE_NETWORK, or MESSENGER. Use this to isolate a competitor's Instagram strategy from their Facebook strategy.

The default response limit is 25 ads per page. You can increase this to a maximum of 2,000 with the limit parameter. If there are more results, the response includes a paging.next URL for the next batch. Your agent needs to handle pagination: follow next links until exhausted, or use the after cursor from paging.cursors to loop programmatically.

Meta does not publish exact rate limits for the Ad Library API, but the limits are per-user per-app per hour. If you pull tens of thousands of ads at once, expect throttling. Queries that return very large datasets are more likely to hit timeouts than strict rate call limits. A page size of 500 to 1,000 is more reliable than pushing the 2,000 maximum.

MCP servers for the Meta Ads Library: four options compared

Wrapping the Meta Ads Library API inside an MCP server turns raw Graph API calls into tools your agent can invoke with natural language. Instead of crafting curl commands, you ask the agent to find a competitor's ads and it calls the right tool. Here are the four approaches available in mid-2026.

Option 1: Meta's official MCP server. Launched in April 2026, this is the first-party option. It exposes 29 tools with both read and write capabilities for Meta Ads. It is free during beta and connects directly through mcp.facebook.com/ads. If you only need Meta and you want an official source, this is the safest choice. But it is Meta-only. No Google, no TikTok, no LinkedIn.

Option 2: GoMarble open-source MCPs. Three separate servers on GitHub: Facebook Ads (26 read-only tools), Google Ads, and Google Analytics 4. All MIT-licensed and free. Setup requires Python 3.10+, a virtual environment, and manual token configuration per platform. GoMarble's Facebook Ads MCP has 318 GitHub stars and is the most popular open-source option. The limitation: read-only only. Your agent can analyze ads but cannot launch or modify campaigns.

Option 3: Smithery-based community MCPs. Several community MCP servers wrap the Ad Library via third-party scraping services like ScrapeCreators. Install is a single npx command: npx -y @smithery/cli@latest install @trypeggy/facebook-ads-library-mcp --client claude. These servers provide two main tools: get_meta_platform_id (returns Page ID from brand name) and get_meta_ads (returns ads for a page). They bypass the EU/UK coverage limitation by scraping the public web interface instead of using the official API. That broader coverage comes with a cost: they rely on a third-party service that could break or change pricing.

Option 4: Hyper unified marketing MCP. Hyper exposes its full marketing platform over MCP with 200+ integrations, 40+ built-in tools, and 100+ preset skills. Its Meta Ads Library scraper is built in. Install takes under a minute: npx skills add hyperfx-ai/marketing-skills followed by OAuth. Hyper can both read competitive ad data and launch campaigns across Meta, TikTok, Google, LinkedIn, Amazon, and Pinterest. For agencies managing multiple client accounts, it includes white-label dashboards and per-client reporting. It is a commercial product, not open-source. The key advantage: a single MCP connection covers competitive research, campaign management, and organic posting across platforms.

Which one you pick depends on scope. For a solo developer querying Meta ad data from Claude, GoMarble or the official Meta MCP works. For a team that needs the agent to both research competitors and act on those insights (launch campaigns, post organic content), Hyper covers the wider surface. The community Smithery servers fill a gap for broad ad discovery outside the EU, but they add a dependency on a scraping service you do not control.

Building an agent workflow around the Ad Library API

The raw API is half the picture. The agent workflow around it is where the value lives. Here is a pattern that works for production agent pipelines.

Layer 1: scheduled collection. Your agent runs on a cron schedule, not on demand. Set it to pull competitor ads weekly. Use ad_delivery_date_min and ad_delivery_date_max to slice the last 7 days. Combine search_page_ids for 5 to 10 competitor Page IDs in each query. Store the raw JSON responses in a database. This builds a historical record that goes beyond the API's one-year retention window.

Layer 2: deduplication. The Ad Library API does not guarantee unique results across queries. The same ad can appear in multiple responses if it ran across multiple countries or was returned by different filter combinations. Deduplicate on the ad Library ID before storing. Skip any ID already in your database.

Layer 3: enrichment. The raw API fields are thin. Enrich each ad record with your own metadata: classify the ad by messaging theme, estimate the advertiser's category, tag creative formats, and score freshness (how recently it appeared relative to the competitor's other ads). This turns raw JSON into something your agent can reason about.

Layer 4: analysis and alerting. Your agent compares the enriched data week over week. It detects when a competitor launches a new batch of ads, shifts messaging themes, changes their creative format mix, or spikes spend. It summarizes the changes and sends an alert. This is what turns ad monitoring from a manual research task into an automated intelligence pipeline.

Building this workflow requires an MCP server that gives agents structured access to ad data. Tools like adextract wrap multiple ad platform APIs into a single MCP surface, so your agent can query Meta Ads Library data alongside Google, TikTok, and LinkedIn ad intelligence without juggling separate API keys and token refresh cycles. If you are building a competitive intelligence agent, check out our adextract MCP server to see how it connects directly to AI workspaces.

The coverage gap: what happens when your competitor only runs US ads

The single biggest limitation of the official API is the coverage gap. If your competitor is a US-only D2C brand that does not run political ads and does not target Europe, their ads are invisible in the Ad Library. The API returns zero results no matter how you query. This is by design. The archive's coverage is shaped by transparency regulations, not marketing needs.

The workaround used by tools like SearchApi and Apify is to scrape the public Ad Library web UI directly. The web interface at facebook.com/ads/library shows ads for all regions, not just the EU and UK. By automating browser requests against the web UI with rotating IPs and session management, these services return ad data for competitors the official API cannot reach.

This approach is effective but fragile. Meta can change the web UI structure, add CAPTCHAs, or enforce anti-scraping measures at any time. A scraping pipeline needs constant maintenance. It also operates in a gray area of Meta's terms of service. The official API is within terms. Web scraping may not be.

For agents, the pragmatic path is to use the official API for what it covers (EU, UK, political ads) and layer on a scraping service for US-only competitors if the intelligence need justifies the maintenance cost. Some MCP servers like the community Smithery ones handle both through a single tool interface, abstracting the underlying data source from the agent.

Token management: the part that breaks agent pipelines

Access tokens are the most common failure point for agent pipelines built on the Ad Library API. The token you generate from Graph API Explorer lasts 1 to 2 hours. Even after extending it to a long-lived token, the maximum lifespan is about 60 days. After that, every API call fails with an OAuth error.

For a one-off research script, this is annoying. For an agent pipeline that is supposed to run weekly without human intervention, it is a dealbreaker. The pipeline silently produces empty results for weeks, and nobody notices until someone checks.

Three mitigations:

First, build token health checks into the pipeline. Before every query batch, make a lightweight API call that validates the token and returns its expiry. If the token is within 7 days of expiry, trigger a refresh alert.

Second, implement a refresh workflow. Meta supports token extension through the Graph API itself. Your agent can programmatically exchange a short-lived token for a long-lived one using the oauth/access_token endpoint, as long as the current token is still valid. Build this into a scheduled refresh job that runs every 30 days.

Third, use a managed MCP server that handles token rotation for you. Meta's official MCP, Hyper, and some community servers negotiate and refresh tokens through OAuth flows. You authenticate once and the platform manages the token lifecycle. This is the path of least resistance for production pipelines.

Alternatively, you can connect multiple ad intelligence sources through a single MCP surface. We covered the architecture behind this in our guide on how MCP servers connect AI agents to ad platforms. That post walks through token management patterns across Meta, Google, and TikTok in a unified agent pipeline.

What changed in 2025-2026: EU political ads ban and new API versions

Three changes from the last year matter for agents using this API.

First, the EU political ads shutdown. In October 2025, Meta stopped allowing new political, electoral, and social issue ads in the European Union entirely. This was a response to the EU's Transparency and Targeting of Political Advertising (TTPA) regulation. For the Ad Library API, this means no new EU political ads appear in queries after that date. Historical data stays. But if your agent was monitoring EU political ad trends, that pipeline is now frozen.

Second, Graph API versioning. Meta shipped v23.0 in May 2025 and v24.0 in early 2026. Most changes affect the Marketing API. The Ad Library endpoints are stable, but field names and ad_type categories have been refined. The CREDIT_ADS category was deprecated and merged into FINANCIAL_PRODUCTS_AND_SERVICES_ADS. Older versioned endpoints eventually stop working, so pin your queries to the latest version and test after each release.

Third, the MCP ecosystem matured. A year ago, connecting an AI agent to the Ad Library meant writing custom Graph API wrappers. Today, you install an MCP server in a single command and the agent has structured tools for ad discovery. The Meta Ads Library went from a developer-only API to something an agent can query with natural language. That shift changes who can use this data and how fast they can act on it.

If you are building an agent pipeline that spans multiple ad platforms, our post on building an MCP-powered competitive ad intelligence stack covers the full architecture: data collection, enrichment, and agent analysis across Meta, Google, TikTok, and LinkedIn.

Real use cases for agents connected to the Ad Library

Here are the workflows teams are running with agents connected to Meta Ads Library data in production.

Creative format benchmarking. An agent pulls all active ads from 5 competitors and categorizes them by format: video, static image, carousel, collection. It tracks the proportion of each format over time and alerts when a competitor shifts their creative mix. A team at Nanobits ran this against Indian beauty brands Wow Skin Science and Plum, finding that Wow allocated 84% of its ads to video while Plum ran only 24.5% video. That gap revealed Plum was underinvesting in video creative at a time when the category leader was all-in on it.

Ad volume and testing velocity monitoring. The agent counts how many unique ad variations a competitor has running at any time. A spike in ad count signals a new campaign launch or an aggressive testing push. If a competitor goes from 20 active ads to 80 in a single week, something changed. The agent flags it.

Messaging theme extraction. The agent reads ad body text across all of a competitor's ads, clusters the messaging into themes (price-focused, ingredient-focused, lifestyle, seasonal), and tracks how those themes shift over time. If a competitor that historically led with product features suddenly pivots to discount messaging across 60% of their ads, it signals a strategy change worth investigating.

Seasonal campaign pattern analysis. The agent builds a calendar of competitor campaign launches by analyzing ad delivery start dates over multiple years. It identifies when competitors typically start their holiday push, when they begin testing spring campaigns, and how far in advance of major shopping events they go live. This turns the Ad Library into a historical campaign calendar.

For a deeper look at how agents turn raw ad data into competitive intelligence, read our piece on how AI agents find your competitor's best performing ads. It covers the enrichment layers and analysis patterns that turn API responses into actionable insight.

Pitfalls to avoid when building agent pipelines on this API

Five mistakes that break agent pipelines on the Meta Ads Library API, based on production experience.

Assuming ALL means all. Setting ad_reached_countries=['ALL'] and ad_type=ALL does not return every ad on the platform. It only returns political and issue ads globally plus EU and UK ads. If you are searching for a US-only commercial advertiser, the response is empty even with ALL. The agent needs to understand this scope limitation and not treat an empty response as "no ads found." It might mean "no ads in the archive's coverage scope."

Not handling pagination. The default response limit is 25 ads. If a competitor has 200 active ads and you do not follow the paging.next URLs, you are analyzing 12.5% of their creative output. Always paginate until exhausted.

Treating spend ranges as exact numbers. The spend data comes as buckets like "$1K-5K." Averaging a bucket's midpoint and treating it as a point estimate is misleading. An ad in the $5K-50K bucket could be $5,001 or $49,999. Report ranges, not estimates.

Ignoring token expiry. The most common silent failure mode. Your pipeline runs for 60 days, then starts returning empty results because the token expired. Every OAuth error looks identical: an empty response. The agent cannot distinguish "no ads found" from "token expired" unless you build explicit token health checks.

Querying by ad Library ID. There is no direct lookup endpoint like ads_archive/<adID>. If your agent stores ad Library IDs and tries to fetch them later by ID, it will fail. The workaround is to search by the advertiser's Page ID and filter client-side. Design your database schema around the combination of page_id and ad delivery dates, not the ad Library ID alone.

Putting it together: a minimal agent pipeline in 4 steps

Here is the shortest path from zero to a working agent pipeline for Meta Ads Library intelligence.

Step 1: verify your identity with Meta and generate a long-lived access token. Extend the token to the maximum 60-day window. Store it in an environment variable or secrets manager.

Step 2: pick an MCP server. For read-only competitive analysis, start with the open-source GoMarble Facebook Ads MCP or Meta's official MCP. Install the server in your agent's MCP config and test a basic query against a known competitor Page ID.

Step 3: write a scheduled collection script. Run it weekly. Pull ads for 5 to 10 competitor Page IDs using date ranges for the last 7 days. Deduplicate on ad Library ID. Store the results in a database with a timestamp.

Step 4: build an analysis agent. On the same schedule, run an agent that compares this week's data against last week. It looks for: new ad launches, format shifts, messaging theme changes, and spend pattern anomalies. It produces a summary and pushes it to Slack, email, or a dashboard.

That is the core loop: collect, deduplicate, enrich, compare. The API gives you the raw material. The agent workflow turns it into competitive intelligence you can act on.

If you want to skip the infrastructure work and connect your agent directly to structured ad intelligence across Meta, Google, TikTok, and LinkedIn, adextract provides an MCP server that does the heavy lifting. The collection, deduplication, enrichment, and cross-platform normalization are handled server-side. Your agent queries structured data, not raw API responses.

Frequently asked questions

Is the Meta Ads Library API free?

Yes, completely free. There is no paid tier and no per-call charge. You need a verified Facebook account, a developer app, and an access token. Identity verification is the only gate.

Can I see all of my competitor's ads through the API?

No. The API only returns ads delivered in the UK or EU (past year) plus political and issue ads globally (past 7 years). A US-only commercial ad that never targeted Europe will not appear. This is the most common misunderstanding about the API's scope.

How do I connect an AI agent to the Meta Ads Library?

Use an MCP server. Options include Meta's official MCP server (free beta, 29 tools, read and write), GoMarble's open-source Facebook Ads MCP (read-only, 26 tools, MIT licensed), community Smithery-based servers that wrap scraping services, and Hyper's unified marketing MCP (commercial, 200+ integrations). Install one in your agent's MCP config and query with natural language.

How long does an access token last?

A default token from Graph API Explorer lasts 1 to 2 hours. After extending it through the Access Token Tools, the maximum lifespan is about 60 days. There is no permanent token. Build a refresh mechanism or use a managed MCP server that handles token rotation for you.

Can I download ad images and videos through the API?

Not directly. The API provides an ad_snapshot_url that points to an archived preview page showing the ad with images and videos. You can view the creative there, but the API response does not include the actual media files. Bulk downloading creatives requires scripting against the snapshot URLs, which may violate Meta's terms.