google-ads-mcp-server 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.
Files changed (49) hide show
  1. agency/__init__.py +5 -0
  2. agency/analysis_profiles.py +239 -0
  3. agency/api.py +236 -0
  4. agency/audit_retention.py +341 -0
  5. agency/builtin_profiles/agency-weekly.md +21 -0
  6. agency/builtin_profiles/agency-weekly.toml +19 -0
  7. agency/builtin_profiles/ecommerce-audit.md +23 -0
  8. agency/builtin_profiles/ecommerce-audit.toml +20 -0
  9. agency/builtin_profiles/leads-audit.md +24 -0
  10. agency/builtin_profiles/leads-audit.toml +20 -0
  11. agency/channels_tools.py +1069 -0
  12. agency/cli_alerts.py +203 -0
  13. agency/config.py +195 -0
  14. agency/customer_match_tools.py +561 -0
  15. agency/dates.py +140 -0
  16. agency/demand_gen_tools.py +545 -0
  17. agency/demo.py +1136 -0
  18. agency/diagnostics_tools.py +961 -0
  19. agency/errors.py +246 -0
  20. agency/experiment_tools.py +614 -0
  21. agency/governance.py +426 -0
  22. agency/governance_tools.py +349 -0
  23. agency/keyword_planner_tools.py +431 -0
  24. agency/locks.py +124 -0
  25. agency/mcc_tools.py +656 -0
  26. agency/measurement_tools.py +1050 -0
  27. agency/modules.py +370 -0
  28. agency/mutations.py +260 -0
  29. agency/offline_conversions_tools.py +522 -0
  30. agency/operations_tools.py +275 -0
  31. agency/read_tools.py +1892 -0
  32. agency/registry.py +41 -0
  33. agency/remote_gateway.py +354 -0
  34. agency/remote_onboarding.py +1349 -0
  35. agency/remote_store.py +1278 -0
  36. agency/reports.py +1101 -0
  37. agency/resources.py +240 -0
  38. agency/runtime.py +203 -0
  39. agency/waste_intelligence.py +358 -0
  40. agency/write_tools.py +2355 -0
  41. google_ads_cli.py +59 -0
  42. google_ads_connect.py +912 -0
  43. google_ads_mcp_server-0.2.0.dist-info/METADATA +532 -0
  44. google_ads_mcp_server-0.2.0.dist-info/RECORD +49 -0
  45. google_ads_mcp_server-0.2.0.dist-info/WHEEL +5 -0
  46. google_ads_mcp_server-0.2.0.dist-info/entry_points.txt +4 -0
  47. google_ads_mcp_server-0.2.0.dist-info/licenses/LICENSE +22 -0
  48. google_ads_mcp_server-0.2.0.dist-info/top_level.txt +4 -0
  49. google_ads_server.py +1910 -0
