AdLoop

repository·main·Indexed 42 days ago

https://github.com/klosk/adloop

An MCP (Model Context Protocol) server that acts as an AI command center for managing Google Ads, Reddit Ads, GA4, and tracking code. Version 0.15.0 provides AI assistants with read and write access to marketing platforms via a hosted cloud service or self-hosted installation. It features a strict draft-preview-confirm workflow with safety guardrails, budget caps, and a compact mode to reduce AI context window usage during audits.

Tokens
37.7K
Snippets
82
Records
154
Agent score
51%

What's inside AdLoop

  1. Plan and execute Google Ads changes using the Draft-Confirm workflow

    main

    All Google Ads write tools follow a strict safety workflow to prevent accidental changes.

    The Workflow

    1. Draft: Call a draft_* tool (e.g., draft_campaign, draft_ad_group, draft_responsive_search_ad). This returns a preview with a plan_id but makes no changes.
    2. Review: Show the full preview to the user and wait for explicit approval.
    3. Dry Run: Call confirm_and_apply(plan_id=..., dry_run=true) to test the execution against the API.
    4. Apply: Only call confirm_and_apply(plan_id=..., dry_run=false) after explicit user confirmation.

    Safety Behaviors

    • Paused by Default: New campaigns, Reddit entities, and RSAs are created in a PAUSED state. They must be explicitly enabled.
    • Targeting Requirements: draft_campaign requires geo_target_ids and language_ids. It will reject drafts missing these.
    • Budget Caps: draft_campaign enforces a max_daily_budget safety cap and warns if the budget is below 5x the target CPA.
    • Irreversible Actions: remove_entity is irreversible. Always prefer pause_entity unless permanent removal is requested. remove_entity requires double confirmation.
    • Replacement vs. Appending: update_campaign replaces positive geo/language targets entirely. It does not append. However, negative geo exclusions are preserved during the swap.

    Configuration Overrides

    • require_dry_run: true: If set in config, the system will refuse dry_run=false until the user manually changes the config.
    • two_phase_apply: true: (Default on AdLoop Cloud) Refuses dry_run=false until the specific plan_id has successfully completed at least one dry_run=true pass.
    # Example workflow
    plan = draft_campaign(campaign_name='New Promo', daily_budget=50, ...)
    # ... user reviews plan ...
    confirm_and_apply(plan_id=plan.id, dry_run=True)
    # ... user confirms ...
    confirm_and_apply(plan_id=plan.id, dry_run=False)
  2. Understanding PMax Data Limitations and Google Recommendations

    main

    PMax Transparency

    The Google Ads API does not provide full channel-level breakdowns for Performance Max. While segments.ad_network_type returns values like SEARCH, CONTENT, YOUTUBE_SEARCH, YOUTUBE_WATCH, and MIXED, the MIXED value acts as a catch-all for most traffic. Avoid promising users exact splits between Search, Display, and YouTube.

    Evaluating Google Recommendations

    Google's auto-generated recommendations are optimized for Google's revenue, not necessarily advertiser ROI.

    • Budget/Broad Match: Always cross-reference these against actual conversion data before applying.
    • Bid Strategies: Recommendations to switch to Smart Bidding are generally considered sound.
    • Keywords: Keyword recommendations may be too broad and should be evaluated carefully.
  3. Understand the Google Ads Write workflow

    main

    All write operations in AdLoop follow a strict draft → preview → confirm workflow. No changes are executed on your account without explicit approval.

    1. Draft: Use tools like draft_campaign, draft_ad_group, or draft_responsive_search_ad to propose changes. These tools include safety checks (e.g., warning if RSA headline counts are too low or blocking BROAD match on Manual CPC campaigns).
    2. Preview: Review the proposed changes and the safety guardrails provided by the tool.
    3. Confirm: Execute the changes using the confirm_and_apply tool.
  4. How the AdLoop Safety Model works

    main

    AdLoop implements several safety mechanisms to prevent accidental ad spend:

    • Two-step writes: Mutations return a preview first. You must call confirm_and_apply to execute changes.
    • Dry-run by default: confirm_and_apply defaults to dry_run=true. You must explicitly set dry_run=false for real changes.
    • Two-phase apply (optional): If safety.two_phase_apply: true is configured, confirm_and_apply will refuse dry_run=false until a successful dry-run pass has been completed.
    • Budget caps: The server rejects any operation exceeding your configured maximum daily budget.
    • New entities are PAUSED: All new campaigns and ads are created in a PAUSED state by default.
    • Broad Match protection: draft_keywords prevents adding BROAD match keywords to campaigns that do not use Smart Bidding.
    • Audit logging: All operations, including dry runs, are logged to ~/.adloop/audit.log.
  5. How audience targeting and demographics differ

    main

    In Google Ads, Audiences and Demographics are distinct concepts:

    Audiences

    User lists like remarketing, in-market, or affinity segments. Use get_audience_performance to analyze them.

    Demographics

    Fixed buckets for Age, Gender, Parental Status, and Income. Use get_demographic_targeting and draft_demographic_targeting.

    Compatibility Matrix

    Audience typeSearchDisplayVideo (YouTube)Performance Max
    Remarketing / your-data lists✓✓✓signal only
    In-market segments✓✓✓signal only
    Affinity segments✓✓✓signal only
    Custom segments✗✓✓signal only
    Combined segments✓✗✗✗
    Detailed demographics✓✓✓signal only

    Key Constraints:

    • Custom segments cannot be attached to Search campaigns.
    • PMax uses audience segments as signals (hints), not hard targeting filters.
    • Demographic Exclusions: Campaign-level demographic criteria can only be exclusions (negative=True). Positive (narrowing) demographic targeting must be applied at the ad group level.
  6. Understand AdLoop data privacy and local execution

    main

    AdLoop is an open-source, locally-run tool designed to run as an MCP (Model Context Protocol) server inside your code editor. It has no backend, no cloud services, and no telemetry.

    Key privacy characteristics:

    • Local Execution: All data processing happens on your machine.
    • No Telemetry: AdLoop does not track usage, collect crash reports, or transmit data to developers.
    • Direct API Communication: Network requests are made exclusively to Google's APIs on your behalf; no intermediate servers are used.
  7. Compare AdLoop Cloud vs. Self-hosted

    main

    Choose between the hosted Cloud version or the self-hosted repository based on your setup requirements and privacy needs.

    Feature☁️ AdLoop Cloud🛠️ Self-hosted
    SetupConnect Google in two clicks~5 min: own Google Cloud project + adloop init
    Google Cloud projectNot neededRequired (free)
    Ads API accessNot neededGranted to your Cloud project
    Works withclaude.ai, ChatGPT, Claude Code, Cursor, GeminiClaude Code, Cursor, Claude Desktop, any local MCP client
    Data PrivacyEU servers (Germany), GDPR-first, DPA included100% your machine — nothing leaves it
    UpdatesAutomaticpip install -U adloop
    PriceFree plan (no card); paid plans for volumeFree forever (MIT)
  8. Use Compact Mode for Google Ads tools

    main

    Several Google Ads read tools support a compact=true parameter. When enabled, these tools return account totals, breakdowns, top-10 rows, and pre-computed 'offender lists' (e.g., zero-conversion spenders, low-QS keywords, negative-keyword candidates, thin RSAs) instead of every raw row. This reduces response size by approximately 90%, making it ideal for account audits where you want to avoid flooding an AI's context window with raw data.

    Supported tools with compact=true:

    • get_campaign_performance
    • get_keyword_performance
    • get_search_terms
    • get_ad_performance
  9. GAQL (Google Ads Query Language) Syntax and Rules

    main

    GAQL is a SQL-like language used to query Google Ads data. When using run_gaql, adhere to these critical rules to avoid errors:

    • No SELECT *: You must explicitly name every field you want to retrieve.
    • Ordering Constraint: Any field used in an ORDER BY clause must also be present in your SELECT clause. For example, ORDER BY metrics.cost_micros will fail if metrics.cost_micros is not selected.
    • Field Compatibility: Certain resource attributes cannot be combined with specific metrics or segments. If a query fails, verify the field compatibility for that resource.
    • Micros Conversion: Values for cost_micros are returned in micros. To get the actual currency amount, divide the value by 1,000,000. (Note: Dedicated read tools like get_campaign_performance handle this conversion automatically; only run_gaql returns raw micros).
    • Date Segments: When selecting segments.date, results are broken down by day. The search_term_view resource always requires a date segment in the WHERE clause.
    SELECT field1, field2, ...
    FROM resource
    WHERE condition
    ORDER BY field [ASC|DESC]
    LIMIT n
  10. Interpreting Data Discrepancies between Google Ads and GA4

    main

    When diagnosing tracking issues, you must account for GDPR cookie consent, which creates a natural discrepancy between Google Ads and GA4 data.

    • Google Ads: Counts all clicks regardless of user consent.
    • GA4: Only records sessions and events for users who accept analytics cookies.
    • Expected Ratio: A ratio of 2:1 to 5:1 (clicks:sessions) is normal when consent banners are present. This is not necessarily a tracking bug.

    Diagnostic Workflow

    Before flagging tracking as broken, evaluate the following:

    1. Consent Rejection: If Ads shows 10 clicks but GA4 shows 3 sessions, this is likely due to consent rejection.
    2. Zero Sessions: If GA4 shows zero sessions from paid traffic, check UTM parameters and GA4 filters in addition to consent.
    3. Systemic Failure: Only flag tracking as broken if the discrepancy cannot be explained by consent (e.g., GA4 shows zero sessions for all traffic sources, including organic).

    If GA4 data appears closer to Google Ads data than expected, the site may be using Consent Mode, which sends cookieless pings to GA4. You can verify this by searching the codebase for gtag('consent', ...) calls.

  11. Connect AdLoop to Claude Code

    main

    You can add AdLoop to Claude Code using the CLI or by editing your .mcp.json file.

    Using CLI:

    claude mcp add --transport stdio adloop -- /absolute/path/to/adloop/.venv/bin/python -m adloop

    Using .mcp.json:

    {
      "mcpServers": {
        "adloop": {
          "command": "/absolute/path/to/adloop/.venv/bin/python",
          "args": ["-m", "adloop"]
        }
      }
    }

    Install Orchestration Rules: After connecting, run the following command to install slash commands (prefixed adloop-*) and orchestration rules:

    adloop install-rules

    Install Modes:

    • inline (default): Embeds full rules into ~/.claude/CLAUDE.md. Adds ~10K tokens to every session.
    • lazy: Use adloop install-rules --lazy. Places a small directive in CLAUDE.md pointing to ~/.claude/rules/adloop.md. The LLM only reads the rules when AdLoop tools are in scope, saving tokens.

    Maintenance:

    • Refresh rules after upgrade: adloop update-rules
    • Remove rules: adloop uninstall-rules
    claude mcp add --transport stdio adloop -- /absolute/path/to/adloop/.venv/bin/python -m adloop
    
    adloop install-rules
  12. Trim toolset context footprint using ADLOOP_TOOLSETS

    main

    To reduce the token cost in MCP clients (like Claude, ChatGPT, or Cursor), you can limit the number of tools loaded by setting the ADLOOP_TOOLSETS environment variable. This prevents the model from loading the entire 18k token catalog at the start of every session.

    Set the variable in your MCP client's env block using a comma-separated list of toolset names.

    Available Toolsets:

    • ads: Google Ads reads, writes, and planning (Keyword Planner).
    • ga4: Google Analytics reports, realtime, and key events.
    • tracking: Cross-channel attribution and tracking code generation.
    • gtm: Google Tag Manager audits and reads.
    • gsc: Search Console reads.
    • web: PageSpeed / Core Web Vitals.
    • merchant: Merchant Center feed health.
    • reddit: Reddit Ads reads, writes, and planning.

    Note: health_check and confirm_and_apply are always included. Unsetting the variable loads the full catalog.

    "env": { "ADLOOP_TOOLSETS": "ads,ga4" }