adloop 0.41.2__tar.gz → 0.41.4__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. {adloop-0.41.2 → adloop-0.41.4}/PKG-INFO +1 -1
  2. {adloop-0.41.2 → adloop-0.41.4}/pyproject.toml +1 -1
  3. {adloop-0.41.2 → adloop-0.41.4}/pyproject.toml.orig +1 -1
  4. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/ads/currency.py +17 -10
  5. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/ads/image_fetch.py +3 -3
  6. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/ads/write.py +59 -8
  7. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/reddit/read.py +8 -3
  8. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/reddit/write.py +108 -22
  9. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/server.py +20 -4
  10. {adloop-0.41.2 → adloop-0.41.4}/README.md +0 -0
  11. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/__init__.py +0 -0
  12. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/__main__.py +0 -0
  13. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/_mcp_patches.py +0 -0
  14. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/ads/__init__.py +0 -0
  15. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/ads/ai_max.py +0 -0
  16. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/ads/assets.py +0 -0
  17. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/ads/audiences.py +0 -0
  18. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/ads/brands.py +0 -0
  19. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/ads/campaign_settings.py +0 -0
  20. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/ads/client.py +0 -0
  21. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/ads/conversion_actions.py +0 -0
  22. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/ads/custom_conversion_goals.py +0 -0
  23. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/ads/enums.py +0 -0
  24. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/ads/forecast.py +0 -0
  25. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/ads/gaql.py +0 -0
  26. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/ads/pmax.py +0 -0
  27. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/ads/read.py +0 -0
  28. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/ads/recommendation_subscriptions.py +0 -0
  29. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/ads/recommendations.py +0 -0
  30. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/ads/shopping.py +0 -0
  31. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/ads/snippet_headers.py +0 -0
  32. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/ads/validate_only.py +0 -0
  33. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/auth.py +0 -0
  34. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/cli.py +0 -0
  35. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/config.py +0 -0
  36. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/conversion_setup.py +0 -0
  37. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/crossref.py +0 -0
  38. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/diagnostics.py +0 -0
  39. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/ga4/__init__.py +0 -0
  40. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/ga4/admin.py +0 -0
  41. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/ga4/annotations.py +0 -0
  42. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/ga4/attribution.py +0 -0
  43. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/ga4/audit.py +0 -0
  44. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/ga4/client.py +0 -0
  45. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/ga4/definitions.py +0 -0
  46. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/ga4/funnels.py +0 -0
  47. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/ga4/reports.py +0 -0
  48. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/ga4/retention.py +0 -0
  49. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/ga4/suggest.py +0 -0
  50. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/ga4/tracking.py +0 -0
  51. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/ga4/write.py +0 -0
  52. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/gsc/__init__.py +0 -0
  53. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/gsc/client.py +0 -0
  54. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/gsc/reports.py +0 -0
  55. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/gtm/__init__.py +0 -0
  56. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/gtm/client.py +0 -0
  57. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/gtm/entities.py +0 -0
  58. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/gtm/read.py +0 -0
  59. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/gtm/write.py +0 -0
  60. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/merchant/__init__.py +0 -0
  61. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/merchant/client.py +0 -0
  62. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/merchant/read.py +0 -0
  63. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/microsoft_ads/__init__.py +0 -0
  64. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/microsoft_ads/auth.py +0 -0
  65. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/microsoft_ads/client.py +0 -0
  66. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/microsoft_ads/manage/__init__.py +0 -0
  67. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/microsoft_ads/manage/_common.py +0 -0
  68. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/microsoft_ads/manage/ad_groups.py +0 -0
  69. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/microsoft_ads/manage/ads.py +0 -0
  70. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/microsoft_ads/manage/campaigns.py +0 -0
  71. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/microsoft_ads/manage/extensions.py +0 -0
  72. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/microsoft_ads/manage/negatives.py +0 -0
  73. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/microsoft_ads/manage/removal.py +0 -0
  74. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/microsoft_ads/manage/targeting.py +0 -0
  75. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/microsoft_ads/read.py +0 -0
  76. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/microsoft_ads/write.py +0 -0
  77. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/oauth_redirect.py +0 -0
  78. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/pagespeed.py +0 -0
  79. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/reddit/__init__.py +0 -0
  80. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/reddit/auth.py +0 -0
  81. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/reddit/client.py +0 -0
  82. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/reddit/schedule.py +0 -0
  83. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/rules/__init__.py +0 -0
  84. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/rules/adloop.md +0 -0
  85. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/rules/commands/analyze-performance.md +0 -0
  86. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/rules/commands/budget-plan.md +0 -0
  87. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/rules/commands/create-ad.md +0 -0
  88. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/rules/commands/create-campaign.md +0 -0
  89. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/rules/commands/diagnose-tracking.md +0 -0
  90. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/rules/commands/optimize-campaign.md +0 -0
  91. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/rules_install.py +0 -0
  92. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/runtime.py +0 -0
  93. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/safety/__init__.py +0 -0
  94. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/safety/approval.py +0 -0
  95. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/safety/approval_card.html +0 -0
  96. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/safety/audit.py +0 -0
  97. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/safety/guards.py +0 -0
  98. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/safety/outcomes.py +0 -0
  99. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/safety/preview.py +0 -0
  100. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/tracking.py +0 -0
  101. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/upload_card.html +0 -0
  102. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/uploads.py +0 -0
  103. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/views/__init__.py +0 -0
  104. {adloop-0.41.2 → adloop-0.41.4}/src/adloop/views/performance.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: adloop
