adsync-cli 0.1.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.
- adsync/__init__.py +296 -0
- adsync/__main__.py +5 -0
- adsync/skills/adsync/SKILL.md +60 -0
- adsync/skills/adsync-playbooks/SKILL.md +74 -0
- adsync_cli-0.1.0.dist-info/METADATA +24 -0
- adsync_cli-0.1.0.dist-info/RECORD +8 -0
- adsync_cli-0.1.0.dist-info/WHEEL +4 -0
- adsync_cli-0.1.0.dist-info/entry_points.txt +2 -0
adsync/__init__.py
ADDED
|
@@ -0,0 +1,296 @@
|
|
|
1
|
+
"""adsync: run AdSync's Meta Ads, Google Ads, GA4 and Search Console tools from a shell.
|
|
2
|
+
|
|
3
|
+
A thin client over the hosted MCP servers (JSON-RPC over HTTP). Scope checks, read-only tokens, the Activity
|
|
4
|
+
log and PAUSED creates all happen on the server, exactly as for an MCP client. Standard library only.
|
|
5
|
+
|
|
6
|
+
adsync login sign in through the browser (or --paste a token)
|
|
7
|
+
adsync tools [meta|google|ga|gsc] list tools
|
|
8
|
+
adsync describe meta get_insights show a tool's arguments
|
|
9
|
+
adsync meta get_insights account_id=act_123 level=ad fields:='["spend","ctr"]'
|
|
10
|
+
adsync skill install add the AdSync skills to Claude Code
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
import argparse
|
|
14
|
+
import base64
|
|
15
|
+
import hashlib
|
|
16
|
+
import json
|
|
17
|
+
import os
|
|
18
|
+
import secrets
|
|
19
|
+
import shutil
|
|
20
|
+
import sys
|
|
21
|
+
import tempfile
|
|
22
|
+
import time
|
|
23
|
+
import urllib.error
|
|
24
|
+
import urllib.parse
|
|
25
|
+
import urllib.request
|
|
26
|
+
import webbrowser
|
|
27
|
+
from getpass import getpass
|
|
28
|
+
from http.server import BaseHTTPRequestHandler, HTTPServer
|
|
29
|
+
from importlib.resources import files
|
|
30
|
+
from pathlib import Path
|
|
31
|
+
|
|
32
|
+
__version__ = "0.1.0"
|
|
33
|
+
|
|
34
|
+
PLATFORMS = {"meta": "meta-ads", "google": "google-ads", "ga": "google-analytics", "gsc": "search-console"}
|
|
35
|
+
UA = f"adsync-cli/{__version__}"
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class Fail(Exception):
|
|
39
|
+
pass
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def base_url() -> str:
|
|
43
|
+
url = os.environ.get("ADSYNC_URL", "https://mcp.getadsync.com").rstrip("/")
|
|
44
|
+
u = urllib.parse.urlsplit(url)
|
|
45
|
+
# The token rides on every request: plain http only to this machine, like the server's own redirect rule.
|
|
46
|
+
if u.scheme != "https" and not (u.scheme == "http" and u.hostname in ("localhost", "127.0.0.1", "::1")):
|
|
47
|
+
raise Fail(f"ADSYNC_URL must be https (or http on localhost), got {url!r}.")
|
|
48
|
+
return url
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def token_file() -> Path:
|
|
52
|
+
return Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config") / "adsync" / "token"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def token() -> str:
|
|
56
|
+
t = os.environ.get("ADSYNC_TOKEN", "").strip()
|
|
57
|
+
if not t and token_file().exists():
|
|
58
|
+
t = token_file().read_text().strip()
|
|
59
|
+
if not t:
|
|
60
|
+
raise Fail("Not signed in. Run `adsync login`, or set ADSYNC_TOKEN.")
|
|
61
|
+
return t
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def post(url: str, data: bytes, headers: dict) -> dict:
|
|
65
|
+
req = urllib.request.Request(url, data, {"User-Agent": UA, **headers})
|
|
66
|
+
try:
|
|
67
|
+
with urllib.request.urlopen(req, timeout=120) as r:
|
|
68
|
+
raw = r.read()
|
|
69
|
+
except urllib.error.HTTPError as e:
|
|
70
|
+
body = e.read().decode(errors="replace")
|
|
71
|
+
if e.code == 401:
|
|
72
|
+
raise Fail("The AdSync token is missing, unknown or revoked. Run `adsync login` again.")
|
|
73
|
+
try:
|
|
74
|
+
body = json.loads(body).get("error_description") or body
|
|
75
|
+
except (ValueError, AttributeError):
|
|
76
|
+
pass
|
|
77
|
+
raise Fail(f"HTTP {e.code} from {url}: {body[:500]}")
|
|
78
|
+
except urllib.error.URLError as e:
|
|
79
|
+
raise Fail(f"Could not reach {url}: {e.reason}")
|
|
80
|
+
except TimeoutError:
|
|
81
|
+
raise Fail(f"{url} did not answer within 120 seconds. For a write, check whether it happened before retrying.")
|
|
82
|
+
try:
|
|
83
|
+
return json.loads(raw or b"{}")
|
|
84
|
+
except ValueError:
|
|
85
|
+
raise Fail(f"Unexpected non-JSON answer from {url}: {raw[:200]!r}")
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def rpc(platform: str, method: str, params: dict | None = None):
|
|
89
|
+
body = json.dumps({"jsonrpc": "2.0", "id": 1, "method": method, "params": params or {}}).encode()
|
|
90
|
+
msg = post(f"{base_url()}/{PLATFORMS[platform]}", body, {
|
|
91
|
+
"Content-Type": "application/json",
|
|
92
|
+
"Accept": "application/json, text/event-stream",
|
|
93
|
+
"Authorization": f"Bearer {token()}",
|
|
94
|
+
})
|
|
95
|
+
if "error" in msg:
|
|
96
|
+
raise Fail(msg["error"].get("message") or json.dumps(msg["error"]))
|
|
97
|
+
return msg["result"]
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def list_tools(platform: str) -> list[dict]:
|
|
101
|
+
out, cursor = [], None
|
|
102
|
+
while True:
|
|
103
|
+
res = rpc(platform, "tools/list", {"cursor": cursor} if cursor else {})
|
|
104
|
+
out += res.get("tools", [])
|
|
105
|
+
cursor = res.get("nextCursor")
|
|
106
|
+
if not cursor:
|
|
107
|
+
return out
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def parse_args(pairs: list[str], raw_json: str | None) -> dict:
|
|
111
|
+
"""key=value passes a string (the server coerces numbers and booleans); key:=value passes raw JSON."""
|
|
112
|
+
args = {}
|
|
113
|
+
if raw_json is not None:
|
|
114
|
+
args = json.loads(sys.stdin.read() if raw_json == "-" else raw_json)
|
|
115
|
+
if not isinstance(args, dict):
|
|
116
|
+
raise Fail("--json must be a JSON object.")
|
|
117
|
+
for pair in pairs:
|
|
118
|
+
key, sep, value = pair.partition("=")
|
|
119
|
+
if not sep or not key:
|
|
120
|
+
raise Fail(f"Expected key=value or key:=json, got {pair!r}.")
|
|
121
|
+
if key.endswith(":"):
|
|
122
|
+
try:
|
|
123
|
+
args[key[:-1]] = json.loads(value)
|
|
124
|
+
except ValueError:
|
|
125
|
+
raise Fail(f"{key[:-1]}:= needs valid JSON, got {value!r}.")
|
|
126
|
+
else:
|
|
127
|
+
args[key] = value
|
|
128
|
+
return args
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def call(platform: str, tool: str, args: dict) -> int:
|
|
132
|
+
res = rpc(platform, "tools/call", {"name": tool, "arguments": args})
|
|
133
|
+
content = res.get("content", [])
|
|
134
|
+
text = "\n".join(c.get("text", "") for c in content if c.get("type") == "text")
|
|
135
|
+
for c in content: # get_ad_image and friends send the picture too: save it so the caller can open it
|
|
136
|
+
if c.get("type") == "image":
|
|
137
|
+
ext = {"image/jpeg": ".jpg", "image/png": ".png", "image/gif": ".gif", "image/webp": ".webp"}.get(
|
|
138
|
+
c.get("mimeType", ""), ".img")
|
|
139
|
+
fd, path = tempfile.mkstemp(prefix="adsync-image-", suffix=ext)
|
|
140
|
+
with os.fdopen(fd, "wb") as f:
|
|
141
|
+
f.write(base64.b64decode(c.get("data", "")))
|
|
142
|
+
print(f"Image saved to {path}", file=sys.stderr)
|
|
143
|
+
if res.get("isError"):
|
|
144
|
+
print(text or "The tool failed.", file=sys.stderr)
|
|
145
|
+
return 1
|
|
146
|
+
print(text)
|
|
147
|
+
return 0
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def show_tools(platform: str | None) -> None:
|
|
151
|
+
for p in [platform] if platform else PLATFORMS:
|
|
152
|
+
for t in list_tools(p):
|
|
153
|
+
a = t.get("annotations") or {}
|
|
154
|
+
kind = "delete" if a.get("destructiveHint") else "read" if a.get("readOnlyHint") else "write"
|
|
155
|
+
desc = (t.get("description") or "").strip().split("\n")[0]
|
|
156
|
+
print(f"{p:<7}{t['name']:<40}{kind:<8}{desc}")
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def describe(platform: str, tool: str) -> None:
|
|
160
|
+
for t in list_tools(platform):
|
|
161
|
+
if t["name"] == tool:
|
|
162
|
+
print(json.dumps({k: t.get(k) for k in ("name", "description", "inputSchema", "annotations")}, indent=2))
|
|
163
|
+
return
|
|
164
|
+
raise Fail(f"No tool {tool!r} on {platform}. Run `adsync tools {platform}`.")
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def save_token(t: str) -> None:
|
|
168
|
+
f = token_file()
|
|
169
|
+
f.parent.mkdir(parents=True, exist_ok=True)
|
|
170
|
+
fd = os.open(f, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
|
171
|
+
with os.fdopen(fd, "w") as out:
|
|
172
|
+
out.write(t + "\n")
|
|
173
|
+
os.chmod(f, 0o600) # in case the file already existed with wider permissions
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def browser_login() -> str:
|
|
177
|
+
"""MCP OAuth 2.1 with PKCE and a loopback redirect: the same consent page Claude Code's own MCP sign-in uses."""
|
|
178
|
+
got: dict = {}
|
|
179
|
+
|
|
180
|
+
class Handler(BaseHTTPRequestHandler):
|
|
181
|
+
def do_GET(self):
|
|
182
|
+
u = urllib.parse.urlsplit(self.path)
|
|
183
|
+
if u.path != "/callback":
|
|
184
|
+
self.send_response(404)
|
|
185
|
+
self.end_headers()
|
|
186
|
+
return
|
|
187
|
+
got.update(urllib.parse.parse_qsl(u.query))
|
|
188
|
+
self.send_response(200)
|
|
189
|
+
self.send_header("Content-Type", "text/html; charset=utf-8")
|
|
190
|
+
self.end_headers()
|
|
191
|
+
self.wfile.write(b"<p style='font-family:sans-serif'>AdSync CLI signed in. You can close this tab.</p>")
|
|
192
|
+
|
|
193
|
+
def log_message(self, *_):
|
|
194
|
+
pass
|
|
195
|
+
|
|
196
|
+
server = HTTPServer(("127.0.0.1", 0), Handler)
|
|
197
|
+
server.timeout = 5
|
|
198
|
+
redirect = f"http://127.0.0.1:{server.server_port}/callback"
|
|
199
|
+
base = base_url()
|
|
200
|
+
client = post(f"{base}/register", json.dumps({"client_name": "AdSync CLI", "redirect_uris": [redirect]}).encode(),
|
|
201
|
+
{"Content-Type": "application/json"})
|
|
202
|
+
verifier = secrets.token_urlsafe(48)
|
|
203
|
+
challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).rstrip(b"=").decode()
|
|
204
|
+
state = secrets.token_urlsafe(16)
|
|
205
|
+
url = f"{base}/authorize?" + urllib.parse.urlencode({
|
|
206
|
+
"client_id": client["client_id"], "redirect_uri": redirect, "response_type": "code", "state": state,
|
|
207
|
+
"code_challenge": challenge, "code_challenge_method": "S256",
|
|
208
|
+
})
|
|
209
|
+
print(f"Opening your browser to sign in. If it does not open, visit:\n{url}\n"
|
|
210
|
+
"On a remote machine (SSH, container), stop with Ctrl-C and run `adsync login --paste` instead.",
|
|
211
|
+
file=sys.stderr)
|
|
212
|
+
webbrowser.open(url)
|
|
213
|
+
deadline = time.monotonic() + 300
|
|
214
|
+
try:
|
|
215
|
+
while not got: # stray requests (a favicon, a prefetch) land on the 404 branch and we keep waiting
|
|
216
|
+
if time.monotonic() > deadline:
|
|
217
|
+
raise Fail("Timed out waiting for the browser sign-in.")
|
|
218
|
+
server.handle_request()
|
|
219
|
+
finally:
|
|
220
|
+
server.server_close()
|
|
221
|
+
if got.get("state") != state:
|
|
222
|
+
raise Fail("Sign-in state did not match. Run `adsync login` again.")
|
|
223
|
+
if "error" in got:
|
|
224
|
+
raise Fail(got.get("error_description") or got["error"])
|
|
225
|
+
form = urllib.parse.urlencode({"grant_type": "authorization_code", "code": got.get("code", ""),
|
|
226
|
+
"redirect_uri": redirect, "client_id": client["client_id"],
|
|
227
|
+
"code_verifier": verifier}).encode()
|
|
228
|
+
return post(f"{base}/token", form, {"Content-Type": "application/x-www-form-urlencoded"})["access_token"]
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def login(paste: bool) -> None:
|
|
232
|
+
t = getpass("Paste an AdSync token (input hidden): ").strip() if paste else browser_login()
|
|
233
|
+
if not t:
|
|
234
|
+
raise Fail("No token given.")
|
|
235
|
+
os.environ["ADSYNC_TOKEN"] = t
|
|
236
|
+
list_tools("meta") # fails with a clear message if the token does not work
|
|
237
|
+
save_token(t)
|
|
238
|
+
print(f"Signed in. Token saved to {token_file()}.", file=sys.stderr)
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def install_skills(dest: Path) -> None:
|
|
242
|
+
src = files("adsync") / "skills"
|
|
243
|
+
for skill in src.iterdir():
|
|
244
|
+
if skill.is_dir():
|
|
245
|
+
target = dest / skill.name
|
|
246
|
+
target.mkdir(parents=True, exist_ok=True)
|
|
247
|
+
with (skill / "SKILL.md").open("rb") as r, open(target / "SKILL.md", "wb") as w:
|
|
248
|
+
shutil.copyfileobj(r, w)
|
|
249
|
+
print(f"Installed {target / 'SKILL.md'}", file=sys.stderr)
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def main(argv: list[str] | None = None) -> int:
|
|
253
|
+
p = argparse.ArgumentParser(prog="adsync", description="Run AdSync ad platform tools from a shell.")
|
|
254
|
+
p.add_argument("--version", action="version", version=__version__)
|
|
255
|
+
sub = p.add_subparsers(dest="cmd", required=True)
|
|
256
|
+
lg = sub.add_parser("login", help="sign in (browser by default)")
|
|
257
|
+
lg.add_argument("--paste", action="store_true", help="paste a token from the dashboard instead")
|
|
258
|
+
sub.add_parser("logout", help="forget the saved token (revoke it in the dashboard)")
|
|
259
|
+
tl = sub.add_parser("tools", help="list tools")
|
|
260
|
+
tl.add_argument("platform", nargs="?", choices=PLATFORMS)
|
|
261
|
+
ds = sub.add_parser("describe", help="show a tool's description and arguments")
|
|
262
|
+
ds.add_argument("platform", choices=PLATFORMS)
|
|
263
|
+
ds.add_argument("tool")
|
|
264
|
+
sk = sub.add_parser("skill", help="install the AdSync skills for Claude Code")
|
|
265
|
+
sk.add_argument("action", choices=["install"])
|
|
266
|
+
sk.add_argument("--dir", type=Path, default=Path.home() / ".claude" / "skills",
|
|
267
|
+
help="skills folder (default ~/.claude/skills; use .claude/skills for one project)")
|
|
268
|
+
for name in PLATFORMS:
|
|
269
|
+
c = sub.add_parser(name, help=f"call a {name} tool")
|
|
270
|
+
c.add_argument("tool")
|
|
271
|
+
c.add_argument("args", nargs="*", help="key=value (string) or key:=json")
|
|
272
|
+
c.add_argument("--json", help="all arguments as a JSON object, or - to read it from stdin")
|
|
273
|
+
a = p.parse_args(argv)
|
|
274
|
+
try:
|
|
275
|
+
if a.cmd == "login":
|
|
276
|
+
login(a.paste)
|
|
277
|
+
elif a.cmd == "logout":
|
|
278
|
+
token_file().unlink(missing_ok=True)
|
|
279
|
+
print("Token removed from this machine. Revoke it in the AdSync dashboard to stop it everywhere.", file=sys.stderr)
|
|
280
|
+
elif a.cmd == "tools":
|
|
281
|
+
show_tools(a.platform)
|
|
282
|
+
elif a.cmd == "describe":
|
|
283
|
+
describe(a.platform, a.tool)
|
|
284
|
+
elif a.cmd == "skill":
|
|
285
|
+
install_skills(a.dir)
|
|
286
|
+
else:
|
|
287
|
+
return call(a.cmd, a.tool, parse_args(a.args, a.json))
|
|
288
|
+
except Fail as e:
|
|
289
|
+
print(f"adsync: {e}", file=sys.stderr)
|
|
290
|
+
return 1
|
|
291
|
+
except json.JSONDecodeError as e:
|
|
292
|
+
print(f"adsync: invalid JSON: {e}", file=sys.stderr)
|
|
293
|
+
return 1
|
|
294
|
+
except KeyboardInterrupt:
|
|
295
|
+
return 130
|
|
296
|
+
return 0
|
adsync/__main__.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: adsync
|
|
3
|
+
description: Use the adsync CLI to read and change Meta (Facebook and Instagram) Ads, Google Ads, Google Analytics 4 and Search Console through AdSync. Use when the user asks about their ad accounts, campaigns, ad sets, ads, keywords, audiences, creatives, spend or performance, or mentions AdSync, and `adsync` is on the PATH.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# AdSync CLI
|
|
7
|
+
|
|
8
|
+
`adsync` calls the same hosted tools as the AdSync MCP servers. The user's token decides what you may do: some tokens are read-only or limited to certain tools and accounts. Every call shows up in the user's AdSync Activity log.
|
|
9
|
+
|
|
10
|
+
## Setup
|
|
11
|
+
|
|
12
|
+
- `adsync tools meta` failing with "Not signed in" means the user must run `adsync login` themselves (it opens a browser). Do not ask them to paste a token into the chat.
|
|
13
|
+
- Not installed: `uv tool install adsync-cli` (or `pipx install adsync-cli`). The command is still `adsync`.
|
|
14
|
+
|
|
15
|
+
## Find the right tool
|
|
16
|
+
|
|
17
|
+
Platforms: `meta`, `google` (Google Ads), `ga` (GA4), `gsc` (Search Console).
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
adsync tools google # name, read/write/delete, one-line description
|
|
21
|
+
adsync describe google get_search_terms # full description and argument schema
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
Run `describe` before the first call to any tool. Do not guess argument names.
|
|
25
|
+
|
|
26
|
+
## Call a tool
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
adsync meta list_ad_accounts
|
|
30
|
+
adsync meta get_insights account_id=act_123 level=ad date_preset=last_7d
|
|
31
|
+
adsync meta get_insights account_id=act_123 fields:='["spend","ctr","actions"]' breakdowns:='["age"]'
|
|
32
|
+
adsync google run_gaql --json '{"account_id":"1234567890","query":"SELECT campaign.name FROM campaign"}'
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
- `key=value` sends a string; the server turns "100" and "true" into numbers and booleans where the schema wants them.
|
|
36
|
+
- `key:=json` sends raw JSON: lists, objects, null.
|
|
37
|
+
- `--json '{...}'` sends everything at once; `--json -` reads it from stdin.
|
|
38
|
+
- Output is compact JSON on stdout. Pipe it to `jq` or save it to a file instead of printing large results in full.
|
|
39
|
+
- Meta lists come wrapped as `{"data": [...]}` (use `jq '.data'`). `"has_more": true` means more rows exist past `limit`: call again with a higher limit.
|
|
40
|
+
- Tools that return a picture (`get_ad_image`, `get_image_by_hash`) save it to a temp file and print `Image saved to <path>` on stderr. Open that file to look at the creative.
|
|
41
|
+
- Errors go to stderr with exit code 1. Read the message: it says what to fix (wrong account, read-only token, reconnect needed, budget change too large).
|
|
42
|
+
- Plan limits come back as errors too: a Pro-only tool on the Free plan, the Free plan's weekly call limit, or more ad accounts turned on than the plan's slots. Tell the user what the message says and stop. Don't retry or work around it. `tools` and `describe` don't count as calls.
|
|
43
|
+
|
|
44
|
+
## Start every task with
|
|
45
|
+
|
|
46
|
+
1. `adsync <platform> list_ad_accounts` (`list_properties` for ga, `list_sites` for gsc) to get ids.
|
|
47
|
+
2. `adsync <platform> get_team_context` for the team's goals, targets and naming conventions. Follow them.
|
|
48
|
+
|
|
49
|
+
## Units and safety
|
|
50
|
+
|
|
51
|
+
- Meta budgets, bids, spend caps and balances (`daily_budget`, `lifetime_budget`, `bid_amount`, `spend_cap`, `amount_spent`, `balance`) are in minor units (cents): `daily_budget=5000` is 50.00 in the account currency. Results add a `*_display` twin with the plain amount: show that to people, and write budgets in minor units.
|
|
52
|
+
- Meta insights (`spend`, `cpc`, `cpm`, `cost_per_action_type`) are already in plain currency. Don't divide them.
|
|
53
|
+
- Google Ads money is in micros: 1,000,000 micros is 1.00.
|
|
54
|
+
- New campaigns, ad sets, ad groups and ads are created PAUSED. Say so, and let the user turn them on.
|
|
55
|
+
- Budget, bid and target changes are capped per call (50% by default). Larger moves need several steps over days.
|
|
56
|
+
- Write tools return `before` and `after`. Show both to the user.
|
|
57
|
+
- Before any write or delete, say exactly what will change and wait for the user's go-ahead, unless they already asked for that exact change.
|
|
58
|
+
- Search Console data lags two to three days: end date ranges three days ago.
|
|
59
|
+
|
|
60
|
+
For audits, fatigue checks, search term cleanups, pacing and reports, use the `adsync-playbooks` skill.
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: adsync-playbooks
|
|
3
|
+
description: Performance marketing playbooks for AdSync. Covers a weekly account audit, Meta creative fatigue, a Google search terms cleanup, budget pacing and a performance report. Use when the user asks to audit an ad account, find wasted spend, check creative fatigue, clean up search terms or add negatives, pace budgets, or write a performance report, whether through the adsync CLI or the AdSync MCP tools.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# AdSync playbooks
|
|
7
|
+
|
|
8
|
+
Tool names below are the same in the `adsync` CLI (`adsync meta get_insights ...`) and the AdSync MCP servers. Run `adsync describe <platform> <tool>` (or read the MCP schema) before the first call to each tool.
|
|
9
|
+
|
|
10
|
+
## Rules for every playbook
|
|
11
|
+
|
|
12
|
+
1. **Context first.** Call `get_team_context`. Use the team's CPA, ROAS and budget targets. If there are none, ask the user for the target, or compare with the account's own 30-day average and say that is what you did.
|
|
13
|
+
2. **Read, then propose.** Gather data, show findings and a numbered list of proposed changes, and wait for approval. Make only the approved changes.
|
|
14
|
+
3. **Pause, don't delete.** Use `update_status` (Meta) or `update_campaign_status`, `update_ad_status` and `update_keyword_status` (Google) set to PAUSED. Deleting loses history.
|
|
15
|
+
4. **Small steps.** Move budgets 20% or less per change. Bigger jumps reset Meta's learning phase and unsettle Google's Smart Bidding. AdSync refuses anything over its per-call cap.
|
|
16
|
+
5. **Enough data.** Don't judge anything with under about 1,000 impressions, or under 2x the target CPA in spend with no conversion. Call it "too early" instead.
|
|
17
|
+
6. **Units.** Meta budgets and bids are in cents (show their `*_display` twins). Meta insights such as `spend` and `cpc` are already in plain currency. Google money is in micros everywhere (`cost_micros`, `average_cpc`, budgets): divide by 1,000,000.
|
|
18
|
+
7. **Show the numbers.** Every recommendation names the metric, the period and the threshold it crossed.
|
|
19
|
+
|
|
20
|
+
## 1. Weekly account audit
|
|
21
|
+
|
|
22
|
+
Use when asked to "audit", "check", or "what's wrong with" an account.
|
|
23
|
+
|
|
24
|
+
1. List accounts and pick the one the user means. Note its currency and time zone.
|
|
25
|
+
2. Pull the last 7 days and the 28 days before them at campaign level:
|
|
26
|
+
- Meta: `get_insights level=campaign date_preset=last_7d`, then `since`/`until` for the earlier 28 days.
|
|
27
|
+
- Google: `get_campaign_performance date_range=LAST_7_DAYS`, then `since`/`until` for the earlier period.
|
|
28
|
+
3. Flag:
|
|
29
|
+
- **Waste:** spend of 2x or more the target CPA with zero conversions.
|
|
30
|
+
- **Drift:** CPA up 30% or more, or ROAS down 30% or more, against the earlier period.
|
|
31
|
+
- **Not serving:** enabled campaigns with zero impressions. On Google, run `check_campaign_serving` for each one.
|
|
32
|
+
- **Budget-capped winners:** CPA under target with spend at or near the daily budget. These are candidates for more budget.
|
|
33
|
+
4. Report the findings grouped by these four headings, worst spend first. Then list the proposed changes.
|
|
34
|
+
|
|
35
|
+
## 2. Creative fatigue (Meta)
|
|
36
|
+
|
|
37
|
+
1. `get_insights level=ad date_preset=last_28d time_increment=7` for weekly rows per ad.
|
|
38
|
+
2. An ad is fatigued when, over the last two weeks against its first two:
|
|
39
|
+
- frequency is above 3 (prospecting) or 6 (retargeting), and
|
|
40
|
+
- CTR fell 25% or more, or CPA rose 25% or more.
|
|
41
|
+
3. For each fatigued ad, give the numbers and its ad set's other active ads. If the ad set would be left with fewer than two active ads, propose a replacement before pausing.
|
|
42
|
+
4. Offer to duplicate a strong ad with a new creative (`duplicate_ad`, then `update_ad`). Copies are created PAUSED.
|
|
43
|
+
|
|
44
|
+
## 3. Search terms cleanup (Google)
|
|
45
|
+
|
|
46
|
+
1. `get_search_terms date_range=LAST_30_DAYS`, highest cost first.
|
|
47
|
+
2. `get_negative_keywords` for the same campaigns, so you don't propose duplicates.
|
|
48
|
+
3. Candidates for negatives:
|
|
49
|
+
- spend of at least the target CPA (or 1.5x the average CPC times 20) with zero conversions, or
|
|
50
|
+
- clearly irrelevant intent (jobs, free, DIY, competitor names unless the team targets them), whatever the spend.
|
|
51
|
+
4. Propose each one with its match type. Use EXACT for single wasteful queries and PHRASE for a recurring word. Never propose a negative that would block a converting term: check the list against terms with conversions first.
|
|
52
|
+
5. After approval, `add_negative_keywords` at campaign level unless the user asks for ad group level.
|
|
53
|
+
|
|
54
|
+
## 4. Budget pacing
|
|
55
|
+
|
|
56
|
+
1. Ask for the monthly budget per account or campaign, or take it from team context.
|
|
57
|
+
2. Pull month-to-date spend (Meta `date_preset=this_month`; Google `date_range=THIS_MONTH`) and current daily budgets (Meta `list_campaigns`/`list_adsets`, Google `list_budgets`).
|
|
58
|
+
3. Projected spend = month-to-date spend / days elapsed * days in month.
|
|
59
|
+
4. Within 5% of plan, report and change nothing. Otherwise propose new daily budgets that land on plan, capped at 20% per change. Put more of any increase on campaigns under target CPA, and take any cut from those over it.
|
|
60
|
+
5. Google shared budgets can't be changed per campaign: point them out instead.
|
|
61
|
+
|
|
62
|
+
## 5. Performance report
|
|
63
|
+
|
|
64
|
+
Use for "how did we do", weekly or monthly reports, and client updates.
|
|
65
|
+
|
|
66
|
+
1. Pick the period (default: last 7 days against the 7 before) and the main result (purchases, leads or conversions). Take it from team context or ask.
|
|
67
|
+
2. Write the sections in this order:
|
|
68
|
+
- **Summary:** three lines covering spend, results, cost per result or ROAS, and the change against last period.
|
|
69
|
+
- **By platform:** a table of spend, results, CPA, ROAS and change, one row per platform.
|
|
70
|
+
- **By campaign:** the top 5 by spend, plus anything flagged by the audit thresholds.
|
|
71
|
+
- **What worked, what didn't:** two or three points each, every one backed by a number.
|
|
72
|
+
- **Next steps:** at most five actions, each with its expected effect.
|
|
73
|
+
3. If GA4 or Search Console are connected and relevant, add sessions and conversions from `run_report`, or clicks and position from `query_search_analytics`, as a separate section. Don't mix them with platform-reported conversions.
|
|
74
|
+
4. Plain words, no jargon the reader didn't use first. Round money to whole units and rates to one decimal.
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: adsync-cli
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Command line client for AdSync: run Meta Ads, Google Ads, GA4 and Search Console tools from a shell.
|
|
5
|
+
Project-URL: Homepage, https://getadsync.com
|
|
6
|
+
Requires-Python: >=3.10
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
|
|
9
|
+
# adsync
|
|
10
|
+
|
|
11
|
+
Command line client for [AdSync](https://getadsync.com). Run Meta Ads, Google Ads, Google Analytics 4 and Search Console tools from a shell, with the same scoped tokens, Activity log and safety rules as the AdSync MCP servers.
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
uv tool install adsync-cli # or: pipx install adsync-cli
|
|
15
|
+
adsync login # opens the browser; or: adsync login --paste
|
|
16
|
+
adsync skill install # adds the AdSync skills to ~/.claude/skills for Claude Code
|
|
17
|
+
adsync tools meta
|
|
18
|
+
adsync describe meta get_insights
|
|
19
|
+
adsync meta get_insights account_id=act_123 date_preset=last_7d
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
- `key=value` sends a string, `key:=json` sends raw JSON, `--json '{...}'` (or `--json -` for stdin) sends all arguments at once.
|
|
23
|
+
- Output is JSON on stdout; errors go to stderr with exit code 1.
|
|
24
|
+
- `ADSYNC_TOKEN` overrides the saved token (`~/.config/adsync/token`), for CI and cron.
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
adsync/__init__.py,sha256=LhBCXy7qqm7HLzZzJ68X_b6eDUxzVwJUnaaacz7daWE,12578
|
|
2
|
+
adsync/__main__.py,sha256=XnpTzfJc0T-j9tHtdkA8ovTr1c139ffTewcJGhxYDaM,49
|
|
3
|
+
adsync/skills/adsync/SKILL.md,sha256=wtwik2q_h5GU4GY_lEsiXLKiuzUuLfWOVB_UWH4uYvg,4081
|
|
4
|
+
adsync/skills/adsync-playbooks/SKILL.md,sha256=_6NxaJtxAGqSxIJ71Ae8kOL5Nu1uiPL7zd_0GLIVCrI,6070
|
|
5
|
+
adsync_cli-0.1.0.dist-info/METADATA,sha256=MfNqOF5tn3nKu7M3kwo_M3ysJZb2XH8cCwDqK4o4rfE,1152
|
|
6
|
+
adsync_cli-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
7
|
+
adsync_cli-0.1.0.dist-info/entry_points.txt,sha256=APOeokdJ2rxBh1OrrHKBYcFIzpCNUsV20FwOsCUgKsg,39
|
|
8
|
+
adsync_cli-0.1.0.dist-info/RECORD,,
|