adstack 0.2.0__py3-none-any.whl

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.
@@ -0,0 +1,342 @@
1
+ """An offline stand-in for a Google Ads account.
2
+
3
+ The sandbox keeps resources in a local JSON file and applies the same mutate
4
+ operations Adstack sends to Google, so configurations, plans and the MCP
5
+ server can be tried without an ad account or credentials (``--sandbox``).
6
+
7
+ It enforces the parts of Google's mutate contract that Adstack relies on:
8
+ requests are atomic; temporary resource names must be created before they are
9
+ referenced; referenced resources must exist; and one request may not mutate
10
+ the same resource twice. It does not emulate ad policy review, keyword
11
+ validation, auctions or billing, and its reports contain zero metrics.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import copy
17
+ import json
18
+ import re
19
+ from collections import Counter
20
+ from pathlib import Path
21
+ from typing import Any
22
+
23
+ from ...errors import ConfigError, ProviderError
24
+ from .api import REPORT_DAYS, REPORT_KINDS
25
+ from .schema import PREFIX
26
+
27
+ SANDBOX_FORMAT = "adstack-sandbox/1"
28
+ SANDBOX_ACCOUNT = "0000000000"
29
+
30
+ COLLECTIONS = {
31
+ "campaignBudgetOperation": "campaignBudgets",
32
+ "campaignOperation": "campaigns",
33
+ "campaignCriterionOperation": "campaignCriteria",
34
+ "adGroupOperation": "adGroups",
35
+ "adGroupCriterionOperation": "adGroupCriteria",
36
+ "adGroupAdOperation": "adGroupAds",
37
+ }
38
+
39
+ # Fields returned by the snapshot, matching the Google Ads API backend's GAQL selections.
40
+ _CAMPAIGN = (
41
+ "resourceName",
42
+ "name",
43
+ "status",
44
+ "advertisingChannelType",
45
+ "campaignBudget",
46
+ "biddingStrategyType",
47
+ "networkSettings",
48
+ "geoTargetTypeSetting",
49
+ )
50
+ _BUDGET = ("resourceName", "amountMicros", "explicitlyShared", "period")
51
+ _GROUP = ("resourceName", "name", "status", "type", "cpcBidMicros")
52
+ _KEYWORD = ("resourceName", "adGroup", "status", "keyword", "negative")
53
+ _AD = ("resourceName", "adGroup", "status", "ad")
54
+ _CRITERION = ("resourceName", "status", "type", "negative", "location", "keyword")
55
+
56
+
57
+ def _pick(resource: dict[str, Any], fields: tuple[str, ...]) -> dict[str, Any]:
58
+ return {field: copy.deepcopy(resource[field]) for field in fields if field in resource}
59
+
60
+
61
+ def _resolve(value: Any, temporary: dict[str, str]) -> Any:
62
+ """Replace references to temporary resource names created earlier in the request."""
63
+ if isinstance(value, str):
64
+ return temporary.get(value, value)
65
+ if isinstance(value, list):
66
+ return [_resolve(item, temporary) for item in value]
67
+ if isinstance(value, dict):
68
+ return {key: _resolve(item, temporary) for key, item in value.items()}
69
+ return value
70
+
71
+
72
+ class SandboxBackend:
73
+ """A fake Google Ads account stored in a JSON file."""
74
+
75
+ sandbox = True
76
+ account = SANDBOX_ACCOUNT
77
+
78
+ def __init__(self, path: str | Path, namespace: str, currency: str):
79
+ self.path = Path(path)
80
+ self.namespace = namespace
81
+ if self.path.exists():
82
+ try:
83
+ self.data = json.loads(self.path.read_text(encoding="utf-8"))
84
+ except (OSError, ValueError) as exc:
85
+ raise ProviderError(f"{self.path}: cannot read the sandbox file: {exc}") from None
86
+ if not isinstance(self.data, dict) or self.data.get("format") != SANDBOX_FORMAT:
87
+ raise ProviderError(f"{self.path}: not an Adstack sandbox file")
88
+ else:
89
+ self.data = {
90
+ "format": SANDBOX_FORMAT,
91
+ "account": SANDBOX_ACCOUNT,
92
+ "currency": currency,
93
+ "next_id": 1001,
94
+ "resources": {collection: {} for collection in COLLECTIONS.values()},
95
+ }
96
+
97
+ # -- Backend interface -------------------------------------------------------------------------
98
+
99
+ def read(self) -> dict[str, Any]:
100
+ resources = self.data["resources"]
101
+ prefix = f"{PREFIX}:{self.namespace}:"
102
+ live = {rn: c for rn, c in resources["campaigns"].items() if c["status"] != "REMOVED"}
103
+ references = Counter(c["campaignBudget"] for c in live.values())
104
+ state: dict[str, Any] = {"currency": self.data["currency"], "campaigns": {}}
105
+ for campaign_rn, campaign in sorted(live.items()):
106
+ if not campaign["name"].startswith(prefix):
107
+ continue
108
+ budget = resources["campaignBudgets"][campaign["campaignBudget"]]
109
+ groups = {
110
+ rn: group
111
+ for rn, group in sorted(resources["adGroups"].items())
112
+ if group["campaign"] == campaign_rn and group["status"] != "REMOVED"
113
+ }
114
+ state["campaigns"][campaign["name"]] = {
115
+ "campaign": _pick(campaign, _CAMPAIGN),
116
+ "budget": {**_pick(budget, _BUDGET), "referenceCount": str(references[campaign["campaignBudget"]])},
117
+ "groups": [_pick(group, _GROUP) for group in groups.values()],
118
+ "keywords": [
119
+ _pick(row, _KEYWORD)
120
+ for _, row in sorted(resources["adGroupCriteria"].items())
121
+ if row["adGroup"] in groups
122
+ ],
123
+ "ads": [
124
+ _pick(row, _AD)
125
+ for _, row in sorted(resources["adGroupAds"].items())
126
+ if row["adGroup"] in groups and row["status"] != "REMOVED"
127
+ ],
128
+ "criteria": [
129
+ _pick(row, _CRITERION)
130
+ for _, row in sorted(resources["campaignCriteria"].items())
131
+ if row["campaign"] == campaign_rn
132
+ ],
133
+ }
134
+ state["campaigns"] = dict(sorted(state["campaigns"].items()))
135
+ return state
136
+
137
+ def mutate(self, operations: list[dict[str, Any]], *, validate_only: bool) -> dict[str, Any]:
138
+ data = copy.deepcopy(self.data)
139
+ temporary: dict[str, str] = {}
140
+ touched: set[str] = set()
141
+ responses = []
142
+ for index, operation in enumerate(operations):
143
+ try:
144
+ resource_name = self._apply(data, operation, temporary)
145
+ except (KeyError, TypeError, ValueError, AttributeError) as exc:
146
+ raise ProviderError(f"sandbox rejected operation {index}: malformed operation ({exc!r})") from None
147
+ except ProviderError as exc:
148
+ raise ProviderError(f"sandbox rejected operation {index}: {exc}") from None
149
+ if resource_name in touched:
150
+ raise ProviderError(
151
+ f"sandbox rejected operation {index}: ID_EXISTS_IN_MULTIPLE_MUTATES: cannot mutate the same "
152
+ f"resource twice in one request ({resource_name})"
153
+ )
154
+ touched.add(resource_name)
155
+ kind = next(iter(operation)).replace("Operation", "Result")
156
+ responses.append({kind: {"resourceName": resource_name}})
157
+ if not validate_only:
158
+ self.data = data
159
+ self.save()
160
+ return {"mutateOperationResponses": responses}
161
+
162
+ def report(self, kind: str, days: int, *, all_campaigns: bool = False) -> list[dict[str, Any]]:
163
+ if kind not in REPORT_KINDS:
164
+ raise ConfigError(f"unknown report {kind!r} (choose from {', '.join(REPORT_KINDS)})")
165
+ if days not in REPORT_DAYS:
166
+ raise ConfigError("days must be 7, 14 or 30")
167
+ if kind == "search_terms":
168
+ return []
169
+ prefix = f"{PREFIX}:{self.namespace}:"
170
+ campaigns = sorted(self.data["resources"]["campaigns"].values(), key=lambda c: c["name"])
171
+ return [
172
+ {
173
+ "campaign": c["name"],
174
+ "status": c["status"],
175
+ "impressions": 0,
176
+ "clicks": 0,
177
+ "cost": "0.00",
178
+ "conversions": 0.0,
179
+ }
180
+ for c in campaigns
181
+ if c["status"] != "REMOVED" and (all_campaigns or c["name"].startswith(prefix))
182
+ ]
183
+
184
+ # -- Storage -----------------------------------------------------------------------------------
185
+
186
+ def save(self) -> None:
187
+ try:
188
+ self.path.parent.mkdir(parents=True, exist_ok=True)
189
+ temporary = self.path.with_name(self.path.name + ".tmp")
190
+ temporary.write_text(json.dumps(self.data, indent=2, sort_keys=True) + "\n", encoding="utf-8")
191
+ temporary.replace(self.path)
192
+ except OSError as exc:
193
+ raise ProviderError(f"cannot write the sandbox file {self.path}: {exc}") from None
194
+
195
+ # -- Mutate emulation --------------------------------------------------------------------------
196
+
197
+ def _apply(self, data: dict[str, Any], operation: dict[str, Any], temporary: dict[str, str]) -> str:
198
+ if not isinstance(operation, dict) or len(operation) != 1:
199
+ raise ProviderError("each operation must contain exactly one resource operation")
200
+ ((kind, body),) = operation.items()
201
+ collection = COLLECTIONS.get(kind)
202
+ if collection is None:
203
+ raise ProviderError(f"unsupported operation {kind!r}")
204
+ if "create" in body:
205
+ return self._create(data, collection, body["create"], temporary)
206
+ if "update" in body:
207
+ return self._update(data, collection, body["update"], body.get("updateMask", ""))
208
+ if "remove" in body:
209
+ return self._remove(data, collection, body["remove"])
210
+ raise ProviderError("operation has no create, update or remove")
211
+
212
+ @staticmethod
213
+ def _existing(data: dict[str, Any], collection: str, resource_name: Any) -> str:
214
+ resource = data["resources"][collection].get(resource_name) if isinstance(resource_name, str) else None
215
+ if resource is None or resource.get("status") == "REMOVED":
216
+ raise ProviderError(f"RESOURCE_NOT_FOUND: {resource_name!r}")
217
+ return resource_name
218
+
219
+ def _create(self, data: dict[str, Any], collection: str, fields: dict[str, Any], temporary: dict[str, str]) -> str:
220
+ fields = _resolve(copy.deepcopy(fields), temporary)
221
+ temp_name = fields.pop("resourceName", None)
222
+ if temp_name is not None:
223
+ if not re.fullmatch(rf"customers/{self.account}/{collection}/-[0-9]+", str(temp_name)):
224
+ raise ProviderError(f"invalid temporary resource name {temp_name!r}")
225
+ if temp_name in temporary:
226
+ raise ProviderError(f"temporary resource name {temp_name!r} is used twice")
227
+ resources = data["resources"]
228
+ new_id = data["next_id"]
229
+ data["next_id"] += 1
230
+ base = f"customers/{self.account}"
231
+
232
+ if collection == "campaignBudgets":
233
+ resource_name = f"{base}/campaignBudgets/{new_id}"
234
+ resource = {
235
+ "name": fields["name"],
236
+ "amountMicros": str(int(fields["amountMicros"])),
237
+ "explicitlyShared": bool(fields.get("explicitlyShared", False)),
238
+ "deliveryMethod": fields.get("deliveryMethod", "STANDARD"),
239
+ "period": "DAILY",
240
+ }
241
+ elif collection == "campaigns":
242
+ budget = self._existing(data, "campaignBudgets", fields.get("campaignBudget"))
243
+ if any(c["name"] == fields["name"] and c["status"] != "REMOVED" for c in resources["campaigns"].values()):
244
+ raise ProviderError(f"DUPLICATE_CAMPAIGN_NAME: {fields['name']!r}")
245
+ if fields.get("status") not in ("ENABLED", "PAUSED"):
246
+ raise ProviderError(f"invalid campaign status {fields.get('status')!r}")
247
+ resource_name = f"{base}/campaigns/{new_id}"
248
+ resource = {
249
+ "name": fields["name"],
250
+ "status": fields["status"],
251
+ "advertisingChannelType": fields["advertisingChannelType"],
252
+ "campaignBudget": budget,
253
+ "biddingStrategyType": "MANUAL_CPC" if "manualCpc" in fields else "UNSPECIFIED",
254
+ "networkSettings": fields.get("networkSettings", {}),
255
+ "geoTargetTypeSetting": fields.get("geoTargetTypeSetting", {}),
256
+ }
257
+ elif collection == "campaignCriteria":
258
+ campaign = self._existing(data, "campaigns", fields.get("campaign"))
259
+ kind = "LOCATION" if "location" in fields else "KEYWORD" if "keyword" in fields else None
260
+ if kind is None:
261
+ raise ProviderError("campaign criterion needs a location or a keyword")
262
+ resource_name = f"{base}/campaignCriteria/{campaign.rsplit('/', 1)[1]}~{new_id}"
263
+ resource = {
264
+ "campaign": campaign,
265
+ "status": fields.get("status", "ENABLED"),
266
+ "type": kind,
267
+ "negative": bool(fields.get("negative", False)),
268
+ kind.lower(): fields[kind.lower()],
269
+ }
270
+ elif collection == "adGroups":
271
+ campaign = self._existing(data, "campaigns", fields.get("campaign"))
272
+ if any(
273
+ g["campaign"] == campaign and g["name"] == fields["name"] and g["status"] != "REMOVED"
274
+ for g in resources["adGroups"].values()
275
+ ):
276
+ raise ProviderError(f"DUPLICATE_ADGROUP_NAME: {fields['name']!r}")
277
+ resource_name = f"{base}/adGroups/{new_id}"
278
+ resource = {
279
+ "campaign": campaign,
280
+ "name": fields["name"],
281
+ "status": fields.get("status", "ENABLED"),
282
+ "type": fields.get("type", "SEARCH_STANDARD"),
283
+ "cpcBidMicros": str(int(fields.get("cpcBidMicros", 0))),
284
+ }
285
+ elif collection == "adGroupCriteria":
286
+ group = self._existing(data, "adGroups", fields.get("adGroup"))
287
+ keyword = fields["keyword"]
288
+ negative = bool(fields.get("negative", False))
289
+ if any(
290
+ k["adGroup"] == group and k["keyword"] == keyword and k["negative"] == negative
291
+ for k in resources["adGroupCriteria"].values()
292
+ ):
293
+ raise ProviderError(f"duplicate keyword {keyword!r}")
294
+ resource_name = f"{base}/adGroupCriteria/{group.rsplit('/', 1)[1]}~{new_id}"
295
+ resource = {
296
+ "adGroup": group,
297
+ "status": fields.get("status", "ENABLED"),
298
+ "keyword": keyword,
299
+ "negative": negative,
300
+ }
301
+ else: # adGroupAds
302
+ group = self._existing(data, "adGroups", fields.get("adGroup"))
303
+ ad = dict(fields["ad"])
304
+ if "responsiveSearchAd" in ad:
305
+ ad["type"] = "RESPONSIVE_SEARCH_AD"
306
+ resource_name = f"{base}/adGroupAds/{group.rsplit('/', 1)[1]}~{new_id}"
307
+ resource = {"adGroup": group, "status": fields.get("status", "ENABLED"), "ad": ad}
308
+
309
+ resource["resourceName"] = resource_name
310
+ resources[collection][resource_name] = resource
311
+ if temp_name is not None:
312
+ temporary[temp_name] = resource_name
313
+ return resource_name
314
+
315
+ def _update(self, data: dict[str, Any], collection: str, fields: dict[str, Any], mask: str) -> str:
316
+ fields = dict(fields)
317
+ resource_name = self._existing(data, collection, fields.pop("resourceName", None))
318
+ resource = data["resources"][collection][resource_name]
319
+ paths = [path for path in str(mask).split(",") if path]
320
+ if not paths:
321
+ raise ProviderError("update operations need an updateMask")
322
+ for path in paths:
323
+ parts = path.split(".")
324
+ value: Any = fields
325
+ for part in parts:
326
+ if not isinstance(value, dict) or part not in value:
327
+ raise ProviderError(f"updateMask path {path!r} is missing from the update")
328
+ value = value[part]
329
+ target = resource
330
+ for part in parts[:-1]:
331
+ target = target.setdefault(part, {})
332
+ target[parts[-1]] = copy.deepcopy(value)
333
+ return resource_name
334
+
335
+ def _remove(self, data: dict[str, Any], collection: str, resource_name: Any) -> str:
336
+ resource_name = self._existing(data, collection, resource_name)
337
+ store = data["resources"][collection]
338
+ if collection in ("campaignCriteria", "adGroupCriteria"):
339
+ del store[resource_name]
340
+ else:
341
+ store[resource_name]["status"] = "REMOVED"
342
+ return resource_name
@@ -0,0 +1,258 @@
1
+ """Validate the ``google_ads`` configuration and normalize it into a desired state.
2
+
3
+ This version manages Google Search campaigns with manual CPC bidding,
4
+ exact-match keywords, campaign negative keywords, location targeting and
5
+ responsive search ads. Validation is offline and strict: unknown keys,
6
+ duplicates and out-of-range values are errors.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import copy
12
+ import re
13
+ from typing import Any
14
+ from urllib.parse import urlsplit
15
+
16
+ from ...errors import ConfigError
17
+ from ...validation import distinct, mapping, money_micros, sequence, slug, text
18
+
19
+ PREFIX = "adstack"
20
+ """Managed resource names start with this prefix: ``adstack:<namespace>:<campaign id>``."""
21
+
22
+ DEFAULT_LIMITS = {"daily_budget": "1000", "cpc": "50"}
23
+ """Upper bounds (in account currency) that catch typos such as an extra zero. Override with ``limits``."""
24
+
25
+ _LIMIT_CEILING_MICROS = 1_000_000 * 1_000_000
26
+
27
+
28
+ def campaign_name(namespace: str, campaign_id: str) -> str:
29
+ return f"{PREFIX}:{namespace}:{campaign_id}"
30
+
31
+
32
+ def ad_group_name(ad_group_id: str) -> str:
33
+ return f"{PREFIX}:{ad_group_id}"
34
+
35
+
36
+ def customer_id(value: Any, source: str) -> str:
37
+ """Normalize a Google Ads customer ID (``123-456-7890`` or ``1234567890``) to 10 digits."""
38
+ digits = str(value).strip().replace("-", "") if isinstance(value, (str, int)) else ""
39
+ if isinstance(value, bool) or not re.fullmatch(r"[0-9]{10}", digits):
40
+ raise ConfigError(f"{source}: expected a 10-digit Google Ads customer ID such as 123-456-7890")
41
+ return digits
42
+
43
+
44
+ def format_customer_id(value: str) -> str:
45
+ return f"{value[:3]}-{value[3:6]}-{value[6:]}" if len(value) == 10 else value
46
+
47
+
48
+ def keyword(value: Any, path: str, *, exact_only: bool = False) -> dict[str, str]:
49
+ """Parse ``[exact]``, ``"phrase"`` or ``broad`` keyword syntax."""
50
+ value = text(value, path, maximum=82)
51
+ if len(value) >= 2 and value[0] == "[" and value[-1] == "]":
52
+ match_type = "EXACT"
53
+ elif len(value) >= 2 and value[0] == '"' and value[-1] == '"':
54
+ match_type = "PHRASE"
55
+ else:
56
+ match_type = "BROAD"
57
+ body = value if match_type == "BROAD" else value[1:-1]
58
+ if exact_only and match_type != "EXACT":
59
+ raise ConfigError(f"{path}: {value!r}: ad group keywords must use exact match, written [keyword]")
60
+ if (
61
+ not body.strip()
62
+ or body != body.strip()
63
+ or len(body) > 80
64
+ or len(body.split()) > 10
65
+ or any(c in body for c in '[]"')
66
+ ):
67
+ raise ConfigError(f"{path}: {value!r} is not a valid keyword (at most 80 characters and 10 words)")
68
+ return {"text": " ".join(body.lower().split()), "matchType": match_type}
69
+
70
+
71
+ def keyword_label(keyword: dict[str, Any]) -> str:
72
+ """Display a keyword in configuration syntax."""
73
+ words, match_type = keyword.get("text", ""), keyword.get("matchType")
74
+ if match_type == "EXACT":
75
+ return f"[{words}]"
76
+ if match_type == "PHRASE":
77
+ return f'"{words}"'
78
+ return str(words)
79
+
80
+
81
+ def responsive_search_ad(value: Any, path: str) -> dict[str, Any]:
82
+ """Validate an ad definition and return it in Google Ads API shape."""
83
+ ad = mapping(value, path, required={"final_url", "headlines", "descriptions"})
84
+ headlines = [
85
+ text(h, f"{path}.headlines", maximum=30)
86
+ for h in sequence(ad["headlines"], f"{path}.headlines", minimum=3, maximum=15)
87
+ ]
88
+ descriptions = [
89
+ text(d, f"{path}.descriptions", maximum=90)
90
+ for d in sequence(ad["descriptions"], f"{path}.descriptions", minimum=2, maximum=4)
91
+ ]
92
+ distinct(headlines, f"{path}.headlines", str.casefold)
93
+ distinct(descriptions, f"{path}.descriptions", str.casefold)
94
+ url = text(ad["final_url"], f"{path}.final_url", maximum=2048)
95
+ try:
96
+ parts = urlsplit(url)
97
+ valid = parts.scheme == "https" and bool(parts.hostname) and not parts.username and not parts.password
98
+ except ValueError:
99
+ valid = False
100
+ if not valid or any(c.isspace() for c in url):
101
+ raise ConfigError(f"{path}.final_url: expected an absolute https:// URL")
102
+ return {
103
+ "finalUrls": [url],
104
+ "responsiveSearchAd": {
105
+ "headlines": [{"text": h} for h in headlines],
106
+ "descriptions": [{"text": d} for d in descriptions],
107
+ },
108
+ }
109
+
110
+
111
+ def load(settings: Any, document: dict[str, Any]) -> dict[str, Any]:
112
+ """Validate the provider block and the campaigns; return the desired state."""
113
+ settings = mapping(
114
+ settings,
115
+ "provider.google_ads",
116
+ required={"namespace", "currency"},
117
+ optional={"customer_id", "login_customer_id", "limits"},
118
+ )
119
+ namespace = slug(settings["namespace"], "provider.google_ads.namespace")
120
+ currency = settings["currency"]
121
+ if not isinstance(currency, str) or not re.fullmatch(r"[A-Z]{3}", currency):
122
+ raise ConfigError("provider.google_ads.currency: expected an ISO 4217 currency code such as USD")
123
+ account = settings.get("customer_id")
124
+ login = settings.get("login_customer_id")
125
+ limits = _limits(settings.get("limits"), "provider.google_ads.limits")
126
+
127
+ document = mapping(document, "configuration", required={"campaigns"}, optional={"ad_templates"})
128
+ raw_templates = document.get("ad_templates") or {}
129
+ if not isinstance(raw_templates, dict):
130
+ raise ConfigError("ad_templates: expected a mapping from template names to ads")
131
+ templates = {
132
+ slug(name, "ad_templates"): responsive_search_ad(ad, f"ad_templates.{name}")
133
+ for name, ad in raw_templates.items()
134
+ }
135
+ campaigns: list[dict[str, Any]] = []
136
+ for index, raw in enumerate(sequence(document["campaigns"], "campaigns", maximum=1000)):
137
+ campaign = _campaign(raw, f"campaigns[{index}]", namespace, templates, limits)
138
+ if any(c["id"] == campaign["id"] for c in campaigns):
139
+ raise ConfigError(f"campaigns: campaign id {campaign['id']!r} is used more than once")
140
+ campaigns.append(campaign)
141
+ return {
142
+ "namespace": namespace,
143
+ "currency": currency,
144
+ "customer_id": None if account is None else customer_id(account, "provider.google_ads.customer_id"),
145
+ "login_customer_id": None if login is None else customer_id(login, "provider.google_ads.login_customer_id"),
146
+ "campaigns": campaigns,
147
+ }
148
+
149
+
150
+ def summary(desired: dict[str, Any]) -> str:
151
+ campaigns = desired["campaigns"]
152
+ groups = [g for c in campaigns for g in c["groups"]]
153
+ keywords = sum(len(g["keywords"]) for g in groups)
154
+ return f"{_plural(len(campaigns), 'campaign')}, {_plural(len(groups), 'ad group')}, {_plural(keywords, 'keyword')}"
155
+
156
+
157
+ def _plural(count: int, noun: str) -> str:
158
+ return f"{count} {noun}" if count == 1 else f"{count} {noun}s"
159
+
160
+
161
+ def _limits(value: Any, path: str) -> dict[str, int]:
162
+ limits = mapping({} if value is None else value, path, optional=set(DEFAULT_LIMITS))
163
+ return {
164
+ key: money_micros(limits.get(key, default), f"{path}.{key}", maximum_micros=_LIMIT_CEILING_MICROS)
165
+ for key, default in DEFAULT_LIMITS.items()
166
+ }
167
+
168
+
169
+ def _campaign(
170
+ raw: Any, where: str, namespace: str, templates: dict[str, Any], limits: dict[str, int]
171
+ ) -> dict[str, Any]:
172
+ spec = mapping(
173
+ raw,
174
+ where,
175
+ required={"id", "status", "daily_budget", "default_cpc", "locations", "ad_groups"},
176
+ optional={"negative_keywords"},
177
+ )
178
+ cid = slug(spec["id"], f"{where}.id")
179
+ where = f"campaigns.{cid}"
180
+ status = spec["status"]
181
+ if status not in ("PAUSED", "ENABLED"):
182
+ raise ConfigError(f"{where}.status: expected PAUSED or ENABLED")
183
+ budget = money_micros(spec["daily_budget"], f"{where}.daily_budget", maximum_micros=limits["daily_budget"])
184
+ default_cpc = money_micros(spec["default_cpc"], f"{where}.default_cpc", maximum_micros=limits["cpc"])
185
+
186
+ locations = [str(x) for x in sequence(spec["locations"], f"{where}.locations", minimum=1, maximum=100)]
187
+ for location in locations:
188
+ if not re.fullmatch(r"[1-9][0-9]{0,11}", location):
189
+ raise ConfigError(
190
+ f"{where}.locations: {location!r} is not a geo target constant ID (2840 is the United States)"
191
+ )
192
+ distinct(locations, f"{where}.locations")
193
+
194
+ raw_negatives = sequence(spec.get("negative_keywords", []), f"{where}.negative_keywords", maximum=500)
195
+ negatives = [keyword(k, f"{where}.negative_keywords") for k in raw_negatives]
196
+ distinct(negatives, f"{where}.negative_keywords", key=lambda k: (k["text"], k["matchType"]))
197
+
198
+ groups: list[dict[str, Any]] = []
199
+ owner: dict[str, str] = {}
200
+ for index, raw_group in enumerate(sequence(spec["ad_groups"], f"{where}.ad_groups", minimum=1, maximum=100)):
201
+ group = _ad_group(raw_group, f"{where}.ad_groups[{index}]", where, templates, default_cpc, limits)
202
+ if any(g["id"] == group["id"] for g in groups):
203
+ raise ConfigError(f"{where}.ad_groups: ad group id {group['id']!r} is used more than once")
204
+ for kw in group["keywords"]:
205
+ if kw["text"] in owner:
206
+ raise ConfigError(
207
+ f"{where}: keyword [{kw['text']}] is in ad groups {owner[kw['text']]} and {group['id']}; "
208
+ "a keyword may belong to one ad group per campaign"
209
+ )
210
+ owner[kw["text"]] = group["id"]
211
+ groups.append(group)
212
+ return {
213
+ "id": cid,
214
+ "name": campaign_name(namespace, cid),
215
+ "status": status,
216
+ "budget": budget,
217
+ "locations": locations,
218
+ "negatives": negatives,
219
+ "groups": groups,
220
+ }
221
+
222
+
223
+ def _ad_group(
224
+ raw: Any,
225
+ where: str,
226
+ campaign_where: str,
227
+ templates: dict[str, Any],
228
+ default_cpc: int,
229
+ limits: dict[str, int],
230
+ ) -> dict[str, Any]:
231
+ spec = mapping(raw, where, required={"id", "keywords"}, optional={"cpc", "ad", "ad_template"})
232
+ gid = slug(spec["id"], f"{where}.id")
233
+ where = f"{campaign_where}.ad_groups.{gid}"
234
+ if ("ad" in spec) == ("ad_template" in spec):
235
+ raise ConfigError(f"{where}: set exactly one of ad (an inline ad) or ad_template (a name from ad_templates)")
236
+ if "ad_template" in spec:
237
+ template = spec["ad_template"]
238
+ if not isinstance(template, str) or template not in templates:
239
+ known = ", ".join(sorted(templates)) or "none are defined"
240
+ raise ConfigError(f"{where}.ad_template: unknown template {template!r} (known templates: {known})")
241
+ ad = copy.deepcopy(templates[template]) # each ad group owns its ad; no shared objects
242
+ else:
243
+ template = None
244
+ ad = responsive_search_ad(spec["ad"], f"{where}.ad")
245
+ keywords = [
246
+ keyword(k, f"{where}.keywords", exact_only=True)
247
+ for k in sequence(spec["keywords"], f"{where}.keywords", minimum=1, maximum=500)
248
+ ]
249
+ distinct(keywords, f"{where}.keywords", key=lambda k: k["text"])
250
+ bid = money_micros(spec["cpc"], f"{where}.cpc", maximum_micros=limits["cpc"]) if "cpc" in spec else default_cpc
251
+ return {
252
+ "id": gid,
253
+ "name": ad_group_name(gid),
254
+ "bid": bid,
255
+ "keywords": keywords,
256
+ "ad": ad,
257
+ "ad_template": template,
258
+ }
adstack/scaffold.py ADDED
@@ -0,0 +1,44 @@
1
+ """The annotated starter configuration written by ``adstack init`` and served by the MCP server."""
2
+
3
+ STARTER_CONFIG = """\
4
+ # Adstack configuration: https://github.com/markwroberts0/adstack/blob/main/docs/configuration.md
5
+ version: 1
6
+
7
+ provider:
8
+ google_ads:
9
+ # Adstack names campaigns adstack:<namespace>:<campaign id>. It manages every
10
+ # campaign in its namespace and never touches campaigns outside it.
11
+ namespace: example
12
+ currency: USD # must match the Google Ads account's currency
13
+ # customer_id: 123-456-7890 # pin the account here, or set GOOGLE_ADS_CUSTOMER_ID
14
+ # limits: # guards against typos, in account currency (defaults shown)
15
+ # daily_budget: 1000
16
+ # cpc: 50
17
+
18
+ ad_templates:
19
+ default:
20
+ final_url: https://www.example.com/
21
+ headlines: # 3-15 headlines, up to 30 characters each
22
+ - Example Headline One
23
+ - Example Headline Two
24
+ - Example Headline Three
25
+ descriptions: # 2-4 descriptions, up to 90 characters each
26
+ - Describe what you offer and why it matters to the person searching.
27
+ - Finish with a clear call to action, such as Start Your Free Trial Today.
28
+
29
+ campaigns:
30
+ - id: search
31
+ status: PAUSED # new campaigns are always created PAUSED
32
+ daily_budget: 10.00 # Google's average daily budget, in account currency
33
+ default_cpc: 1.00 # manual CPC bid for ad groups that don't set cpc
34
+ locations: [2840] # geo target constant IDs (2840 = United States)
35
+ negative_keywords: # "phrase", [exact] or broad match
36
+ - '"free"'
37
+ - '"jobs"'
38
+ ad_groups:
39
+ - id: main
40
+ ad_template: default # or an inline ad: {final_url, headlines, descriptions}
41
+ keywords: # exact match: [keyword]
42
+ - '[example product]'
43
+ - '[buy example product]'
44
+ """