agent-ads
01
Step 01

Authenticate

Meta requires an access token. Store it once in your OS credential store:

Primary command
Authenticate
bash
agent-ads meta auth set

For CI, headless Linux, or one-off overrides, you can still set a shell variable for the current process:

bash
export META_ADS_ACCESS_TOKEN=EAABs...

Required permission: ads_read — read access to campaigns, insights, creatives, and pixels.

Optional permission: business_management — discover businesses and ad accounts (businesses list, ad-accounts list). Without it, you can still query any account directly if you know its ID.

Both permissions are read-only. The CLI never creates, modifies, or deletes anything.

Generate a token at the Graph API Explorer — select your app, add the permissions above, and click "Generate Access Token".

On Linux, persistent secure storage requires a running Secret Service provider such as GNOME Keyring or KWallet. If secure storage is unavailable, use META_ADS_ACCESS_TOKEN in the shell for that session.

02
Step 02

Verify your setup

Add --api to also ping the Meta API and confirm your token works.

Primary command
Verify your setup
bash
agent-ads meta doctor
json
{
  "ok": true,
  "checks": [
    { "name": "credential_store", "ok": true, "detail": "stored Meta token found in OS credential store" },
    { "name": "config_file", "ok": true, "detail": "using /work/agent-ads.config.json" },
    { "name": "access_token", "ok": true, "detail": "using stored Meta token from the OS credential store" }
  ]
}

Add --api to also ping the Meta API and confirm your token works.

03
Step 03

Discover your accounts

Primary command
Discover your accounts
bash
# List businesses you have access to
agent-ads meta businesses list

# List ad accounts under a business
agent-ads meta ad-accounts list --business-id 1234567890
json
[
  { "id": "act_1234567890", "name": "My Ad Account", "account_status": 1, "currency": "USD" }
]
04
Step 04

Explore campaigns

Primary command
Explore campaigns
bash
agent-ads meta campaigns list --account act_1234567890
05
Step 05

Pull a performance report

Primary command
Pull a performance report
bash
agent-ads meta insights query \
  --account act_1234567890 \
  --level campaign \
  --fields campaign_id,campaign_name,impressions,clicks,spend \
  --since 2026-03-01 \
  --until 2026-03-16 \
  --time-increment 1
json
[
  {
    "campaign_id": "120210123456",
    "campaign_name": "Spring Sale",
    "impressions": "4520",
    "clicks": "312",
    "spend": "48.75",
    "date_start": "2026-03-01",
    "date_stop": "2026-03-01"
  }
]
06
Step 06

Export to CSV

Primary command
Export to CSV
bash
agent-ads meta insights query \
  --account act_1234567890 \
  --level campaign \
  --fields campaign_id,campaign_name,impressions,clicks,spend \
  --date-preset last_7d \
  --format csv \
  --output report.csv
Reference

Meta Ads guides

7 guides — exact flags, auth details, and workflow notes.

Guide

Meta Guide

This is the routing guide for the Meta provider. Read this first when the user wants to work with Meta (Facebook/Instagram) ads. Then load only the specific reference file linked below.

Route to the Right Reference

TaskFirst commandReference file
Set up auth, check config, understand outputagent-ads meta doctormeta-auth-and-output.md
Discover businesses and ad accountsagent-ads meta businesses listmeta-accounts-and-objects.md
List campaigns, ad sets, or adsagent-ads meta campaigns list --account <id>meta-accounts-and-objects.md
Run a performance report (sync)agent-ads meta insights query ...meta-reports.md
Run a large async reportagent-ads meta insights export --async --wait ...meta-reports.md
Manage async report lifecycleagent-ads meta report-runs submit/wait/resultsmeta-reports.md
Inspect ad creativesagent-ads meta creatives preview --ad <id>meta-creative-and-changes.md
Review account change historyagent-ads meta activities list --account <id>meta-creative-and-changes.md
Check pixels, datasets, or measurement healthagent-ads meta pixel-health get --pixel <id>meta-tracking.md
Follow an end-to-end recipemeta-workflows.md

Load only the reference file you need. Do not preload all of them.

