adlibrary.com Logoadlibrary.com
Share
Competitive Research

Claude Code + AdLibrary API: Building Agentic Marketing Workflows That Actually Ship

The release of Claude Code Remote Contro introduces deep terminal integration and remote control capabilities, challenging existing AI editors like Cursor while opening new frontiers for programmatic ad research.

Claude Code agentic marketing starts where the chat window ends: the model reads files, calls APIs, interprets JSON, writes output, and loops — all from a single terminal session. Paired with the AdLibrary API, that loop becomes a competitor intelligence engine capable of running every night without anyone at the keyboard.

TL;DR: Claude Code orchestrates multi-step marketing research by calling the AdLibrary API to fetch competitor creatives, classify ad patterns, and output structured briefs — all in one unattended workflow. This post walks through the API surface, two worked examples, and the real constraints you need to plan around.

This guide is for practitioners who already use Claude and want to go beyond one-shot prompting. If you're still sending paragraphs of research into a chat box and manually summarizing the output, that's the gap we're closing here.

Why Agentic Beats Prompt-Once Workflows

A single-turn prompt is a snapshot. You paste in some ad copy, ask for patterns, read the output, and do something with it. The moment the window closes, the context evaporates. The next researcher starts from scratch.

An 10 agentic MCP recipes is a loop. Claude Code issues a bash command, reads the result, decides what to do next based on that result, issues another command, and so on — until it hits an exit condition or a human checkpoint. The state isn't in the chat window; it's in files, API responses, and structured output on disk.

For marketing this distinction is significant. Competitor ad research isn't a one-time act — brands rotate creative every two to four weeks, test new hooks, pivot messaging after earnings calls. If your research process requires a human to sit at a keyboard and paste URLs, it will happen monthly at best. An agentic loop tied to a schedule can run Sunday at 3 AM, pull fresh ad data from the unified ad search layer, and drop a brief in your team's Slack before anyone's had coffee.

The practical difference between a "copilot" tool (Claude in a chat box, Cursor for code) and an agent is simple: copilots wait for humans to submit the next message. Agents submit the next message themselves, based on what they just read. Claude Code agents for media buyers formalizes this into a repeatable ops pattern.

Another frequently underestimated advantage: agent output is structurally consistent. When you describe a task in prose and paste it in manually each time, the framing drifts. The agent reads the same instruction file every run, calls the same endpoints in the same order, and outputs JSON that downstream tools can parse reliably. That consistency is what makes the output useful rather than interesting.

From our experience running these workflows across dozens of brand categories on AdLibrary's corpus — over one billion indexed ads — the teams that get durable value from agentic setups treat the agent's output as a data pipeline, not a report. They pipe competitor ad metadata into a structured store, query it across weeks, and look for direction changes rather than reacting to individual creative variations.

The alternative is manual ad-creation inefficiency at a research level: someone spends three hours every Friday collecting ad screenshots, writing down what they noticed, and putting it in a deck nobody reads by Monday. The agentic approach replaces that loop with something that runs in twelve minutes and outputs a machine-readable file.

The AdLibrary API Surface: What You Can Actually Query

Before wiring Claude Code to anything, you need to know what the API actually returns. The AdLibrary API exposes four major endpoint categories that matter for agentic marketing work:

Authentication — API access uses bearer tokens scoped to your account tier. Pass the token in the Authorization header on every request. Tokens do not expire during a session but rotate on plan renewal. Store them in an environment variable, never hardcode.

GET /v1/ads/search
Authorization: Bearer $ADLIBRARY_API_KEY

Brand search — Query by advertiser name to pull all active (and recently inactive) ads for a given brand across platforms:

GET /v1/ads/search?brand=gymshark&platforms=meta,tiktok&status=active&limit=50

The response includes ad ID, creative URL, copy text, call-to-action type, first-seen and last-seen timestamps, and estimated impression tier. That last field — impression tier — is the fastest proxy for spend weight when exact spend data isn't available.

Platform search — Filter by platform independently of brand. Useful when you want to understand what's running on TikTok in a category without anchoring to specific advertisers:

GET /v1/ads/search?category=supplements&platform=tiktok&sort=impressions_desc&limit=100

Timeline endpoint — Pulls the ad history for a specific ad ID, showing when it ran, paused, and resumed. This is the core data source for the ad-timeline-analysis feature that surfaces creative fatigue signals. For agents, it answers: "Has this ad been running continuously for 90 days, or was it paused and relaunched?"

GET /v1/ads/{ad_id}/timeline

Landing-page metadata — Retrieves the destination URL, page title, and structured metadata for any ad's click destination. This is valuable for agents doing funnel audits — the creative is one half of a competitor's hypothesis; the landing page is the other:

GET /v1/ads/{ad_id}/landing-page

Full schema documentation lives at api-documentation-and-implementation-guide. For the use case of feeding this data into AI pipelines, see ad data for AI agents — it covers the data shape conventions and recommended polling intervals.

Rate limits vary by plan, but plan for 60 requests/minute on standard tiers. Agentic loops need exponential backoff logic — Claude Code can write that for you as part of the setup script if you ask explicitly.

Claude Code as Orchestrator: Sub-Agents, Slash Commands, and /schedule

Claude Code runs in your terminal. It can execute shell commands, read and write files, call APIs via curl or a Python script, and branch on the output of any of those operations. For marketing workflows, this means it can replace a n8n or Make automation for tasks that require reasoning at intermediate steps — not just routing data from A to B, but deciding what to do based on what it reads.

Sub-agents let you decompose complex tasks. Instead of one giant prompt that tries to do everything, you define a coordinator agent that delegates subtasks to specialist agents. In Anthropic's agent architecture documentation, this is described as multi-agent orchestration — the coordinator dispatches tasks to workers, collects their outputs, and synthesizes a final result.

For a competitor brief workflow:

  • Coordinator agent: read the brand list, call the AdLibrary search endpoint, distribute brand names to workers
  • Worker agents (one per brand): fetch ad data, summarize creative themes, flag any timeline anomalies
  • Synthesis agent: merge worker outputs, identify cross-brand patterns, format the final brief

Slash commands in Claude Code are reusable instruction files. You write /competitor-brief once as a .md file in your project's .claude/commands/ directory. Every subsequent run of that command loads the same instructions, your API key from the environment, and the current date automatically. This is what makes the workflow repeatable without copy-paste.

A minimal competitor-brief command file looks like:

markdown
# competitor-brief
Fetch the top 50 active ads for each brand in $BRAND_LIST.
For each brand, identify: primary hook type (testimonial/demo/offer),
average creative run length, and any ads in the top 10 by impressions
that have run >60 days (fatigue risk).
Output: /tmp/competitor-brief-{{date}}.json

/schedule is Claude Code's mechanism for recurring execution. You define when a command runs (cron-driven Meta Ads MCP agent syntax) and what context it receives. A Sunday 3 AM competitor brief becomes two lines of setup. The MCP specification that underlies Claude Code's tool use also allows external tool registration — meaning your Claude Code agent can call your own internal APIs alongside the AdLibrary API in a single session.

For deeper dives on the orchestration layer: agentic marketing workflows with Claude Code and building marketing workflows with Claude cover the scaffolding in more detail. For the comparison between Claude Code and editor-based tools: Claude Code vs Cursor for marketers.

Worked Example 1: Weekly Competitor Brief

Here is the actual sequence for a competitor brief that a DTC supplements brand runs every Sunday night, covering five direct competitors.

Step 0 — Find the angle first. Before writing any prompt, the team used AdLibrary's unified ad search to manually survey the competitive landscape across platforms. They identified which hook types (testimonial, clinical claim, demo) dominated the category and used that as the classification taxonomy the agent would apply. Starting an agentic workflow without a clear taxonomy produces volume, not insight.

Step 1 — Fetch brand ad data. The coordinator agent calls:

bash
curl -H "Authorization: Bearer $ADLIBRARY_API_KEY" \
  "https://api.adlibrary.com/v1/ads/search?brand=competitor_a&platform=meta&status=active&limit=50"

This runs for all five brands in sequence, with 1-second sleep between calls. Output is five JSON files: competitor_a_ads.json through competitor_e_ads.json.

Step 2 — Classify hook types. Claude Code reads each JSON file and classifies each ad into one of the four hook categories. The instruction is specific: "Read the ad copy in the text field. If the first sentence contains a first-person testimonial phrase, classify as TESTIMONIAL. If it contains a numeric claim with a unit (%, mg, days, lbs), classify as CLINICAL. If it describes product action without a claim, classify as DEMO. Otherwise classify as OFFER."

This specificity matters. Vague classification instructions produce garbage. The explicit rules produce a structured output the synthesis agent can aggregate.

Step 3 — Flag fatigue candidates. For any ad that has been active for more than 60 days, the agent calls the timeline endpoint to confirm continuous run (not pause-and-resume). Ads running continuously for 90+ days in a DTC category are almost always in decay — the algorithm is still serving them because the audience pool is large, but CTR will be trending down. Flagging these for competitors is useful because it identifies where they're likely about to rotate creative, which is your window to own a hook they're about to abandon.

Step 4 — Generate the brief. The synthesis agent reads all five classified JSON files and outputs a Markdown brief:

## Week of 2026-04-27
### Category hook distribution
- TESTIMONIAL: 62% (up from 48% four weeks ago)
- CLINICAL: 21%
- DEMO: 11%
- OFFER: 6%

### Fatigue candidates
- Competitor B: Ad #1847293 — running 94 days, testimonial format
- Competitor D: Ad #2019482 — running 88 days, clinical format

The whole workflow runs in under 15 minutes and writes the brief to /tmp/competitor-brief-2026-04-27.md, which the team's Slack bot picks up automatically. For more on automating this monitoring loop, see automate competitor ad monitoring. The Claude Code for competitor research automation post has the full CLAUDE.md template for this pattern.

Worked Example 2: Ad Creative Pattern Miner

The competitor brief tells you what's running. The pattern miner tells you what's working — or at least what's run long enough to suggest it isn't failing.

This workflow targets a different question: across the top 200 ads in a category by estimated impressions, what structural patterns appear most frequently in the ads that have run longest?

Input — A category search across platforms:

bash
curl -H "Authorization: Bearer $ADLIBRARY_API_KEY" \
  "https://api.adlibrary.com/v1/ads/search?category=skincare&sort=impressions_desc&limit=200"

Pattern extraction prompt — Claude Code reads the 200-ad JSON and runs this instruction:

For each ad, extract:
1. Opening word type: [question / number / imperative / brand-name / "If" / other]
2. Copy length bucket: [<50 words / 50-150 words / >150 words]
3. CTA type: from the cta_type field
4. Has social proof (reviews, star ratings, user count): [yes/no] from copy text
5. Has urgency signal ("today", "limited", "only X left"): [yes/no]

Output a JSON array. One object per ad.

With 200 structured objects, the next agent step aggregates: what opening word type appears in the top quartile by run-length? What copy length bucket correlates with ads that have been running over 45 days?

In one skincare category sweep on AdLibrary's corpus, the pattern that emerged was clear: ads opening with a number ("3 ingredients dermatologists actually use") ran 40% longer on average than ads opening with a question. That's a testable hypothesis for your own creative roadmap — not a guarantee, but a directional signal backed by observing thousands of real in-market decisions.

The AI ad enrichment layer that AdLibrary applies to indexed ads adds structured metadata (sentiment, visual category, hook type) that makes this pattern extraction faster — instead of prompting Claude to classify copy, you can query the pre-classified metadata directly. For large-scale creative analysis workflows, this pre-enrichment saves significant compute time.

For the code scaffold that underpins this workflow: Claude Code for ad creative analysis has the full Python wrapper and prompt library. The broader context of how AI reads and categorizes ad data lives in AI impact on ad creative research and testing.

Limits, Costs, and Observability

Agentic workflows fail in ways that are harder to see than a single broken API call. Here is what to plan for.

Rate limits and backoff. The AdLibrary API uses token-bucket rate limiting. At 60 req/min, a workflow fetching 200 ads across 5 brands plus timeline calls for each can hit the ceiling mid-run. Write your backoff logic before you need it:

python
import time, requests

def api_call_with_backoff(url, headers, max_retries=4):
    for attempt in range(max_retries):
        r = requests.get(url, headers=headers)
        if r.status_code == 429:
            wait = 2 ** attempt  # 1, 2, 4, 8 seconds
            time.sleep(wait)
            continue
        r.raise_for_status()
        return r.json()
    raise Exception("Rate limit retries exhausted")

Claude Code will write this for you if you describe the rate-limit behavior in your setup prompt.

Token costs. A workflow processing 200 ads with copy text runs through roughly 40,000–80,000 input tokens depending on ad copy length and how many intermediate reasoning steps you ask for. At Claude Sonnet pricing (see Anthropic pricing), that's a fraction of a dollar per run. The weekly amortization is low. The cost that adds up is debugging failed runs — a 200-ad classification that crashes at ad #140 because of a malformed JSON response wastes the prior tokens. Structure your workflows to checkpoint: write partial output to disk every 50 items, not just at the end.

Observability. Agents that run unattended need observable behavior. Minimum viable observability for a Claude Code marketing agent:

  • Structured logs to a file (not stdout only)
  • Exit codes: 0 = success, 1 = partial failure with details, 2 = total failure
  • A summary line at the end of every run: "Processed 200 ads: 198 classified, 2 skipped (malformed). Wrote output to /tmp/brief-2026-04-27.json"

Without these, a failed run looks like silence. Silence looks like success. You present a competitor brief to your team that's two weeks out of date and doesn't know it.

For the broader Claude Code for marketing ops pattern — which covers reports, data pipelines, and scheduled reviews — observability is treated as a first-class concern, not an afterthought. The automated ad performance insights post also addresses what happens when AI-generated analysis hits the edge of reliable pattern recognition.