agency/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ """Agency-grade Google Ads MCP extensions."""
2
+
3
+ from .registry import register_agency_tools
4
+
5
+ __all__ = ["register_agency_tools"]
@@ -0,0 +1,239 @@
1
+ """Customizable analysis profiles (Markdown templates + TOML parameters).
2
+
3
+ Profiles live in `CONFIG_DIR/profiles` (falling back to the repository's
4
+ built-in `config/profiles` directory). Each profile pairs:
5
+ - `<id>.toml`: reproducible numeric/filter parameters and alert thresholds.
6
+ - `<id>.md`: editable Markdown audit instructions and output structure.
7
+
8
+ Security boundary:
9
+ Profiles express analysis preferences only. Account access (`ALLOWED_CUSTOMER_IDS`),
10
+ `READ_ONLY_MODE`, budget/bid caps, and human approvals are always enforced by the
11
+ server and cannot be relaxed by any profile.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from importlib import resources as importlib_resources
17
+ import os
18
+ import re
19
+ import tomllib
20
+ from pathlib import Path
21
+ from typing import Any, Optional
22
+
23
+ from mcp.types import ToolAnnotations
24
+ from pydantic import Field
25
+
26
+ from .api import format_json
27
+ from .config import CONFIG_DIR, PROJECT_ROOT, ensure_tool_allowed, load_json_config
28
+ from .governance import audited_tool
29
+
30
+
31
+ READ_ONLY = ToolAnnotations(
32
+ readOnlyHint=True,
33
+ destructiveHint=False,
34
+ idempotentHint=True,
35
+ openWorldHint=False,
36
+ )
37
+
38
+ _PROFILE_ID_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,63}$")
39
+
40
+
41
+ def _effective_config_dir() -> Path:
42
+ env_dir = os.getenv("GOOGLE_ADS_CONFIG_DIR")
43
+ if env_dir:
44
+ return Path(env_dir).expanduser()
45
+ return CONFIG_DIR
46
+
47
+
48
+ def _builtin_package_profiles_dir() -> Path | None:
49
+ try:
50
+ ref = importlib_resources.files("agency").joinpath("builtin_profiles")
51
+ candidate = Path(str(ref))
52
+ if candidate.is_dir():
53
+ return candidate
54
+ except (ModuleNotFoundError, TypeError, OSError):
55
+ pass
56
+ local_pkg = Path(__file__).resolve().parent / "builtin_profiles"
57
+ return local_pkg if local_pkg.is_dir() else None
58
+
59
+
60
+ def _profile_sources() -> list[tuple[Path, str]]:
61
+ """Return `(directory, source_label)` pairs in precedence order.
62
+
63
+ 1. User `CONFIG_DIR/profiles` (editable local overrides).
64
+ 2. Checkout `PROJECT_ROOT/config/profiles` (when running inside repo).
65
+ 3. Packaged `agency/builtin_profiles` (bundled inside wheel for `uvx`/`pip install`).
66
+ """
67
+ sources: list[tuple[Path, str]] = []
68
+ seen_resolved: set[Path] = set()
69
+
70
+ def _add(path: Path | None, label: str) -> None:
71
+ if path is None or not path.is_dir():
72
+ return
73
+ resolved = path.resolve()
74
+ if resolved in seen_resolved:
75
+ return
76
+ seen_resolved.add(resolved)
77
+ sources.append((path, label))
78
+
79
+ user_dir = _effective_config_dir() / "profiles"
80
+ checkout_dir = PROJECT_ROOT / "config" / "profiles"
81
+ pkg_dir = _builtin_package_profiles_dir()
82
+
83
+ if user_dir.is_dir() and (
84
+ not checkout_dir.is_dir() or user_dir.resolve() != checkout_dir.resolve()
85
+ ):
86
+ _add(user_dir, "user")
87
+ _add(checkout_dir, "builtin")
88
+ _add(pkg_dir, "builtin")
89
+ return sources
90
+
91
+
92
+ def _validate_profile_id(profile_id: str) -> str:
93
+ clean = (profile_id or "").strip().lower()
94
+ if not _PROFILE_ID_RE.fullmatch(clean):
95
+ raise ValueError(
96
+ "profile_id must contain only lowercase letters, digits, hyphens or underscores"
97
+ )
98
+ return clean
99
+
100
+
101
+ def _load_profile_from_dir(directory: Path, profile_id: str, source: str) -> dict[str, Any]:
102
+ toml_path = directory / f"{profile_id}.toml"
103
+ md_path = directory / f"{profile_id}.md"
104
+ if not toml_path.is_file() and not md_path.is_file():
105
+ raise FileNotFoundError(profile_id)
106
+
107
+ meta: dict[str, Any] = {}
108
+ if toml_path.is_file():
109
+ meta = tomllib.loads(toml_path.read_text(encoding="utf-8"))
110
+
111
+ instructions = md_path.read_text(encoding="utf-8").strip() if md_path.is_file() else ""
112
+ alert_defaults = load_json_config("alerts.json", {}).get("defaults", {})
113
+ raw_thresholds = meta.get("thresholds") or {}
114
+ merged_thresholds = {**alert_defaults, **raw_thresholds}
115
+
116
+ return {
117
+ "id": str(meta.get("id") or profile_id),
118
+ "name": str(meta.get("name") or profile_id.replace("-", " ").title()),
119
+ "description": str(meta.get("description") or ""),
120
+ "version": str(meta.get("version") or "1.0"),
121
+ "source": source,
122
+ "recommended_modules": list(meta.get("recommended_modules") or ["core"]),
123
+ "parameters": dict(meta.get("parameters") or {}),
124
+ "thresholds": merged_thresholds,
125
+ "has_markdown_template": bool(instructions),
126
+ "instructions_markdown": instructions,
127
+ }
128
+
129
+
130
+ def list_profiles() -> list[dict[str, Any]]:
131
+ """Discover all available analysis profiles (user CONFIG_DIR overrides built-in)."""
132
+ seen: dict[str, dict[str, Any]] = {}
133
+ for directory, source in _profile_sources():
134
+ ids = {
135
+ path.stem.lower()
136
+ for path in list(directory.glob("*.toml")) + list(directory.glob("*.md"))
137
+ if _PROFILE_ID_RE.fullmatch(path.stem.lower())
138
+ }
139
+ for pid in sorted(ids):
140
+ if pid in seen:
141
+ continue
142
+ seen[pid] = _load_profile_from_dir(directory, pid, source)
143
+ return [seen[key] for key in sorted(seen)]
144
+
145
+
146
+ def load_profile(profile_id: str) -> dict[str, Any]:
147
+ """Load a single profile by ID."""
148
+ clean = _validate_profile_id(profile_id)
149
+ for directory, source in _profile_sources():
150
+ try:
151
+ return _load_profile_from_dir(directory, clean, source)
152
+ except FileNotFoundError:
153
+ continue
154
+ available = [item["id"] for item in list_profiles()]
155
+ raise ValueError(
156
+ f"Unknown analysis profile '{clean}'. Available profiles: {available}"
157
+ )
158
+
159
+
160
+ def profile_thresholds(profile_id: str) -> dict[str, Any]:
161
+ """Return effective alert/analysis thresholds for a profile."""
162
+ return dict(load_profile(profile_id)["thresholds"])
163
+
164
+
165
+ def register_analysis_profile_tools(mcp) -> None:
166
+ @mcp.tool(annotations=READ_ONLY)
167
+ @audited_tool
168
+ def list_analysis_profiles() -> str:
169
+ """List editable local analysis profiles (Markdown templates + TOML parameters)."""
170
+ ensure_tool_allowed("list_analysis_profiles")
171
+ profiles = [
172
+ {
173
+ "id": item["id"],
174
+ "name": item["name"],
175
+ "description": item["description"],
176
+ "version": item["version"],
177
+ "source": item["source"],
178
+ "recommended_modules": item["recommended_modules"],
179
+ "has_markdown_template": item["has_markdown_template"],
180
+ "parameters": item["parameters"],
181
+ "thresholds": item["thresholds"],
182
+ }
183
+ for item in list_profiles()
184
+ ]
185
+ return format_json(
186
+ {
187
+ "count": len(profiles),
188
+ "profiles_dir": str(_effective_config_dir() / "profiles"),
189
+ "profiles": profiles,
190
+ "security_notice": (
191
+ "Analysis profiles customize instructions, parameters, and thresholds only. "
192
+ "Server-side account allowlists, READ_ONLY_MODE, caps, and approvals always apply."
193
+ ),
194
+ }
195
+ )
196
+
197
+ @mcp.tool(annotations=READ_ONLY)
198
+ @audited_tool
199
+ def get_analysis_profile(
200
+ profile_id: str = Field(description="Profile ID (e.g. 'leads-audit' or 'ecommerce-audit')"),
201
+ customer_id: Optional[str] = Field(
202
+ default=None,
203
+ description="Optional 10-digit customer ID to include in the reproducibility header",
204
+ ),
205
+ ) -> str:
206
+ """Load an analysis profile's Markdown instructions, TOML parameters, and merged thresholds."""
207
+ ensure_tool_allowed("get_analysis_profile")
208
+ profile = load_profile(profile_id)
209
+ return format_json(
210
+ {
211
+ **profile,
212
+ "reproducibility_header": {
213
+ "profile_id": profile["id"],
214
+ "profile_version": profile["version"],
215
+ "customer_id": customer_id,
216
+ "parameters": profile["parameters"],
217
+ "thresholds": profile["thresholds"],
218
+ },
219
+ "security_notice": (
220
+ "Include the reproducibility_header in the final report. "
221
+ "This profile cannot override READ_ONLY_MODE, ALLOWED_CUSTOMER_IDS, or mutation approvals."
222
+ ),
223
+ }
224
+ )
225
+
226
+ @mcp.prompt()
227
+ def analysis_profile_prompt(profile_id: str, customer_id: str = "") -> str:
228
+ """Run a customizable Google Ads audit using a local Markdown + TOML analysis profile."""
229
+ profile = load_profile(profile_id)
230
+ header = (
231
+ f"Use analysis profile `{profile['id']}` (v{profile['version']} — {profile['name']}).\n"
232
+ f"Target customer_id: {customer_id or '<select from list_accounts>'}\n"
233
+ f"Recommended modules: {', '.join(profile['recommended_modules'])}\n"
234
+ f"Effective TOML parameters:\n```json\n{format_json(profile['parameters'])}\n```\n"
235
+ f"Effective thresholds:\n```json\n{format_json(profile['thresholds'])}\n```\n\n"
236
+ "Security reminder: Profiles only define analysis preferences; server guardrails "
237
+ "(READ_ONLY_MODE, ALLOWED_CUSTOMER_IDS, dry-run approvals) always apply.\n\n"
238
+ )
239
+ return header + profile["instructions_markdown"]
agency/api.py ADDED
@@ -0,0 +1,236 @@
1
+ """Google Ads REST client with retries, pagination and local rate limiting."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import random
8
+ import time
9
+ from collections import defaultdict, deque
10
+ from threading import RLock
11
+ from typing import Any
12
+
13
+ import requests
14
+
15
+ from .config import ensure_customer_allowed, get_settings
16
+ from .errors import GoogleAdsError
17
+ from .runtime import resolve_login_customer_id
18
+
19
+
20
+ _rate_lock = RLock()
21
+ _request_times: dict[str, deque[float]] = defaultdict(deque)
22
+
23
+
24
+ def _server_module():
25
+ import google_ads_server
26
+
27
+ return google_ads_server
28
+
29
+
30
+ def _headers(
31
+ customer_id: str | None = None,
32
+ login_customer_id: str | None = None,
33
+ ) -> dict[str, str]:
34
+ server = _server_module()
35
+ headers = server.get_headers(server.get_credentials())
36
+ if customer_id is not None:
37
+ resolved_manager = resolve_login_customer_id(
38
+ customer_id,
39
+ explicit_login_customer_id=login_customer_id,
40
+ )
41
+ if resolved_manager:
42
+ headers["login-customer-id"] = resolved_manager
43
+ else:
44
+ headers.pop("login-customer-id", None)
45
+ elif login_customer_id:
46
+ headers["login-customer-id"] = ensure_customer_allowed(login_customer_id)
47
+ return headers
48
+
49
+
50
+ def _rate_limit(customer_id: str) -> None:
51
+ limit = get_settings().rate_limit_per_minute
52
+ now = time.monotonic()
53
+ with _rate_lock:
54
+ bucket = _request_times[customer_id]
55
+ while bucket and now - bucket[0] >= 60:
56
+ bucket.popleft()
57
+ if len(bucket) >= limit:
58
+ wait_seconds = min(30.0, max(0.0, 60 - (now - bucket[0])))
59
+ else:
60
+ wait_seconds = 0.0
61
+ if wait_seconds:
62
+ time.sleep(wait_seconds)
63
+ with _rate_lock:
64
+ _request_times[customer_id].append(time.monotonic())
65
+
66
+
67
+ def request(
68
+ method: str,
69
+ path: str,
70
+ *,
71
+ customer_id: str,
72
+ body: dict[str, Any] | None = None,
73
+ params: dict[str, Any] | None = None,
74
+ retries: int = 3,
75
+ ) -> dict[str, Any]:
76
+ customer_id = ensure_customer_allowed(customer_id)
77
+ _rate_limit(customer_id)
78
+ server = _server_module()
79
+ url = f"https://googleads.googleapis.com/{server.API_VERSION}/{path.lstrip('/')}"
80
+ last_error: Exception | None = None
81
+ for attempt in range(retries):
82
+ try:
83
+ response = requests.request(
84
+ method,
85
+ url,
86
+ headers=_headers(customer_id=customer_id),
87
+ json=body,
88
+ params=params,
89
+ timeout=server.HTTP_TIMEOUT_SECONDS,
90
+ )
91
+ if response.status_code in {429, 500, 502, 503, 504} and attempt < retries - 1:
92
+ retry_after = float(response.headers.get("Retry-After", 0) or 0)
93
+ time.sleep(max(retry_after, (2**attempt) + random.random()))
94
+ continue
95
+ if not response.ok:
96
+ raise GoogleAdsError.from_response(
97
+ http_status=response.status_code,
98
+ api_version=server.API_VERSION,
99
+ body=response.text[:6000],
100
+ )
101
+ if not response.content:
102
+ return {}
103
+ return response.json()
104
+ except (requests.RequestException, json.JSONDecodeError, RuntimeError) as error:
105
+ last_error = error
106
+ if attempt >= retries - 1 or isinstance(error, GoogleAdsError):
107
+ raise
108
+ if isinstance(error, RuntimeError):
109
+ raise
110
+ time.sleep((2**attempt) + random.random())
111
+ raise RuntimeError(f"Google Ads request failed: {last_error}")
112
+
113
+
114
+ DEFAULT_MAX_SEARCH_ROWS = 2000
115
+
116
+
117
+ def _effective_max_rows(max_rows: int | None) -> int | None:
118
+ if max_rows is not None:
119
+ return max(1, int(max_rows))
120
+ raw = os.getenv("GOOGLE_ADS_MAX_SEARCH_ROWS", str(DEFAULT_MAX_SEARCH_ROWS)).strip()
121
+ if raw in {"0", ""}:
122
+ return None
123
+ try:
124
+ return max(1, int(raw))
125
+ except ValueError:
126
+ return DEFAULT_MAX_SEARCH_ROWS
127
+
128
+
129
+ def search_with_meta(
130
+ customer_id: str,
131
+ query: str,
132
+ *,
133
+ max_rows: int | None = None,
134
+ ) -> dict[str, Any]:
135
+ """Execute GAQL search with bounded row collection to protect LLM context windows."""
136
+ customer_id = ensure_customer_allowed(customer_id)
137
+ limit = _effective_max_rows(max_rows)
138
+ from .demo import demo_search, is_demo_mode
139
+
140
+ if is_demo_mode():
141
+ rows = demo_search(customer_id, query)
142
+ truncated = bool(limit is not None and len(rows) > limit)
143
+ clipped = rows[:limit] if truncated else rows
144
+ return {
145
+ "rows": clipped,
146
+ "returned_rows": len(clipped),
147
+ "truncated": truncated,
148
+ "max_rows": limit,
149
+ }
150
+
151
+ results: list[dict[str, Any]] = []
152
+ page_token: str | None = None
153
+ truncated = False
154
+ while True:
155
+ # The REST googleAds:search endpoint fixes page size at 10000 rows and
156
+ # rejects an explicit pageSize with PAGE_SIZE_NOT_SUPPORTED.
157
+ body: dict[str, Any] = {"query": query}
158
+ if page_token:
159
+ body["pageToken"] = page_token
160
+ response = request(
161
+ "POST",
162
+ f"customers/{customer_id}/googleAds:search",
163
+ customer_id=customer_id,
164
+ body=body,
165
+ )
166
+ page_rows = response.get("results", [])
167
+ results.extend(page_rows)
168
+ page_token = response.get("nextPageToken")
169
+ if limit is not None and len(results) >= limit:
170
+ if len(results) > limit or page_token:
171
+ truncated = True
172
+ results = results[:limit]
173
+ break
174
+ if not page_token:
175
+ break
176
+ return {
177
+ "rows": results,
178
+ "returned_rows": len(results),
179
+ "truncated": truncated,
180
+ "max_rows": limit,
181
+ }
182
+
183
+
184
+ def search(
185
+ customer_id: str,
186
+ query: str,
187
+ *,
188
+ max_rows: int | None = None,
189
+ ) -> list[dict[str, Any]]:
190
+ return search_with_meta(customer_id, query, max_rows=max_rows)["rows"]
191
+
192
+
193
+ def mutate(
194
+ customer_id: str,
195
+ service: str,
196
+ operations: list[dict[str, Any]],
197
+ *,
198
+ validate_only: bool,
199
+ partial_failure: bool = False,
200
+ ) -> dict[str, Any]:
201
+ customer_id = ensure_customer_allowed(customer_id)
202
+ body = {
203
+ "operations": operations,
204
+ "validateOnly": validate_only,
205
+ "partialFailure": partial_failure,
206
+ "responseContentType": "MUTABLE_RESOURCE",
207
+ }
208
+ return request(
209
+ "POST",
210
+ f"customers/{customer_id}/{service}:mutate",
211
+ customer_id=customer_id,
212
+ body=body,
213
+ )
214
+
215
+
216
+ def batch_mutate(
217
+ customer_id: str,
218
+ mutate_operations: list[dict[str, Any]],
219
+ *,
220
+ validate_only: bool,
221
+ ) -> dict[str, Any]:
222
+ customer_id = ensure_customer_allowed(customer_id)
223
+ return request(
224
+ "POST",
225
+ f"customers/{customer_id}/googleAds:mutate",
226
+ customer_id=customer_id,
227
+ body={
228
+ "mutateOperations": mutate_operations,
229
+ "validateOnly": validate_only,
230
+ "responseContentType": "MUTABLE_RESOURCE",
231
+ },
232
+ )
233
+
234
+
235
+ def format_json(value: Any) -> str:
236
+ return json.dumps(value, ensure_ascii=False, indent=2, default=str)