How to Manage Google Ads with an AI Agent: An MCP Server with Business Rules
How do you manage Google Ads with an AI agent without risking the budget? The agent should not write to the Google Ads API directly. It works through an MCP server that holds the business rules: bid limits, negative keyword lists, a check before every session and a traced record of every change. Below is that setup running on my own Etsy shop.
Why not the official Google Ads MCP server
This is my own project, built for my Etsy shop MoonBloom, which sells children's wallpapers and runs Google Ads campaigns in DE, AT, ES and FR. The code is private, so I show short fragments only.
My first question was whether I needed to build anything. Google's documentation (developers.google.com, checked 2026-10-13) describes its official Google Ads MCP server as read-only in the current release. It has three tools: list_accessible_customers, search for GAQL queries and get_resource_metadata. In Google's words: "It cannot modify bids, pause campaigns, or create new assets."
Write access therefore means calling the mutate methods of the Google Ads API directly. The API executes what it is sent. It has no object locking, so concurrent edits raise CONCURRENT_MODIFICATION_ERROR. Google itself recommends test accounts, validate_only and Change History for making changes safely.
My conclusion
The business rules have to live in a layer I own: how far a bid may move, which searches are never wanted, how many ads may run. A prompt can ask the agent to respect them. Code can refuse the call when it does not. That is the whole reason this server exists.
Architecture: one FastMCP tool call, end to end
I wrote this MCP server in Python with FastMCP from the official MCP SDK (mcp 1.28.1) over stdio. Claude Code is the agent, and the server is registered in the project's .mcp.json. This is what happens between one tool call and Google:
โ the mcp_tool() decorator in server.py registers it with FastMCP and tags the call with the tool name
2. Input shield
โ writes: build_request() builds a Pydantic model, a failed rule is journaled as REQUEST_REJECTED, Google is never called
3. Preflight gate
โ refusal_for() returns PREFLIGHT_REQUIRED until the session's log check has passed
4. Business logic in tools/*.py
โ campaign, adgroup, rsa, asset, negative, history, observability, eval and preflight tools
5. Google Ads client with a gRPC interceptor
โ core/client.py logs every RPC and retries read methods only
6. Result and telemetry
โ append_audit_log (secrets redacted) โ logs/audit.jsonl โ Cloud Logging, span โ Cloud Trace
Reads get ID validation (IdArguments, digits only). Writes get a full Pydantic model, so a malformed request dies at step 2.
The client retries read methods only: 2 retries, after 1 s and 2 s plus up to 0.5 s of jitter. Writes are never retried automatically, because a repeated mutation could apply twice.
The rest of the stack: google-ads client library 31.0.0, Pydantic 2.13, the OpenTelemetry SDK with a Cloud Trace exporter and gRPC instrumentation, and Google Cloud Logging.
Tool catalog: 36 tools over the Google Ads API
24 tools read and 12 write. I grouped them by what they are for.
| Group | Tools | Read / write | Rule it carries |
|---|---|---|---|
| Preflight, journal, observability (7) | preflight_log_check get_change_history verify_changes_logged get_cloud_logs get_cloud_trace analyze_tool_health evaluate_agent_process |
7 read | Opens or keeps shut the preflight gate, reconciles Google's change history with the journal, scores tool health and agent behaviour. |
| Campaigns, budgets, bids (10) | get_campaigns get_campaign_details get_campaign_targeting_overview get_ad_groups get_ad_group_keywordsWrite: toggle_campaign_status set_campaign_daily_budget step_bid_threshold set_ad_group_cpc_bid set_keyword_status |
5 read ยท 5 write | CPC ceiling in steps of 0.05 EUR within 0.10-3.00 EUR, daily budget 1.00-100.00 EUR in whole cents, ad group bid 0.05-3.00 EUR for MANUAL_CPC only. |
| Ads (2) | get_campaign_adsWrite: deploy_golden_rsa |
1 read ยท 1 write | 15 headlines, 4 descriptions, headline 1 is the Dynamic Keyword Insertion headline, at most 3 enabled RSAs, create and pause in one request. |
| Assets (7) | get_assets_associations get_assets_performance get_assets_diversity get_campaign_images get_campaign_assets_overviewWrite: link_asset_to_entity unlink_asset_from_entity |
5 read ยท 2 write | Reads show coverage and performance. The two writes pass the input shield and the preflight gate like every other write. |
| Search terms, negatives, audits, recommendations (10) | mine_search_terms_and_harvest_negatives audit_campaign_4level_shield get_daily_performance get_impression_share_loss fetch_google_ai_recommendations search_keyword_ideasWrite: apply_negative_shield add_negative_keywords remove_negative_keyword auto_fix_collisions_and_dupes |
6 read ยท 4 write | Per-language negative lists (DE 58, FR 40, ES 39 words), duplicates skipped, chunks of 500. Duplicates of the High Intent campaign are paused elsewhere. |
Business rules in code, not in the prompt
Each rule below exists because of money or ad quality, and each lives in a file I can read, not in a system prompt the model may weigh against something else.
| Rule | Where | What happens on violation |
|---|---|---|
| Preflight gate | shield/preflight.py tools/preflight_tools.py |
PREFLIGHT_REQUIRED, journaled, no Google call. OK opens the gate. ATTENTION keeps it shut until the owner says "continue" and the agent re-runs with acknowledge=True. |
| CPC ceiling (Maximize Clicks) | tools/campaign_tools.py |
Steps of ยฑ0.05 EUR only, within 0.10-3.00 EUR, TARGET_SPEND campaigns only. Out of range or uncapped: refused, nothing sent. |
| Daily budget | shield/models_campaign.py core/client.py |
Outside 1.00-100.00 EUR the shield rejects the request. Amounts are rounded to whole cents. |
| Ad group bid | shield/models_adgroup.py |
Allowed range 0.05-3.00 EUR, MANUAL_CPC campaigns only. |
| Responsive search ads ("golden RSA") | shield/models_ad.py tools/rsa_tools.py |
Exactly 15 headlines and 4 descriptions, headline 1 is the DKI headline, headline up to 30 characters, description up to 90, final URL carries the shop's coupon parameter. At most 3 enabled RSAs per ad group: the new ad is created and the oldest paused in the same mutate request. |
| Negative keyword shields | tools/negative_tools.py |
Per-language lists (DE 58, FR 40, ES 39 words). Words already present are skipped, the rest is sent in chunks of 500. |
| Cross-campaign duplicates | tools/negative_tools.py |
Keywords that also exist in the High Intent campaign are paused in the other campaigns (auto_fix_collisions_and_dupes). |
| Sparse update masks | 7 write paths | Every update sends an explicit field mask, so only the named field changes. |
| Outside changes | tools/history_tools.py |
Anything changed by a script, another agent or a person in the UI shows up as OUTSIDE_CHANGES. |
| Retries | core/client.py |
Reads only. Writes are never retried by the client. |
The CPC ceiling: a bid the agent can only nudge
Under Maximize Clicks the campaign CPC ceiling is the bid lever that counts, because that strategy ignores ad group bids. So it is the one number that decides what a click may cost. The agent may move it by 0.05 EUR per call and never outside 0.10-3.00 EUR, which caps how much damage one wrong call can do to the cost per click. An uncapped campaign has no known starting point, so the tool refuses to guess one.
if c.bidding_strategy_type.name != "TARGET_SPEND":
raise ValueError(f"Campaign '{c.name}' uses {c.bidding_strategy_type.name}, not TARGET_SPEND (Maximize Clicks); it has no CPC ceiling to step.")
curr_micros = c.target_spend.cpc_bid_ceiling_micros
if not curr_micros:
raise ValueError(f"Campaign '{c.name}' has no CPC ceiling set (uncapped); refusing to guess a starting value.")
step_micros = 50_000 if req.direction == "+0.05" else -50_000
new_micros = curr_micros + step_micros
if not CEILING_MIN_MICROS <= new_micros <= CEILING_MAX_MICROS:
raise ValueError(f"New ceiling {new_micros / 1e6:.2f} EUR is outside the 0.10-3.00 EUR safeguard.")
The budget: a rounding bug that would look like a Google error
Budgets reach the API in micros. In floating point int(4.10 * 1_000_000) is 4099999, and the API rejects it because it is not a multiple of 0.01 EUR. The helper rounds to whole cents first, so a correct budget never fails in a way the agent would have to interpret. The daily budget itself stays within 1.00-100.00 EUR, so a slipped decimal cannot turn a small daily spend into a large one.
def eur_to_micros(amount_eur: float) -> int:
"""
Converts EUR to micros rounded to whole cents.
int(4.10 * 1_000_000) == 4099999, which the API rejects as not a multiple of 0.01 EUR.
"""
return int(round(amount_eur * 100)) * 10_000
The gate: nothing runs until the log check has passed
The preflight gate is a few lines because the rule is simple: until the session's log check has passed, every non-exempt tool returns the refusal text. The agent cannot argue its way past it, because the refusal happens in code before any tool body runs.
def refusal_for(function: str) -> Optional[str]:
"""The refusal text when `function` must not run yet, else None."""
if not required() or is_open() or function in PREFLIGHT_EXEMPT:
return None
return REFUSAL
Ad quality and the negative lists
The golden RSA rules protect ad quality: every live ad is complete, starts with the keyword-insertion headline, carries the shop's coupon and stays within the character limits. Creating the new ad and pausing the oldest in one mutate request means an ad group is never left half changed. The negative shields protect the budget the other way round: they keep spend away from searches I never want to pay for, in each language I advertise in.
Tracing and post-run analysis: closing the loop
Rules in code stop bad calls. They do not tell me whether the agent behaved well over a whole session, or whether someone changed the account behind its back. So I treat one agent run as one turn of a loop. The evals are not a dashboard I might remember to open: their result is the input that decides whether the next run may start.
โ OK opens the gate, ATTENTION keeps every ad tool shut until the owner reviews it
Agent run: Claude Code calls tools
โ every call becomes one span and one structured log line
Trace and structured log: Cloud Trace, logs/audit.jsonl, Cloud Logging
โ analyze_tool_health, evaluate_agent_process, verify_changes_logged
Post-run evals
โ their findings are read by the next preflight
Next preflight gate
Every tool call is a trace
I use an OpenTelemetry TracerProvider with a Cloud Trace exporter (shield/cloud_sink.py). Each tool call produces one span named tools/call plus the tool name, with the attribute gen_ai.tool.name.
gRPC instrumentation adds a child span for every Google Ads RPC inside it, filtered to Google Ads calls only. The agent can open a trace itself with get_cloud_trace, so a slow call can be followed down to the RPC that took the time.
Structured logs, correlated with traces
Each call writes one JSON line: timestamp, tool, action_type (READ or MUTATION), args, success, error_code, latency_ms, sla_status, a google_ads_api block (calls, ms, failed, retried, methods), request ids, trace id and span id, session_id and operator. Secrets are redacted before writing.
The line goes to logs/audit.jsonl and is mirrored to Cloud Logging. Severity is NOTICE for a successful change, WARNING for a shield refusal and ERROR for a Google-side failure. The trace id sits in the log line, so I can jump from a log entry to its span. The agent reads its own logs with get_cloud_logs.
After the run: tool health
analyze_tool_health flags a tool as slow when its p95 is above 2500 ms with at least 3 samples. It flags an error spike when there are at least 3 errors, at least 2x the previous window and an error rate of at least 10 percent. Every call over 2500 ms is marked DEGRADED.
After the run: a deterministic process eval
evaluate_agent_process is a guardrail eval over the journal with no LLM judge, so the same journal always gives the same verdict. It checks four rules:
- READ_FIRST: the session must read
get_change_historybefore its first change. Otherwise the agent acts on a picture of the account that a person may already have changed. - ONE_LEVER: one kind of change per test batch, where changes within 10 minutes form one batch. If a budget and a CPC ceiling move together, I cannot tell which one moved the result.
- AUTO_FIX_ALONE:
auto_fix_collisions_and_dupespauses keywords without a dry run, so it must never run together with other changes. Run alone, its effect is easy to attribute in the journal. - VERIFY_AFTER:
verify_changes_loggedmust run between 15 minutes and 24 hours after the last change. Google's change history lags about 15 minutes, so an earlier check would see nothing.
Changes made around the agent
The agent is not the only one who touches the account. verify_changes_logged reconciles Google's change_event history with the journal's MUTATION rows. A change with no matching MCP call is reported as OUTSIDE_CHANGES: a script, another agent or a person in the UI.
Before the next run: the preflight gate
preflight_log_check runs three checks, TOOL_HEALTH, OUTSIDE_CHANGES and AGENT_PROCESS, over the last 7 days or since the last accepted checkpoint (max 30).
OK opens the gate. ATTENTION keeps every ad tool shut until I have reviewed the findings and say "continue", after which the agent re-runs the check with acknowledge=True. Between 05.10 and 12.10.2026 the gate refused tools three times with PREFLIGHT_REQUIRED, and Google was not called.
The checker needed checking too (2026-10-05)
On 2026-10-05 two of the three preflight checks read the cloud journal, which started on 05.10, and the third read the local journal, which started on 01.10. As a result AGENT_PROCESS missed five violations. The fix: all three checks now choose the journal source the same way.
What the journal shows (01.10-13.10.2026, 13:12 UTC)
- 237 calls in 15 sessions: 216 reads and 21 changes.
- 236 calls carry a trace id.
- 1 change was rejected by the shield.
- Median latency 1.3 s, p95 5.6 s, with 37 calls marked DEGRADED.
- 0 retries.
Incidents the guardrails caught
Most rules in the table above started as a mistake. Each entry names the date, what happened and the rule it produced.
- 04.08.2026. A field-mask helper silently dropped a field set to False, so Google accepted an update that changed nothing. I caught it on a manual read-back and sent the update again with an explicit mask. Rule: every update sends an explicit field mask.
- 01.10.2026. The RSA deploy paused every ad when 2 or more existed and could drop the first headline. Rule: headline 1 must be the DKI headline, at most 3 RSAs stay enabled, and the oldest is paused in the same request.
- 01.10.2026. The bid tool changed ad group bids, which Maximize Clicks ignores. Rule: the tool now steps the campaign CPC ceiling instead.
- 05.10.2026. A ceiling change with a malformed direction was rejected by the Pydantic shield as REQUEST_REJECTED. Google was never called. Rule: the shield, not the prompt, decides what a valid request is.
- 05.10.2026. A non-numeric campaign ID reached a GAQL query and raised BAD_NUMBER. Rule: an ID validator (digits only) now runs before every read.
- 05.10.2026. The journal-source mismatch in the preflight, described above. Rule: all three checks choose the journal source the same way.
- 05.10 to 12.10.2026. Three PREFLIGHT_REQUIRED refusals: the gate stopped tools until the log check had passed. Rule: the gate itself, working as designed.
- 13.10.2026. The keyword tool rejected a request with 25 keywords (limit 20) and an unsupported country code before calling Google. Rule: read tools validate their input too.
Results on the live account
- Average CPC fell from 0.82 EUR (05.07-04.08.2026, 2 campaigns) to 0.47 EUR (18.08-17.09.2026, all 6 spending campaigns, 276.66 EUR for 592 clicks).
- The spend was about 8.92 EUR per day across DE, AT, ES and FR (18.08-17.09.2026).
- 909 search queries were analysed. A leak of 22.07 EUR (11 clicks, 0 sales) was found and its ad group paused on 04.08.2026. 36 duplicate keywords were paused.
Two honest notes. The two CPC windows cover different campaigns, so this is not a controlled comparison. And my sales happen on Etsy, which Google Ads does not attribute, so I make no ROAS or sales claim here.
The business side of the same system, written for shop owners: Google Ads MCP: how an AI agent runs your ads without burning the budget โ
Questions about building a Google Ads MCP server
What is a Google Ads MCP server?
Why not use Google's official Google Ads MCP server?
How do you stop an AI agent from overspending in Google Ads?
How do you trace what an AI agent did?
How do you build an MCP server in Python with FastMCP?
Can Claude Code manage Google Ads?
Tools used
I design the layer between an AI agent and a real API: which tools to expose, which rules to enforce in code and how to trace every call. Happy to talk through a specific system.