When This Stack Overdoes It

This is the section most guides on agentic tooling skip. Not every research task benefits from orchestration.

Small brand sets. If you're monitoring two competitors who run fewer than twenty ads at a time, a fifteen-minute manual AdLibrary session is faster than setting up and maintaining an agent. The setup cost of a Claude Code workflow — environment variables, a CLAUDE.md, a command file, a schedule, error handling — is real. It pays off over months of repeated runs, not for a one-time audit.

Brand safety checkpoints. Agentic output is structurally consistent but not editorially supervised. An agent that classifies an ad as a "testimonial" doesn't know that the testimonial makes an unsubstantiated health claim. A human still needs to review any output that informs a creative brief before the brief reaches a designer. The agent's job is to reduce the time a human spends on data collection, not to eliminate the human from the output review step. Keeping a human in the loop before creative output reaches production isn't bureaucracy — it's the brand safety floor.

Prompt drift. Agentic workflows degrade quietly. The instruction file you wrote in January still runs, but the ad landscape changed: new hook types emerged, a competitor pivoted to video-only formats your taxonomy didn't anticipate, the API added a new field your code ignores. Schedule a quarterly review of your agent's classification logic against a fresh manual audit. The Claude Code prompts for marketing library has a taxonomy-refresh template that makes this a 30-minute task.

When manual research beats automation. Category entry, acquisition strategy, brand repositioning — these are moments when you want a human analyst reading ads with fresh eyes, forming qualitative impressions that no taxonomy captures. Use AdLibrary's unified search interface for these sessions. Save the agent for the ongoing monitoring cadence.

The teams that overdo it treat every workflow as an automation problem. The teams that get durable value draw the line clearly: automate the recurring, structured, high-volume data collection; keep humans for the interpretive decisions that require judgment the agent can't yet replicate. That line is where the stack pays for itself without creating a brittle infrastructure that breaks every platform update.

For a full picture of the use cases where this approach earns its complexity: ad data for AI agents documents the patterns that teams in this setup have found most productive. The AdLibrary API access feature page covers plan-level access and what each tier unlocks for programmatic use. See also: how to set up Meta Ads MCP.

Frequently asked questions

What is Claude Code agentic marketing?

Claude Code agentic marketing refers to using Claude Code's CLI-based agent capabilities to run multi-step marketing research and analysis workflows autonomously — fetching data from ad intelligence APIs, classifying creative patterns, and generating structured outputs without manual intervention at each step. It differs from single-turn prompting because the agent loops, reads intermediate outputs, and decides next actions based on what it finds. See agentic marketing workflows with Claude Code for the full workflow pattern.

Can I use the AdLibrary API without coding experience?

Not productively at this level of workflow complexity. The patterns in this post assume you can write or read basic Python or bash scripts and understand JSON responses. If you're earlier in that journey, Claude Code for marketers intro starts at a more accessible entry point, and the how to use Claude for marketing guide covers non-coding Claude workflows. API access details and tier requirements live on the API access feature page.

How often should an agentic competitor brief run?

Weekly is the practical floor for DTC and performance marketing categories where creative rotates frequently. Monthly is appropriate for B2B categories with longer creative cycles. Daily runs are rarely justified by the data density — ad creative doesn't meaningfully change within 24 hours at most spend levels. The automate competitor ad monitoring use case page documents the polling cadences that balance signal freshness against API cost.

What's the difference between Claude Code and Claude in a browser for this use case?

Claude in a browser is a single-turn or multi-turn conversation with no ability to execute code, call external APIs, or write output to disk. Claude Code runs in your terminal, can execute arbitrary commands, and maintains state across steps in a workflow. For marketing workflows that need to pull live data, classify 200+ ads, and write structured output files, only Claude Code (or an equivalent CLI agent) is appropriate. The Claude Code vs Cursor for marketers post covers the broader tool landscape.

How do I handle API rate limits in a Claude Code marketing agent?

Build exponential backoff into your API call wrapper before you run anything at scale. The AdLibrary API returns HTTP 429 on rate limit; your script should catch that, sleep for 2^n seconds (1, 2, 4, 8...), and retry up to four times before raising a failure. Ask Claude Code to write this wrapper for you in the setup session — describe the rate-limit behavior and it will generate the pattern. Checkpointing partial output to disk every 50 items also ensures that rate-limit interruptions don't require reprocessing from the start.

Querying publicly indexed ad data through an official API like AdLibrary's is legitimate — you're accessing data the platforms have made transparently available. The ad transparency libraries and regulatory standards guide covers the legal context. The constraints to watch are: don't misrepresent the AI-generated analysis as original research when presenting to clients, and keep humans in the review loop for any output that informs public-facing creative decisions.