3
- Version: 0.41.2
3
+ Version: 0.41.4
4
4
  Summary: Google Ads MCP server for Claude, ChatGPT and Cursor, with Reddit Ads, GA4 and Tag Manager. Every change is previewed first.
5
5
  Keywords: mcp,mcp-server,google-ads,google-ads-mcp,reddit-ads,google-analytics,ga4,claude,chatgpt,cursor,marketing
6
6
  Author: Daniel Klose
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "adloop"
3
- version = "0.41.2"
3
+ version = "0.41.4"
4
4
  description = "Google Ads MCP server for Claude, ChatGPT and Cursor, with Reddit Ads, GA4 and Tag Manager. Every change is previewed first."
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.11"
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "adloop"
3
- version = "0.41.2"
3
+ version = "0.41.4"
4
4
  description = "Google Ads MCP server for Claude, ChatGPT and Cursor, with Reddit Ads, GA4 and Tag Manager. Every change is previewed first."
5
5
  readme = "README.md"
6
6
  authors = [
@@ -37,21 +37,26 @@ _CURRENCY_SYMBOLS: dict[str, str] = {
37
37
  "UAH": "\u20b4",
38
38
  }
39
39
 
40
- # Module-level cache: customer_id -> currency_code (one API call per session)
41
- _cache: dict[str, str] = {}
40
+ # Module-level cache: (tenant, customer_id) -> currency_code (one API call
41
+ # per session). The tenant is part of the key because a hosted server runs
42
+ # many tenants in one process: what one of them reads, or fails to read,
43
+ # about an account must never be served to another.
44
+ _cache: dict[tuple[str, str], str] = {}
42
45
 
43
46
 
44
47
  def get_currency_code(config: AdLoopConfig, customer_id: str) -> str:
45
48
  """Detect the account's currency via ``customer.currency_code``.
46
49
 
47
- Result is cached per *customer_id* for the lifetime of the server process.
48
- Falls back to ``"EUR"`` on any error.
50
+ A successful lookup is cached per tenant and *customer_id* for the
51
+ lifetime of the server process. Falls back to ``"EUR"`` on any error;
52
+ the fallback is not cached, so a passing failure does not stick.
49
53
  """
50
54
  from adloop.ads.client import normalize_customer_id
55
+ from adloop.runtime import current_tenant
51
56
 
52
- cid = normalize_customer_id(customer_id)
53
- if cid in _cache:
54
- return _cache[cid]
57
+ key = (current_tenant(), normalize_customer_id(customer_id))
58
+ if key in _cache:
59
+ return _cache[key]
55
60
 
56
61
  try:
57
62
  from adloop.ads.gaql import execute_query
@@ -59,11 +64,13 @@ def get_currency_code(config: AdLoopConfig, customer_id: str) -> str:
59
64
  rows = execute_query(
60
65
  config, customer_id, "SELECT customer.currency_code FROM customer LIMIT 1"
61
66
  )
62
- code = (rows[0].get("customer.currency_code", "EUR") if rows else "EUR") or "EUR"
67
+ code = rows[0].get("customer.currency_code") if rows else None
63
68
  except Exception:
64
- code = "EUR"
69
+ code = None
70
+ if not code:
71
+ return "EUR"
65
72
 
66
- _cache[cid] = code
73
+ _cache[key] = code
67
74
  return code
68
75
 
69
76
 
@@ -3,9 +3,9 @@
3
3
  The fetched bytes are uploaded into the user's Google Ads account, where
4
4
  they become visible. A fetch that could be steered at an internal address
5
5
  (cloud metadata, a database admin page, a loopback service) would therefore
6
- be a way to exfiltrate whatever lives there. So, unlike the up/down
7
- reachability check for landing pages, this fetcher closes the DNS-rebinding
8
- gap:
6
+ be a way to exfiltrate whatever lives there. So this fetcher closes the
7
+ DNS-rebinding gap (the reachability check for landing pages reuses its
8
+ pinned connections):
9
9
 
10
10
  * the hostname is resolved exactly once per request, and every resolved
11
11
  address must be public;
@@ -216,12 +216,10 @@ def _ssrf_error(url: str) -> str | None:
216
216
  pointing at such addresses could never serve anyway. Returns an error
217
217
  string, or None if the URL looks safe to fetch.
218
218
 
219
- Note: the fetch re-resolves DNS after this check, so a hostile DNS
220
- server could still rebind between check and fetch — acceptable here
221
- because the fetch result is only an up/down signal, never returned
222
- to the caller. Fetches whose bytes ARE used (image assets) go through
223
- ``adloop.ads.image_fetch``, which pins the connection to the checked
224
- address.
219
+ This check is the readable refusal. What holds against a hostile DNS
220
+ server (one answer for this check, another for the fetch) is the opener
221
+ from ``_build_public_only_opener``: it resolves the name once more,
222
+ refuses a non-public answer and connects to exactly that address.
225
223
  """
226
224
  import ipaddress
227
225
  import socket
@@ -262,8 +260,48 @@ def _ssrf_error(url: str) -> str | None:
262
260
  return None
263
261
 
264
262
 
263
+ def _pinned_connection_factory(scheme: str):
264
+ """A connection class for urllib that dials only a checked, public address.
265
+
266
+ urllib resolves the hostname when it connects, after any check made
267
+ beforehand, so a DNS server can answer the check with a public address
268
+ and the connection with an internal one (DNS rebinding). This factory
269
+ resolves once, refuses a non-public answer and connects to that very
270
+ address; the request keeps its Host header, and TLS still verifies the
271
+ certificate against the hostname.
272
+ """
273
+ import urllib.error
274
+ from urllib.parse import urlsplit
275
+
276
+ from adloop.ads import image_fetch
277
+
278
+ def connect(host, timeout=image_fetch.TIMEOUT_SECONDS, **kwargs):
279
+ parts = urlsplit(f"//{host}")
280
+ name = parts.hostname or host
281
+ port = parts.port or (443 if scheme == "https" else 80)
282
+ try:
283
+ pinned_ip = image_fetch.resolve_public_address(name, port)
284
+ except image_fetch.ImageFetchError as e:
285
+ raise urllib.error.URLError(str(e)) from e
286
+ if scheme == "https":
287
+ return image_fetch._PinnedHTTPSConnection(
288
+ name, port, pinned_ip=pinned_ip, timeout=timeout,
289
+ context=kwargs.get("context") or image_fetch._tls_context(),
290
+ )
291
+ return image_fetch._PinnedHTTPConnection(name, port, pinned_ip=pinned_ip, timeout=timeout)
292
+
293
+ return connect
294
+
295
+
265
296
  def _build_public_only_opener():
266
- """Return a urllib opener that re-checks every redirect hop for SSRF."""
297
+ """Return a urllib opener that can only reach public addresses.
298
+
299
+ Every redirect hop is checked, and every connection (the first request
300
+ and each redirect) goes to an address that was resolved once and found
301
+ public, so the check cannot be passed with one DNS answer and the fetch
302
+ made with another. Behind an HTTP proxy the proxy does the resolving,
303
+ so there the stock connections are kept.
304
+ """
267
305
  import urllib.error
268
306
  import urllib.request
269
307
 
@@ -274,7 +312,20 @@ def _build_public_only_opener():
274
312
  raise urllib.error.URLError(f"redirect blocked: {err}")
275
313
  return super().redirect_request(req, fp, code, msg, headers, newurl)
276
314
 
277
- return urllib.request.build_opener(_PublicOnlyRedirectHandler)
315
+ if urllib.request.getproxies():
316
+ return urllib.request.build_opener(_PublicOnlyRedirectHandler)
317
+
318
+ class _PinnedHTTPHandler(urllib.request.HTTPHandler):
319
+ def http_open(self, req):
320
+ return self.do_open(_pinned_connection_factory("http"), req)
321
+
322
+ class _PinnedHTTPSHandler(urllib.request.HTTPSHandler):
323
+ def https_open(self, req):
324
+ return self.do_open(_pinned_connection_factory("https"), req)
325
+
326
+ return urllib.request.build_opener(
327
+ _PublicOnlyRedirectHandler, _PinnedHTTPHandler, _PinnedHTTPSHandler
328
+ )
278
329
 
279
330
 
280
331
  # Statuses that say nothing about whether the landing page is any good:
@@ -91,7 +91,9 @@ _STANDARD_PIXEL_EVENTS = (
91
91
  "custom",
92
92
  )
93
93
 
94
- _account_meta_cache: dict[str, dict] = {}
94
+ # Keyed by (tenant, ad account): a hosted server runs many tenants in one
95
+ # process, and one tenant must not be served what another's login read.
96
+ _account_meta_cache: dict[tuple[str, str], dict] = {}
95
97
 
96
98
 
97
99
  # ---------------------------------------------------------------------------
@@ -116,7 +118,10 @@ def resolve_account(config: AdLoopConfig, ad_account_id: str = "") -> str:
116
118
 
117
119
  def account_meta(config: AdLoopConfig, ad_account_id: str) -> dict:
118
120
  """Currency + time zone of an ad account, cached per process."""
119
- cached = _account_meta_cache.get(ad_account_id)
121
+ from adloop.runtime import current_tenant
122
+
123
+ key = (current_tenant(), ad_account_id)
124
+ cached = _account_meta_cache.get(key)
120
125
  if cached is not None:
121
126
  return cached
122
127
  data = data_of(reddit_get(config, f"ad_accounts/{ad_account_id}"))
@@ -127,7 +132,7 @@ def account_meta(config: AdLoopConfig, ad_account_id: str) -> dict:
127
132
  "business_id": str(data.get("business_id") or ""),
128
133
  "admin_approval": str(data.get("admin_approval") or ""),
129
134
  }
130
- _account_meta_cache[ad_account_id] = meta
135
+ _account_meta_cache[key] = meta
131
136
  return meta
132
137
 
133
138
 
@@ -18,6 +18,7 @@ entity after review, exactly like new Google campaigns and RSAs.
18
18
 
19
19
  from __future__ import annotations
20
20
 
21
+ import re
21
22
  from datetime import datetime, timezone
22
23
  from typing import TYPE_CHECKING, Any
23
24
 
@@ -151,15 +152,46 @@ def _iso_time(value: str, field: str, errors: list[str]) -> str:
151
152
  return candidate
152
153
 
153
154
 
155
+ def _parse_time(value: str) -> datetime:
156
+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
157
+ return parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc)
158
+
159
+
154
160
  def _days_between(start: str, end: str) -> int:
161
+ """Whole days a lifetime budget still has to be spent in.
162
+
163
+ Counted from now when the schedule already started: a budget is spent in
164
+ the days that are left, so days that have passed must not thin out its
165
+ per-day share. An unreadable schedule counts as one day.
166
+ """
167
+ now = datetime.now(timezone.utc)
155
168
  try:
156
- s = datetime.fromisoformat(start.replace("Z", "+00:00")) if start else datetime.now(timezone.utc)
157
- e = datetime.fromisoformat(end.replace("Z", "+00:00"))
169
+ s = max(_parse_time(start), now) if start else now
170
+ e = _parse_time(end)
158
171
  except ValueError:
159
172
  return 1
160
173
  return max(int((e - s).total_seconds() // 86400), 1)
161
174
 
162
175
 
176
+ def _rescheduled_equivalent(current: dict, start_time: str, end_time: str) -> float | None:
177
+ """Per-day share of an existing lifetime budget under a new schedule.
178
+
179
+ Moving the end date closer squeezes the same budget into fewer days, so a
180
+ schedule change on a lifetime budget is a budget change for the cap. What
181
+ was already spent is not known here; the whole budget is counted.
182
+ """
183
+ if current.get("goal_type") != "LIFETIME_SPEND" or not (start_time or end_time):
184
+ return None
185
+ lifetime = from_micro(current.get("goal_value"))
186
+ if not lifetime:
187
+ return None
188
+ days = _days_between(
189
+ start_time or str(current.get("start_time") or ""),
190
+ end_time or str(current.get("end_time") or ""),
191
+ )
192
+ return round(float(lifetime) / days, 2)
193
+
194
+
163
195
  def _daily_equivalent(
164
196
  *, daily_budget: float | None, lifetime_budget: float | None, start_time: str, end_time: str,
165
197
  errors: list[str],
@@ -215,17 +247,45 @@ def _store(plan_kwargs: dict, *, warnings: list[str] | None = None) -> dict:
215
247
  return store_draft(ChangePlan(platform=PLATFORM, **plan_kwargs), warnings=warnings)
216
248
 
217
249
 
218
- def _fetch(config: AdLoopConfig, entity_type: str, entity_id: str) -> dict:
219
- collection = _COLLECTIONS[entity_type]
220
- return data_of(reddit_get(config, f"{collection}/{entity_id}"))
250
+ _ENTITY_ID = re.compile(r"[A-Za-z0-9_]+")
251
+
252
+
253
+ def _in_account(config: AdLoopConfig, entity_type: str, entity: dict, account: str) -> bool:
254
+ """Whether a fetched campaign, ad group or ad belongs to ``account``."""
255
+ owner = str(entity.get("ad_account_id") or "").strip()
256
+ if owner:
257
+ return owner == account
258
+ # No owner on the entity: the account's own listing decides.
259
+ from adloop.reddit.client import reddit_get_all
260
+
261
+ listed = reddit_get_all(config, f"ad_accounts/{account}/{_COLLECTIONS[entity_type]}")
262
+ return any(str(row.get("id")) == str(entity.get("id")) for row in listed)
263
+
221
264
 
265
+ def _fetch(config: AdLoopConfig, entity_type: str, entity_id: str, account: str) -> dict:
266
+ """The entity, or ``{}`` when it is not one of ``account``'s.
222
267
 
223
- def _exists(config: AdLoopConfig, entity_type: str, entity_id: str) -> bool:
224
- """Whether the entity exists; a 404 is a no, other errors propagate."""
268
+ Reddit addresses campaigns, ad groups and ads by id alone, without the ad
269
+ account in the path, and one Reddit login often reaches several accounts.
270
+ A change is drafted, previewed, capped and logged for one account, so an
271
+ id from another account is treated as not found. Ids are checked too:
272
+ they go into the request path.
273
+ """
274
+ entity_id = str(entity_id or "")
275
+ if not account or not _ENTITY_ID.fullmatch(entity_id):
276
+ return {}
277
+ entity = data_of(reddit_get(config, f"{_COLLECTIONS[entity_type]}/{entity_id}"))
278
+ if not entity or not _in_account(config, entity_type, entity, account):
279
+ return {}
280
+ return entity
281
+
282
+
283
+ def _exists(config: AdLoopConfig, entity_type: str, entity_id: str, account: str) -> bool:
284
+ """Whether the entity exists in ``account``; a 404 is a no, other errors propagate."""
225
285
  from adloop.reddit.auth import RedditApiError
226
286
 
227
287
  try:
228
- return bool(_fetch(config, entity_type, entity_id))
288
+ return bool(_fetch(config, entity_type, entity_id, account))
229
289
  except RedditApiError as e:
230
290
  if getattr(e, "status", None) == 404:
231
291
  return False
@@ -283,7 +343,7 @@ def _draft_status(
283
343
  if errors:
284
344
  return _validation_error(errors)
285
345
 
286
- current = _fetch(config, entity_type, entity_id)
346
+ current = _fetch(config, entity_type, entity_id, account)
287
347
  if not current:
288
348
  return {"error": f"Reddit {entity_type} '{entity_id}' was not found."}
289
349
  warnings: list[str] = []
@@ -390,7 +450,7 @@ def update_reddit_campaign(
390
450
  if errors:
391
451
  return _validation_error(errors)
392
452
 
393
- current = _fetch(config, "campaign", campaign_id)
453
+ current = _fetch(config, "campaign", campaign_id, account)
394
454
  if not current:
395
455
  return {"error": f"Reddit campaign '{campaign_id}' was not found."}
396
456
  meta = account_meta(config, account)
@@ -415,6 +475,12 @@ def update_reddit_campaign(
415
475
  errors.append("Bid settings live on the ad groups of a non-CBO campaign.")
416
476
  if errors:
417
477
  return _validation_error(errors)
478
+ if goal_value is None:
479
+ daily_equivalent = _rescheduled_equivalent(current, start_time, end_time)
480
+ try:
481
+ _budget_cap(daily_equivalent, config, meta["currency"])
482
+ except SafetyViolation as e:
483
+ return {"error": f"{e} The new schedule spreads the lifetime budget over fewer days."}
418
484
 
419
485
  patch: dict[str, Any] = {}
420
486
  display: dict[str, Any] = {}
@@ -792,7 +858,7 @@ def update_reddit_ad_group(
792
858
  if errors:
793
859
  return _validation_error(errors)
794
860
 
795
- current = _fetch(config, "ad_group", ad_group_id)
861
+ current = _fetch(config, "ad_group", ad_group_id, account)
796
862
  if not current:
797
863
  return {"error": f"Reddit ad group '{ad_group_id}' was not found."}
798
864
  meta = account_meta(config, account)
@@ -815,6 +881,12 @@ def update_reddit_ad_group(
815
881
  )
816
882
  if errors:
817
883
  return _validation_error(errors)
884
+ if goal_value is None:
885
+ daily_equivalent = _rescheduled_equivalent(current, start_time, end_time)
886
+ try:
887
+ _budget_cap(daily_equivalent, config, meta["currency"])
888
+ except SafetyViolation as e:
889
+ return {"error": f"{e} The new schedule spreads the lifetime budget over fewer days."}
818
890
 
819
891
  patch: dict[str, Any] = {}
820
892
  display: dict[str, Any] = {}
@@ -949,7 +1021,7 @@ def update_reddit_ad(
949
1021
  if errors:
950
1022
  return _validation_error(errors)
951
1023
 
952
- current = _fetch(config, "ad", ad_id)
1024
+ current = _fetch(config, "ad", ad_id, account)
953
1025
  if not current:
954
1026
  return {"error": f"Reddit ad '{ad_id}' was not found."}
955
1027
  if click_url and current.get("post_id"):
@@ -1299,7 +1371,7 @@ def draft_reddit_ad_group(
1299
1371
  if errors:
1300
1372
  return _validation_error(errors)
1301
1373
 
1302
- campaign = _fetch(config, "campaign", campaign_id)
1374
+ campaign = _fetch(config, "campaign", campaign_id, account)
1303
1375
  if not campaign:
1304
1376
  return {"error": f"Reddit campaign '{campaign_id}' was not found."}
1305
1377
  is_cbo = bool(campaign.get("is_campaign_budget_optimization"))
@@ -1555,7 +1627,7 @@ def _draft_ad_from_post(
1555
1627
  if errors:
1556
1628
  return _validation_error(errors)
1557
1629
 
1558
- ad_group = _fetch(config, "ad_group", ad_group_id)
1630
+ ad_group = _fetch(config, "ad_group", ad_group_id, account)
1559
1631
  if not ad_group:
1560
1632
  return {"error": f"Reddit ad group '{ad_group_id}' was not found."}
1561
1633
 
@@ -1866,7 +1938,7 @@ def draft_reddit_ad(
1866
1938
  if errors:
1867
1939
  return _validation_error(errors)
1868
1940
 
1869
- ad_group = _fetch(config, "ad_group", ad_group_id)
1941
+ ad_group = _fetch(config, "ad_group", ad_group_id, account)
1870
1942
  if not ad_group:
1871
1943
  return {"error": f"Reddit ad group '{ad_group_id}' was not found."}
1872
1944
 
@@ -2060,7 +2132,7 @@ def draft_reddit_custom_audience(
2060
2132
  f"(known: {', '.join(sorted(pixels)) or 'none'})"
2061
2133
  ])
2062
2134
  else:
2063
- missing = [c for c in payload["engagement_audience_config"]["campaign_ids"] if not _exists(config, "campaign", c)]
2135
+ missing = [c for c in payload["engagement_audience_config"]["campaign_ids"] if not _exists(config, "campaign", c, account)]
2064
2136
  if missing:
2065
2137
  return _validation_error([f"campaigns not found in this account: {', '.join(missing)}"])
2066
2138
 
@@ -2085,6 +2157,13 @@ def draft_reddit_custom_audience(
2085
2157
  # ---------------------------------------------------------------------------
2086
2158
 
2087
2159
 
2160
+ # Plans that change an existing campaign, ad group or ad by its id.
2161
+ _ENTITY_OPERATIONS = frozenset({
2162
+ "reddit_set_status", "reddit_archive_entity", "reddit_update_ad",
2163
+ "reddit_update_campaign", "reddit_update_ad_group",
2164
+ })
2165
+
2166
+
2088
2167
  def is_reddit_plan(plan: ChangePlan) -> bool:
2089
2168
  return str(plan.operation or "").startswith(OPERATION_PREFIX)
2090
2169
 
@@ -2105,20 +2184,20 @@ def preflight(config: AdLoopConfig, plan: ChangePlan) -> dict:
2105
2184
  checks: dict[str, Any] = {"ad_account_id": account, "currency": meta["currency"]}
2106
2185
 
2107
2186
  if plan.operation in ("reddit_set_status", "reddit_archive_entity"):
2108
- current = _fetch(config, plan.entity_type, plan.entity_id)
2187
+ current = _fetch(config, plan.entity_type, plan.entity_id, account)
2109
2188
  if not current:
2110
2189
  raise ValueError(f"{plan.entity_type} '{plan.entity_id}' no longer exists.")
2111
2190
  checks["entity"] = current.get("name")
2112
2191
  checks["configured_status_now"] = current.get("configured_status")
2113
2192
  checks["already_in_target_status"] = current.get("configured_status") == changes.get("target_status")
2114
2193
  elif plan.operation == "reddit_update_ad":
2115
- current = _fetch(config, "ad", plan.entity_id)
2194
+ current = _fetch(config, "ad", plan.entity_id, account)
2116
2195
  if not current:
2117
2196
  raise ValueError(f"ad '{plan.entity_id}' no longer exists.")
2118
2197
  checks["entity"] = current.get("name")
2119
2198
  checks["post_id"] = current.get("post_id")
2120
2199
  elif plan.operation in ("reddit_update_campaign", "reddit_update_ad_group"):
2121
- current = _fetch(config, plan.entity_type, plan.entity_id)
2200
+ current = _fetch(config, plan.entity_type, plan.entity_id, account)
2122
2201
  if not current:
2123
2202
  raise ValueError(f"{plan.entity_type} '{plan.entity_id}' no longer exists.")
2124
2203
  checks["entity"] = current.get("name")
@@ -2141,7 +2220,7 @@ def preflight(config: AdLoopConfig, plan: ChangePlan) -> dict:
2141
2220
  checks["funding_instrument_id"] = (changes.get("payload") or {}).get("funding_instrument_id")
2142
2221
  elif plan.operation == "reddit_create_ad_group":
2143
2222
  campaign_id = (changes.get("payload") or {}).get("campaign_id", "")
2144
- campaign = _fetch(config, "campaign", campaign_id)
2223
+ campaign = _fetch(config, "campaign", campaign_id, account)
2145
2224
  if not campaign:
2146
2225
  raise ValueError(f"campaign '{campaign_id}' no longer exists.")
2147
2226
  checks["campaign"] = campaign.get("name")
@@ -2150,7 +2229,7 @@ def preflight(config: AdLoopConfig, plan: ChangePlan) -> dict:
2150
2229
  checks["budget_cap_ok"] = True
2151
2230
  elif plan.operation == "reddit_create_ad":
2152
2231
  ad_group_id = (changes.get("ad") or {}).get("ad_group_id", "")
2153
- group = _fetch(config, "ad_group", ad_group_id)
2232
+ group = _fetch(config, "ad_group", ad_group_id, account)
2154
2233
  if not group:
2155
2234
  raise ValueError(f"ad group '{ad_group_id}' no longer exists.")
2156
2235
  checks["ad_group"] = group.get("name")
@@ -2169,7 +2248,7 @@ def preflight(config: AdLoopConfig, plan: ChangePlan) -> dict:
2169
2248
  raise ValueError(f"pixel '{pixel_ids[0]}' is no longer available to this ad account.")
2170
2249
  checks["pixel_id"] = pixel_ids[0]
2171
2250
  for campaign_id in (payload.get("engagement_audience_config") or {}).get("campaign_ids") or []:
2172
- if not _exists(config, "campaign", campaign_id):
2251
+ if not _exists(config, "campaign", campaign_id, account):
2173
2252
  raise ValueError(f"campaign '{campaign_id}' no longer exists.")
2174
2253
  checks["audience_name"] = payload.get("name")
2175
2254
  else:
@@ -2189,6 +2268,13 @@ def apply_plan(config: AdLoopConfig, plan: ChangePlan) -> dict:
2189
2268
  account = changes.get("ad_account_id") or plan.customer_id
2190
2269
  op = plan.operation
2191
2270
 
2271
+ if op in _ENTITY_OPERATIONS and not _fetch(config, plan.entity_type, plan.entity_id, account):
2272
+ # The dry run checked this too, but it is the apply that changes
2273
+ # something, and Reddit would take the id whatever account it is in.
2274
+ raise ValueError(
2275
+ f"{plan.entity_type} '{plan.entity_id}' is not in Reddit ad account {account}; nothing was changed."
2276
+ )
2277
+
2192
2278
  if op in ("reddit_set_status", "reddit_archive_entity"):
2193
2279
  collection = _COLLECTIONS[plan.entity_type]
2194
2280
  result = reddit_patch(
@@ -11,7 +11,7 @@ from fastmcp import FastMCP
11
11
  from fastmcp.server.middleware import Middleware
12
12
  from fastmcp.utilities.docstring_parsing import parse_docstring
13
13
  from mcp.types import Icon, ToolAnnotations
14
- from pydantic import BeforeValidator
14
+ from pydantic import BeforeValidator, TypeAdapter
15
15
 
16
16
  from adloop import diagnostics
17
17
  from adloop.runtime import current_config
@@ -308,11 +308,27 @@ class _AppOnlyToolsForCardClients(Middleware):
308
308
  mcp.add_middleware(_AppOnlyToolsForCardClients())
309
309
 
310
310
 
311
+ _DRY_RUN_FLAG = TypeAdapter(bool)
312
+
313
+
311
314
  def _wants_real_apply(arguments: dict | None) -> bool:
312
- value = (arguments or {}).get("dry_run", True)
315
+ """Whether a confirm_and_apply call asks for a real apply.
316
+
317
+ Only a clear dry run skips the dialog. The tool reads ``dry_run`` with
318
+ pydantic's lax booleans, which take more spellings of "no" than any
319
+ list kept here ("off", "f", "n", ...), so the value is read the same
320
+ way, and anything that is not a plain yes counts as a real apply.
321
+ """
322
+ args = arguments or {}
323
+ if "dry_run" not in args:
324
+ return False # the tool's default is a dry run
325
+ value = args["dry_run"]
313
326
  if isinstance(value, str):
314
- return value.strip().lower() in {"false", "0", "no"}
315
- return value is False or value == 0
327
+ value = value.strip()
328
+ try:
329
+ return _DRY_RUN_FLAG.validate_python(value) is not True
330
+ except ValueError:
331
+ return True
316
332
 
317
333
 
318
334
  class _ConfirmationDialog(Middleware):
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes