Build an AI Agent That Optimizes Ad Campaigns with Trends
Build an AI agent that optimizes ad campaigns using trend signals: Python SDK and MCP tools, guardrails, human approval, and a working end-to-end loop.

An AI agent that optimizes ad campaigns is a loop, not a chatbot: it reads campaign and trend data through tools, reasons about what changed, proposes an action, and either executes it or routes it to a human. If you are building one, the practical question is which tools you expose and what the agent is allowed to do with them. This guide shows a working loop using the TrendsAGI Python SDK, its agent tools and its MCP server as the trend-signal layer your ad data cannot provide.
The timing is not speculative. Amazon Ads announced Ads Agent on November 11, 2025 to help advertisers plan, launch and optimize campaigns (advertising.amazon.com), and Google made its Ads Advisor and Analytics Advisor chatbot agents generally available to all English-language accounts (adexchanger.com). Third-party plumbing matured alongside: GoMarble OS ships as a Claude Code / Codex CLI plugin that connects agents to live ad-platform data through an MCP server with OAuth. What remains missing from vendor announcements and agency essays is the build: tool definitions, scheduling, guardrails and rollback. That is what follows.
What the agent should actually optimize
Agentic systems work best on bounded, reversible decisions. In practice that means four levers: bids, budget pacing, targeting (keywords and audiences), and creative refresh. Trending topics enter the loop as the input that tells you when to move a lever — a topic gaining velocity is a signal for a creative refresh, a keyword expansion, or a short-term budget shift toward a matching category, not a reason to rewrite your whole media plan.
Keep the split explicit. Amazon says its Ads Agent automates identifying targeting segments, adjusting pacing across hundreds of campaigns, and generating SQL for advanced analytics (advertising.amazon.com). Those are the kinds of tasks worth automating. Channel-mix shifts and incrementality test design are not: Admiral Media describes agents drafting proposals while a senior media director approves any meaningful shift in channel mix, and notes that test design stays with a senior practitioner (admiral.media). Encode that boundary into your tool permissions rather than trusting the agent to respect it.
The stack: trend signal plus ad-account tools
A useful optimization agent needs two tool sets: read access to performance data (spend, conversions, CPA by campaign) and read access to a market signal that is not in the ad account. TrendsAGI supplies the second. It detects topics gaining attention on social platforms, measures velocity as posts per hour from stored snapshots, and explains each with AI insights covering summary, key themes, sentiment, audience and marketing angles. Two honesty notes to carry into your design: velocity is a measured snapshot rate, not a forecast or unique-user count, and recommendation confidence measures evidence completeness, not probability of success.
Architecturally there are two ways to expose these tools to an agent. First, in-process: install the SDK and wrap it with TrendsAGITools, which is read-only by default and only adds write tools when you pass allow_writes=True. Second, over the wire: run the MCP server or use the hosted endpoint so any MCP-speaking agent — Claude Code, Cursor, or a multi-agent framework — can call the same tools.
# In-process tools, read-only
pip install "trendsagi[mcp]"
export TRENDSAGI_API_KEY=...
from trendsagi import TrendsAGIClient, TrendsAGITools
client = TrendsAGIClient(api_key=os.environ["TRENDSAGI_API_KEY"])
tools = TrendsAGITools(client) # read-only
# On the wire: local MCP server
trendsagi mcp
# Claude Code against the hosted MCP server
claude mcp add --transport http trendsagi https://api.trendsagi.com/mcpThe hosted server at https://api.trendsagi.com/mcp is Streamable HTTP with OAuth 2.1 sign-in or an API key as a Bearer token, and exposes read-only tools. Each connection is its own API key and each tool call counts as one API request.
Step 1: find a rising trend in a category
Start with velocity rather than volume. Velocity answers "what is moving now," which is the question an ad-optimization agent actually asks. Use the SDK directly for a scheduled job, or the tools wrapper if you are handing this to an LLM.
import os
from trendsagi import TrendsAGIClient, TrendsAGITools
client = TrendsAGIClient(api_key=os.environ["TRENDSAGI_API_KEY"])
tools = TrendsAGITools(client)
rising = client.get_trends(
category="Technology",
sort_by="velocity",
limit=5,
)
for t in rising: # shape per the API; inspect keys before mapping
print(t)
If you are driving this from a tool-calling agent, the same call is one tool name. Note the return convention: success returns {"result": <data>}, failure returns {"error": ..., "detail": ...} instead of raising. Your agent loop must check for the error key rather than assume success.
out = tools.call("list_trends", {"category": "Technology"})
if "error" in out:
raise RuntimeError(out["detail"])
trend_id = out["result"]["trends"][0]["id"]
Step 2: check analytics and read the insight
Before any campaign action, the agent should pull the analytics window and the AI insight for the trend. Analytics supports period=24h|7d|30d. A single spike in a 24h window is weaker evidence than sustained growth across 7d, and your guardrail should encode that difference.
analytics = client.get_trend_analytics(trend_id, period="7d")
insight = client.get_ai_insights(trend_id)
# Same calls as tools
analytics = tools.call("get_trend_analytics", {"trend_id": trend_id, "period": "7d"})
insight = tools.call("get_trend_ai_insights", {"trend_id": trend_id})
You can also search insights by theme across trends, which is useful when a creative team wants "everything we know about AI chips" rather than one trend id:
matches = tools.call("search_trend_insights", {"key_theme_contains": "AI chips"})
Step 3: pull recommendations and propose a campaign change
TrendsAGI turns trends into evidence-backed recommendations, and exposes them with priority and an action endpoint. Treat the recommendation as a draft, not an instruction. The pattern that survives contact with a media director is: agent drafts, human approves, execution is logged.
recs = tools.call("list_recommendations", {"limit": 10, "priority": "high"})
rec_id = recs["result"]["recommendations"][0]["id"]
# Human approves in your own UI before this runs.
# client-side action call; see the API reference for the action payload
action_result = client._post(f"/api/intelligence/recommendations/{rec_id}/action")
For write tools you must construct the wrapper intentionally: TrendsAGITools(client, allow_writes=True) adds add_to_watchlist and update_recommendation. Do not enable writes in the same process that runs unattended scans.
Step 4: turn the signal into a campaign action
Map signal strength to action type, and cap the blast radius of each action:
| Signal | Agent action | Guardrail |
|---|---|---|
| Velocity rising, 7d growth positive | Draft creative refresh for matching ad set | Draft only; no publish |
| Velocity spike, 24h only | Add to watchlist, alert marketer | No budget change |
| Sustained growth, sentiment positive | Propose keyword expansion in one campaign | Cap budget delta; human approves |
| Any channel-mix implication | Escalate to media director | Hard block on execution |
Watchlist entries are how you keep observing without acting. The alert conditions are volume_threshold or percentage_growth:
client.create_topic_interest(
keyword="AI chips",
alert_condition_type="volume_threshold",
volume_threshold_value=500,
)
Safety: read-only by default, writes opt-in, usage checked
Three controls do most of the work.
- Read-only by default.
TrendsAGITools(client)exposes only read tools.allow_writes=Trueis an explicit decision, and should live in a separate deployment from your unattended scanner. - Usage visibility. Call
get_api_usagein your run loop so the agent can back off before hitting limits instead of failing mid-proposal. - Preview before execution. TrendsAGI's ad-platform connectors (Google Ads, Meta Ads, TikTok, LinkedIn, Microsoft, Pinterest, Snapchat, Reddit) preview ad changes before any explicit execution. Build your approval step on that preview, not on a hopeful dry run.
usage = tools.call("get_api_usage", {})
if usage.get("result", {}).get("remaining", 1) <= 10:
raise SystemExit("Near usage limit; skipping run")
If you extend this to outbound webhooks, never guess the delivery payload shape. Create the subscription, sendPOST /api/integrations/webhooks/{id}/test, and map fields from what actually arrives. VerifyX-Webhook-Signatureas a hex HMAC-SHA256 of the raw body with a constant-time comparison.
End-to-end example: propose, don't publish
A realistic run for a DTC growth engineer: on a schedule, scan Technology for the fastest-rising trend; confirm it has 7d analytics support and positive sentiment; match it to one live campaign; draft a recommendation; route to a human. The agent never publishes.
import os
from trendsagi import TrendsAGIClient, TrendsAGITools
client = TrendsAGIClient(api_key=os.environ["TRENDSAGI_API_KEY"])
tools = TrendsAGITools(client) # read-only
def run_once():
t = tools.call("list_trends", {"category": "Technology", "sort_by": "velocity", "limit": 5})
if "error" in t:
return {"status": "blocked", "reason": t["detail"]}
trend = t["result"]["trends"][0]
a = tools.call("get_trend_analytics", {"trend_id": trend["id"], "period": "7d"})
i = tools.call("get_trend_ai_insights", {"trend_id": trend["id"]})
if "error" in a or "error" in i:
return {"status": "blocked", "reason": "insufficient evidence"}
recs = tools.call("list_recommendations", {"limit": 10, "priority": "high"})
return {
"status": "proposed",
"trend": trend["name"],
"analytics": a["result"],
"insight": i["result"],
"candidates": recs.get("result", {}).get("recommendations", []),
"requires_approval": True,
}
run_once()
Wrap run_once in your scheduler, write every proposal to a log with the trend id and analytics window, and require a signed approval before the write path runs in a separate process with allow_writes=True.
Evaluate and keep humans in the loop
Judge the agent on proposal quality and decision latency, not just spend. Log for every run: the trend id, the analytics period, the insight themes, the proposed action and the human decision. Then compare campaign outcomes against a holdout that received no agent-proposed changes over the same window. Do not let the agent design the incrementality test — Admiral Media is explicit that test design remains a senior practitioner's job (admiral.media). Hard-block any action classified as a channel-mix shift; route it to the media director with the evidence attached.
Frequently asked questions
What exactly should the agent optimize (bids, budgets, targeting, creative) and where do trending topics enter the loop?
Optimize bounded, reversible levers: bids, pacing, targeting and creative refresh. Trending topics enter as timing and direction signals — a rising topic triggers a creative refresh or keyword expansion proposal, never an unbounded budget rewrite.
Which data sources and APIs does the agent need, and how are credentials handled?
You need ad-account performance data plus an external signal source. For TrendsAGI, authenticate with X-API-Key or Authorization: Bearer, keep the key in an environment variable, and use the hosted MCP server's OAuth 2.1 sign-in when you cannot hold a key directly.
How do I wire the agent to ad platforms — custom MCP server, plugin, or vendor agent like Amazon Ads Agent?
All three are viable. Vendor agents like Amazon Ads Agent and Google's Advisor tools are in-platform; whether they expose public APIs or extension points is not confirmed publicly. For custom control, expose ad-account and trend tools through your own MCP server and call TrendsAGI's hosted MCP endpoint for the trend side.
How do I evaluate whether the agent improved performance, and how do I keep a human in the loop on major channel-mix shifts?
Compare treatment campaigns against an untouched holdout over matched windows and log every proposal and approval. Hard-block channel-mix changes at the tool layer so the agent can only escalate them to a human approver.
What are the real limits: what agents still cannot do (incrementality design, measurement), and where vendors constrain you?
Agents still fail at incrementality test design and measurement rigor; keep that with a senior practitioner. Vendor tools also constrain you — feature access varies by account and page, and public APIs for extending them are unconfirmed.
What does a minimal working implementation look like — Python SDK, tool definitions, and a scheduled optimization run?
Install the SDK, build TrendsAGITools(client) read-only, call list_trends, get_trend_analytics and get_trend_ai_insights in one function, return proposals with requires_approval, and schedule it. Enable writes only in a separate approved process.
How we researched this
Prepared by TrendsAGI Research. Facts checked on 27 October 2026 against the sources listed below.
Capability descriptions and code use TrendsAGI's documented REST API, Python SDK and MCP server. External facts come from the sources below.
| Claim | Applies to | Source |
|---|---|---|
| Amazon Ads announced Ads Agent, an AI agent that simplifies how advertisers plan, launch and optimize campaigns. | All plans | advertising.amazon.com |
| Amazon's Ads Agent automates identifying targeting segments, adjusting pacing across hundreds of campaigns, and generating SQL queries for advanced analytics. | All plans | advertising.amazon.com |
| At launch, Amazon Ads Agent was available on specific pages across Amazon Ads, including Amazon Marketing Cloud and Amazon DSP multimedia solutions. | All plans | advertising.amazon.com |
| Google made its agentic AI tools, Ads Advisor and Analytics Advisor, fully available to all English-language accounts, per Google VP of Global Ads Dan Taylor. | All plans | adexchanger.com |
| Google's Ads Advisor and Analytics Advisor are in-platform chatbot solutions built into Google's ads products. | All plans | adexchanger.com |
| Admiral Media uses agents to draft proposals while a senior media director still approves any meaningful shift in channel mix. | All plans | admiral.media |
| Agents can execute an incrementality test once the design is locked, but the test design itself remains a senior practitioner's job. | All plans | admiral.media |
We re-research and rewrite this page at least every four months; the updated date only changes when the facts are re-checked.
Sources
- Boost advertising efficiency with Ads Agent (Amazon Ads) — advertising.amazon.com
- Agentic AI in Performance Marketing: What Autonomous Ad Ops Means for App Growth (Admiral Media) — admiral.media
- Google Rolls Out Chatbot Agents For Marketers (AdExchanger) — adexchanger.com