Common Mistakes

  • Forgetting META_ADS_ACCESS_TOKEN before running API commands
  • Passing both --account and --object to insights commands (they are mutually exclusive)
  • Using --action-breakdowns without actions in --fields
  • Treating default JSON output as if it includes meta, paging, or warnings (it doesn't — use --envelope)
  • Assuming pixel-health is a raw EMQ passthrough (it's a combined diagnostic view)
  • Forgetting --all or --max-items when paginating (you only get one page by default)
Guide

Meta Auth And Output

Use this file for local setup, authentication, config resolution, and output behavior.

First command
Meta Auth And Output
bash
agent-ads meta auth set

Authentication

Two environment variables control Meta API access:

VariableRequiredPurpose
META_ADS_ACCESS_TOKENYesBearer token for all Meta API calls

Required permissions

PermissionNeeded for
ads_readAll --account commands: campaigns, insights, creatives, pixels
business_managementbusinesses list and ad-accounts list (discovery)

Both are read-only — no write access is granted. Generate a token at the Graph API Explorer with the permissions above.

Secrets are never read from CLI flags or config files. Persistent secrets live in the OS credential store, and shell env remains available for overrides or CI.

Setting up auth

Option 1 — store the token in the OS credential store:

bash
agent-ads meta auth set

Option 2 — shell environment override:

bash
export META_ADS_ACCESS_TOKEN=EAABs...

On Linux, persistent secure storage requires a running Secret Service provider such as GNOME Keyring or KWallet. In headless environments, use the shell variable for that process.

Verifying auth

bash
# Check config and env without hitting the API
agent-ads meta doctor

# Also ping the API to confirm the token works
agent-ads meta doctor --api

Example doctor output:

json
{
  "ok": true,
  "checks": [
    { "name": "credential_store", "ok": true, "detail": "stored Meta token found in OS credential store" },
    { "name": "config_file", "ok": true, "detail": "using /work/agent-ads.config.json" },
    { "name": "access_token", "ok": true, "detail": "using stored Meta token from the OS credential store" },
    { "name": "api_ping", "ok": true, "detail": "token accepted by Meta API; sampled 1 business record(s)" }
  ]
}

Config Resolution

Precedence (highest to lowest):

  1. Shell META_ADS_ACCESS_TOKEN
  2. OS credential store for the token

For non-secret config:

  1. CLI flags (--api-version v24.0)
  2. Shell environment variables
  3. agent-ads.config.json file values

Config file

Default path: agent-ads.config.json in the current directory. Override with --config <path>.

Supported keys under providers.meta:

KeyDefaultDescription
api_base_urlhttps://graph.facebook.comMeta Graph API base URL
api_versionv25.0API version
timeout_seconds60HTTP request timeout
default_business_idnoneFallback for --business-id
default_account_idnoneFallback for --account
output_formatjsonDefault output format

Inspecting config

bash
# Show the resolved config file path
agent-ads meta config path

# Show the full resolved configuration (all sources merged)
agent-ads meta config show

# Validate the config file parses correctly
agent-ads meta config validate

Output

Formats

FlagBehaviorBest for
--format json (default)JSON array or objectAutomation, piping to jq
--format jsonlOne JSON object per lineStreaming, line-by-line processing
--format csvCSV with header rowSpreadsheets, data import

Default output (data-only)

By default, stdout contains only the data — no metadata wrapper:

json
[
  { "id": "act_123", "name": "Agency Account" }
]

Envelope mode

Add --envelope to wrap data with response metadata, paging cursors, and warnings:

json
{
  "data": [{ "id": "act_123", "name": "Agency Account" }],
  "meta": {
    "api_version": "v25.0",
    "endpoint": "/1234567890/ad_accounts",
    "object_id": "1234567890"
  },
  "paging": { "cursors": { "before": "...", "after": "..." }, "next": "..." }
}

Use --envelope when you need to extract the paging cursor for manual pagination, or when you want to see request metadata and warnings.

Other output flags

FlagWhat it does
--prettyPretty-print JSON output
--include-metaAdd api_version, endpoint, object_id as columns in CSV output
--output <path>Write to a file instead of stdout (- for explicit stdout)
-q, --quietSuppress warnings on stderr

Error output

Errors are always JSON on stderr:

json
{ "error": { "kind": "api", "message": "Invalid OAuth 2.0 Access Token", "code": 190 } }

Exit Codes

CodeMeaningExample
0SuccessNormal response
1Transport or internal failureNetwork timeout, serialization error
2Config or argument failureMissing token, invalid flags
3Meta API failureToken expired, rate limit, invalid field
Guide

Meta Accounts And Objects

Use this file for business discovery, ad-account listing, and campaign/adset/ad metadata.

First command
Meta Accounts And Objects
bash
agent-ads meta businesses list

Businesses

List all businesses accessible to your token:

bash
agent-ads meta businesses list

With custom fields and full pagination:

bash
agent-ads meta businesses list --all --fields id,name,verification_status

Default fields: id, name, verification_status.

Ad Accounts

List ad accounts under a business. The --scope flag controls which relationship to query:

ScopeDescription
accessible (default)All ad accounts the business can access
ownedOnly ad accounts owned by the business
pending-clientAd accounts with pending client relationships
bash
# Default scope (accessible)
agent-ads meta ad-accounts list --business-id 1234567890

# Explicit scope
agent-ads meta ad-accounts list --business-id 1234567890 --scope owned

# With custom fields
agent-ads meta ad-accounts list --business-id 1234567890 --fields id,name,account_status,currency,timezone_name

Default fields: id, account_id, name, account_status, currency, timezone_name.

If default_business_id is set in config, you can omit --business-id.

Campaigns

bash
agent-ads meta campaigns list --account act_1234567890
agent-ads meta campaigns list --account act_1234567890 --all --fields id,name,status,objective

Default fields: id, name, status, effective_status, objective, created_time, updated_time.

Ad Sets

bash
agent-ads meta adsets list --account act_1234567890
agent-ads meta adsets list --account act_1234567890 --all --fields id,name,campaign_id,status,daily_budget

Default fields: id, name, campaign_id, status, effective_status, daily_budget, lifetime_budget, billing_event.

Ads

bash
agent-ads meta ads list --account act_1234567890
agent-ads meta ads list --account act_1234567890 --all --fields id,name,adset_id,status

Default fields: id, name, adset_id, campaign_id, status, effective_status, creative{id,name}.

Shared Flags

All object list commands accept:

FlagDescription
--account <id>Ad account ID (omit if default_account_id is set in config)
--fields <list>Comma-separated field names
--fields-file <path>Read field names from a file (comma or newline separated, - for stdin)
--page-size <n>Items per API request
--cursor <token>Resume from a cursor
--allAuto-paginate through all results
--max-items <n>Stop after collecting N items

Account ID Normalization

Account IDs accept either raw numeric (1234567890) or prefixed (act_1234567890) format. The CLI always normalizes to act_<id> before making API calls. Output also uses the act_ prefix.

Guide

Meta Reports

Use this file for insights query (synchronous), insights export (high-level async), and report-runs (explicit async lifecycle).

First command
Meta Reports
bash
agent-ads meta insights query \
  --account act_1234567890 \
  --level campaign \
  --fields campaign_id,campaign_name,impressions,clicks,spend \
  --since 2026-03-01 \
  --until 2026-03-16 \
  --time-increment 1

Use this file for insights query (synchronous), insights export (high-level async), and report-runs (explicit async lifecycle).

Sync Insights Query

The most common way to pull performance data. Returns results inline.

bash
agent-ads meta insights query \
  --account act_1234567890 \
  --level campaign \
  --fields campaign_id,campaign_name,impressions,clicks,spend \
  --since 2026-03-01 \
  --until 2026-03-16 \
  --time-increment 1

Example output:

json
[
  {
    "campaign_id": "120210123456",
    "campaign_name": "Spring Sale",
    "impressions": "4520",
    "clicks": "312",
    "spend": "48.75",
    "date_start": "2026-03-01",
    "date_stop": "2026-03-01"
  }
]

Insights flags

Object selection (mutually exclusive)

FlagDescription
--account <id>Query insights for an ad account (most common)
--object <id>Query insights for any Graph API object (campaign, adset, ad, etc.)

You must use one or the other — not both. If neither is provided and default_account_id is set in config, that value is used.

Aggregation level

FlagValuesDescription
--levelaccount, campaign, adset, adGranularity of the breakdown

Time range (mutually exclusive groups)

FlagsDescription
--since YYYY-MM-DD --until YYYY-MM-DDExplicit date range (both required together)
--date-preset <preset>Named preset: today, yesterday, last_7d, last_14d, last_28d, last_30d, last_90d, this_month, last_month, etc.
--time-range-file <path>JSON file with {"since": "...", "until": "..."} (use - for stdin)

Time increment

FlagValuesDescription
--time-increment1 (daily), 7 (weekly), 14 (biweekly), monthly, all_daysHow to bucket the time range into rows

Most common: 1 for daily, monthly for monthly. Omit for a single aggregated row per entity.

Breakdowns and dimensions

FlagDescription
--breakdowns <list>Comma-separated: age, gender, country, placement, publisher_platform, device_platform, etc.
--action-breakdowns <list>Comma-separated: action_type, action_device, action_destination, etc. Requires actions in --fields
--attribution-windows <list>Comma-separated: 1d_click, 7d_click, 1d_view, etc.

Filtering and sorting

FlagDescription
--filter <json>Inline filter object (repeatable): '{"field":"impressions","operator":"GREATER_THAN","value":"100"}'
--filter-file <path>JSON file containing a filter array (use - for stdin)
--sort <list>Comma-separated: spend_descending, impressions_ascending, etc.

Fields

FlagDescription
--fields <list>Comma-separated field names
--fields-file <path>Read fields from file (comma or newline separated, - for stdin)

If no fields are specified, defaults to: account_id, account_name, campaign_id, campaign_name, impressions, clicks, spend.

Pagination

FlagDescription
--page-size <n>Items per API page
--cursor <token>Resume from cursor
--allAuto-paginate all results
--max-items <n>Stop after N items

High-Level Async Export

For large jobs, use insights export with --async. This submits an async report run and optionally waits for it to complete and returns the results:

bash
# Submit and wait in one command
agent-ads meta insights export \
  --account act_1234567890 \
  --level ad \
  --fields ad_id,ad_name,spend,impressions,actions \
  --since 2026-01-01 --until 2026-03-01 \
  --async --wait

# Submit only (returns report_run_id, you poll separately)
agent-ads meta insights export \
  --account act_1234567890 \
  --level ad \
  --fields ad_id,ad_name,spend \
  --async

Additional flags for async mode:

FlagDefaultDescription
--asyncoffUse async report run instead of inline query
--waitoffPoll until complete, then return results (requires --async)
--poll-interval-seconds5Seconds between status checks
--wait-timeout-seconds3600Maximum wait time before timing out

Without --async, insights export behaves identically to insights query.

Explicit Report Runs

For full control over the async lifecycle:

Submit

bash
agent-ads meta report-runs submit \
  --account act_1234567890 \
  --level ad \
  --fields ad_id,ad_name,spend,impressions,actions \
  --since 2026-03-01 --until 2026-03-16

Returns: { "report_run_id": "12345", "id": "12345", ... }

Check status

bash
agent-ads meta report-runs status --id 12345

Returns: { "id": "12345", "async_status": "Job Running", "async_percent_completion": 45, ... }

Wait for completion

bash
agent-ads meta report-runs wait --id 12345
agent-ads meta report-runs wait --id 12345 --poll-interval-seconds 10 --wait-timeout-seconds 1800

Polls until async_status contains "complete" or async_percent_completion reaches 100. Returns the final status object.

Fetch results

bash
agent-ads meta report-runs results --id 12345 --all
agent-ads meta report-runs results --id 12345 --all --fields ad_id,ad_name,spend --format csv --output results.csv

Gotchas

  • --account and --object are mutually exclusive. Use --account for ad-account-level queries, --object for querying a specific campaign/adset/ad.
  • If you use --action-breakdowns, you must include actions in --fields. The CLI validates this and will error if actions is missing.
  • Prefer async (--async --wait or explicit report-runs) for large date ranges, ad-level queries across many ads, or heavy breakdown combinations.
  • --time-increment and --date-preset are separate concepts: --date-preset sets the time range, --time-increment sets how rows are bucketed within that range.
Guide

Meta Creative And Changes

Use this file for inspecting ad creative content and reviewing account activity history.

First command
Meta Creative And Changes
bash
agent-ads meta creatives get --id 120210123456789

Creative Lookups

Get creative by ID

Fetch the full creative object (story spec, asset feed, thumbnail):

bash
agent-ads meta creatives get --id 120210123456789

Default fields: id, name, object_story_spec, asset_feed_spec, thumbnail_url.

bash
# With custom fields
agent-ads meta creatives get --id 120210123456789 --fields id,name,body,image_url,call_to_action_type

Preview creative

Get the rendered ad preview. You can target by creative ID or ad ID:

bash
# By creative ID
agent-ads meta creatives preview --creative 120210123456789

# By ad ID (resolves the ad's creative automatically)
agent-ads meta creatives preview --ad 120210987654321

Default fields: body (the rendered preview HTML/payload).

Optional flags:

FlagDescription
--ad-format <format>Ad format to preview (e.g. DESKTOP_FEED_STANDARD, MOBILE_FEED_STANDARD)
--render-type <type>Render type (e.g. FALLBACK)
--fields <list>Custom fields

When using --ad, the CLI first resolves the ad to its creative ID, then calls the preview edge. A warning is emitted noting this resolution step.

Activities (Change History)

List account activity logs to answer "what changed and when?"

bash
agent-ads meta activities list --account act_1234567890

Default fields: id, event_time, event_type, category, object_type, translated_event_type.

Filtering activities

FlagDescription
--since <timestamp>Start time (ISO 8601, e.g. 2026-03-10T00:00:00Z)
--until <timestamp>End time
--category <category>Filter by category (e.g. AD, CAMPAIGN, BUDGET)
--data-source <source>Filter by data source
--oid <object-id>Filter by specific object ID
--business-id <id>Filter by business
--add-childrenInclude child object activities

Pagination

Activities support standard pagination: --page-size, --cursor, --all, --max-items.

Forensic investigations often need more than one page. Always use --all or --max-items explicitly.

Example: find all changes in the last 24 hours

bash
agent-ads meta activities list \
  --account act_1234567890 \
  --since 2026-03-17T00:00:00Z \
  --all \
  --fields id,event_time,event_type,category,object_type,translated_event_type,extra_data

When to Use What

QuestionCommand
"What does this ad look like?"creatives preview --ad <id>
"What's the raw creative spec?"creatives get --id <id>
"What changed in this account recently?"activities list --account <id> --since <time> --all
"Who changed this specific campaign?"activities list --account <id> --oid <campaign-id> --all

Note: activities list does not support --date-preset or --time-range-file. Use --since and --until directly.

Guide

Meta Tracking

Use this file for custom conversions, pixels, datasets, and measurement-health diagnostics.

First command
Meta Tracking
bash
agent-ads meta custom-conversions list --account act_1234567890
agent-ads meta custom-conversions list --account act_1234567890 --all

Custom Conversions

List custom conversion rules for an ad account:

bash
agent-ads meta custom-conversions list --account act_1234567890
agent-ads meta custom-conversions list --account act_1234567890 --all

Default fields: id, name, custom_event_type, rule, creation_time.

Pixels

List pixels attached to an ad account:

bash
agent-ads meta pixels list --account act_1234567890
agent-ads meta pixels list --account act_1234567890 --all --fields id,name,last_fired_time,match_rate_approx

Default fields: id, name, owner_ad_account, last_fired_time, match_rate_approx, event_stats.

Datasets

Get quality metrics for a specific dataset (offline event set):

bash
agent-ads meta datasets get --id 1234567890
agent-ads meta datasets get --id 1234567890 --fields id,name,event_stats,match_rate_approx,collection_rate

Default fields: id, name, event_stats, last_fired_time, match_rate_approx.

Note: --id is the dataset ID, not an ad account ID.

Pixel Health (Combined Diagnostics)

pixel-health get is a combined diagnostic view — it fetches pixel metadata and the pixel stats edge in a single call, then returns them together:

bash
agent-ads meta pixel-health get --pixel 1234567890

Returns:

json
{
  "pixel": {
    "id": "1234567890",
    "name": "My Pixel",
    "match_rate_approx": 0.45,
    "event_stats": "...",
    "last_fired_time": "2026-03-17T12:00:00Z"
  },
  "stats": [...]
}

Optional filters

FlagDescription
--aggregation <value>Aggregation level for stats
--event <name>Filter to a specific event (e.g. Purchase, Lead)
--event-source <source>Filter by event source
--start-time <timestamp>Stats start time
--end-time <timestamp>Stats end time
--fields <list>Override default pixel fields

Example: check health for a specific event

bash
agent-ads meta pixel-health get \
  --pixel 1234567890 \
  --event Purchase \
  --start-time 2026-03-01 \
  --end-time 2026-03-17

When to Use What

QuestionCommand
"What pixels does this account have?"pixels list --account <id>
"What custom conversions are set up?"custom-conversions list --account <id>
"Is the pixel firing correctly?"pixel-health get --pixel <id>
"What's the dataset match rate?"datasets get --id <id>
"What events has the pixel received recently?"pixel-health get --pixel <id> --event Purchase

Note: pixel-health is a practical diagnostics view built by the CLI. It is not a raw passthrough of Meta's Event Match Quality (EMQ) API. It combines the pixel node metadata with the /stats edge to give a unified health picture.

Guide

Meta Workflows

Use this file for end-to-end recipes. Each workflow is a sequence of commands you can run in order.

First command
Meta Workflows
bash
# Step 1: List all businesses
agent-ads meta businesses list --all --pretty

# Step 2: For each business, list accessible ad accounts
agent-ads meta ad-accounts list --business-id 1234567890 --scope accessible --all

# Step 3: Optionally check which accounts you own vs. have access to
agent-ads meta ad-accounts list --business-id 1234567890 --scope owned --all

1. Multi-Client Account Discovery

Start from your token and discover all businesses and their ad accounts:

bash
# Step 1: List all businesses
agent-ads meta businesses list --all --pretty

# Step 2: For each business, list accessible ad accounts
agent-ads meta ad-accounts list --business-id 1234567890 --scope accessible --all

# Step 3: Optionally check which accounts you own vs. have access to
agent-ads meta ad-accounts list --business-id 1234567890 --scope owned --all

2. Daily Performance Report

Pull daily campaign performance for a date range, exported as CSV:

bash
agent-ads meta insights query \
  --account act_1234567890 \
  --level campaign \
  --fields campaign_id,campaign_name,impressions,clicks,spend,cpc,ctr \
  --since 2026-03-01 \
  --until 2026-03-16 \
  --time-increment 1 \
  --format csv \
  --output campaign-daily.csv

For the last 7 days with a named preset:

bash
agent-ads meta insights query \
  --account act_1234567890 \
  --level campaign \
  --fields campaign_id,campaign_name,impressions,clicks,spend \
  --date-preset last_7d \
  --time-increment 1 \
  --all

3. Ad-Level Report With Breakdowns

Detailed ad-level performance with age and gender breakdowns:

bash
agent-ads meta insights query \
  --account act_1234567890 \
  --level ad \
  --fields ad_id,ad_name,impressions,clicks,spend,actions \
  --date-preset last_30d \
  --breakdowns age,gender \
  --action-breakdowns action_type \
  --all

Note: actions must be in --fields when using --action-breakdowns.

4. Large Async Export

For reports that are too large for sync queries (many ads, long date ranges, heavy breakdowns):

One-command approach

bash
agent-ads meta insights export \
  --account act_1234567890 \
  --level ad \
  --fields ad_id,ad_name,spend,impressions,clicks,actions \
  --since 2026-01-01 --until 2026-03-01 \
  --async --wait \
  --format csv \
  --output large-report.csv

Step-by-step approach (explicit control)

bash
# Submit the job
agent-ads meta report-runs submit \
  --account act_1234567890 \
  --level ad \
  --fields ad_id,ad_name,spend,impressions,clicks \
  --since 2026-01-01 --until 2026-03-01

# Note the report_run_id from the output, then wait
agent-ads meta report-runs wait --id 12345678

# Fetch results
agent-ads meta report-runs results --id 12345678 --all --format csv --output results.csv

5. Forensic Diagnosis

Investigate what changed, inspect the creative, and check pixel health:

bash
# Step 1: What changed in the account recently?
agent-ads meta activities list \
  --account act_1234567890 \
  --since 2026-03-10T00:00:00Z \
  --all

# Step 2: Inspect a specific ad's creative
agent-ads meta creatives preview --ad 120210987654321

# Step 3: Check if the pixel is healthy
agent-ads meta pixel-health get --pixel 9876543210

# Step 4: Check dataset match quality
agent-ads meta datasets get --id 5555555555

6. CI/Automation Pattern

Use in scripts or CI jobs with explicit error handling:

bash
#!/bin/bash
set -euo pipefail

# Verify setup
agent-ads meta doctor --api -q

# Pull report
agent-ads meta insights query \
  --account act_1234567890 \
  --level campaign \
  --fields campaign_id,campaign_name,impressions,clicks,spend \
  --date-preset yesterday \
  --format csv \
  --output /data/yesterday.csv

echo "Report saved to /data/yesterday.csv"

Exit codes make it safe in set -e scripts: 0 = success, 1 = transport/internal, 2 = config/argument, 3 = Meta API error.

7. Piping and Composing

Combine with standard Unix tools:

bash
# Pretty-print to less
agent-ads meta businesses list --pretty | less

# Filter with jq
agent-ads meta campaigns list --account act_1234567890 --all | jq '.[] | select(.status == "ACTIVE")'

# Count active campaigns
agent-ads meta campaigns list --account act_1234567890 --all | jq '[.[] | select(.effective_status == "ACTIVE")] | length'

# JSONL for line-by-line processing
agent-ads meta insights query \
  --account act_1234567890 \
  --level campaign \
  --fields campaign_id,spend \
  --date-preset last_7d \
  --format jsonl | while IFS= read -r line; do
    echo "$line" | jq -r '.campaign_id + ": $" + .spend'
  done