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.
adstack/engine.py ADDED
@@ -0,0 +1,178 @@
1
+ """The workflow shared by the CLI and the MCP server: create, verify and apply plans."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ from collections.abc import Collection, Mapping
8
+ from dataclasses import dataclass, field, replace
9
+ from datetime import UTC, datetime
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ from . import __version__
14
+ from .config import Config, load_sources
15
+ from .errors import PlanError, ProviderError
16
+ from .plan import GATES, PLAN_FORMAT, body, counts, fingerprint, plan_hash
17
+ from .providers import Backend, get_provider
18
+
19
+ DATA_DIR = ".adstack"
20
+ RECEIPT_FORMAT = "adstack-receipt/1"
21
+
22
+
23
+ @dataclass(frozen=True)
24
+ class Workspace:
25
+ """Where Adstack keeps local files (``.adstack/``) and whether it talks to the sandbox."""
26
+
27
+ root: Path = field(default_factory=Path.cwd)
28
+ sandbox: bool = False
29
+ env: Mapping[str, str] = field(default_factory=lambda: dict(os.environ))
30
+
31
+ @property
32
+ def data_dir(self) -> Path:
33
+ return Path(self.root) / DATA_DIR
34
+
35
+
36
+ def connect(config: Config, workspace: Workspace) -> Backend:
37
+ provider = get_provider(config.provider)
38
+ sandbox_dir = workspace.data_dir / "sandbox" if workspace.sandbox else None
39
+ return provider.connect(config.desired, sandbox_dir=sandbox_dir, env=workspace.env)
40
+
41
+
42
+ def target_label(provider_name: str, backend: Backend) -> str:
43
+ provider = get_provider(provider_name)
44
+ kind = "sandbox account" if backend.sandbox else "account"
45
+ return f"{provider.title} {kind} {provider.format_account(backend.account)}"
46
+
47
+
48
+ def create_plan(
49
+ config: Config,
50
+ workspace: Workspace,
51
+ *,
52
+ prune: bool = False,
53
+ destroy: bool = False,
54
+ backend: Backend | None = None,
55
+ ) -> dict[str, Any]:
56
+ """Read the account and compute a plan. Nothing in the account changes."""
57
+ if prune and destroy:
58
+ raise PlanError("--prune and --destroy cannot be combined")
59
+ provider = get_provider(config.provider)
60
+ backend = backend or connect(config, workspace)
61
+ state = backend.read()
62
+ result = provider.plan(config.desired, state, backend.account, prune=prune, destroy=destroy)
63
+ return {
64
+ "format": PLAN_FORMAT,
65
+ "adstack_version": __version__,
66
+ "created_at": _now(),
67
+ "provider": config.provider,
68
+ "backend": "sandbox" if backend.sandbox else "api",
69
+ "account": backend.account,
70
+ "target": target_label(config.provider, backend),
71
+ "options": {"prune": prune, "destroy": destroy},
72
+ "config": {"files": dict(sorted(config.sources.items())), "summary": config.summary()},
73
+ "config_hash": fingerprint(config.desired),
74
+ "state_hash": fingerprint(state),
75
+ "summary": counts(result["changes"]),
76
+ "changes": result["changes"],
77
+ "blockers": result["blockers"],
78
+ "requires": result["requires"],
79
+ "operations": result["operations"],
80
+ }
81
+
82
+
83
+ def verify(plan: dict[str, Any], workspace: Workspace) -> tuple[dict[str, Any], Backend]:
84
+ """Recompute a saved plan from its embedded configuration and the account's current state.
85
+
86
+ Raises PlanError unless the result is identical, so a plan can only be applied
87
+ while it still describes exactly what will happen.
88
+ """
89
+ if plan.get("format") != PLAN_FORMAT:
90
+ raise PlanError("not an Adstack plan (or one from an incompatible version)")
91
+ files = plan.get("config", {}).get("files") if isinstance(plan.get("config"), dict) else None
92
+ if not isinstance(files, dict):
93
+ raise PlanError("the plan does not contain its configuration")
94
+ config = load_sources(files)
95
+ if config.provider != plan.get("provider") or fingerprint(config.desired) != plan.get("config_hash"):
96
+ raise PlanError("the plan's embedded configuration does not match its hash; the plan file was modified")
97
+ workspace = replace(workspace, sandbox=plan.get("backend") == "sandbox")
98
+ backend = connect(config, workspace)
99
+ if backend.account != plan.get("account"):
100
+ raise PlanError(
101
+ f"this plan targets account {plan.get('account')}, but the configuration and environment now "
102
+ f"target {backend.account}"
103
+ )
104
+ options = plan.get("options") if isinstance(plan.get("options"), dict) else {}
105
+ fresh = create_plan(
106
+ config,
107
+ workspace,
108
+ prune=bool(options.get("prune")),
109
+ destroy=bool(options.get("destroy")),
110
+ backend=backend,
111
+ )
112
+ if body(fresh) != body(plan):
113
+ raise PlanError(
114
+ "the account or the configuration changed after this plan was created; create a new plan and review it"
115
+ )
116
+ return fresh, backend
117
+
118
+
119
+ def missing_permissions(plan: dict[str, Any], allow: Collection[str]) -> list[str]:
120
+ return [gate for gate in GATES if plan["requires"].get(gate) and gate not in allow]
121
+
122
+
123
+ def apply(
124
+ plan: dict[str, Any],
125
+ workspace: Workspace,
126
+ *,
127
+ allow: Collection[str] = (),
128
+ verified: tuple[dict[str, Any], Backend] | None = None,
129
+ ) -> tuple[dict[str, Any], Path] | None:
130
+ """Apply a reviewed plan after verifying it is still current.
131
+
132
+ The platform validates the whole request first; then it is applied atomically and a
133
+ receipt is written to ``.adstack/receipts/``. Returns ``(receipt, path)``, or None
134
+ when there is nothing to do.
135
+ """
136
+ fresh, backend = verified if verified is not None else verify(plan, workspace)
137
+ if fresh["blockers"]:
138
+ raise PlanError("this plan has blockers and cannot be applied: " + "; ".join(fresh["blockers"]))
139
+ if not fresh["operations"]:
140
+ return None
141
+ missing = missing_permissions(fresh, allow)
142
+ if missing:
143
+ needed = ", ".join(f"{gate} ({GATES[gate]})" for gate in missing)
144
+ raise PlanError(f"applying this plan needs explicit permission: {needed}")
145
+ receipts = workspace.data_dir / "receipts"
146
+ receipts.mkdir(parents=True, exist_ok=True)
147
+ backend.mutate(fresh["operations"], validate_only=True)
148
+ response = backend.mutate(fresh["operations"], validate_only=False)
149
+ digest = plan_hash(fresh)
150
+ receipt = {
151
+ "format": RECEIPT_FORMAT,
152
+ "applied_at": _now(),
153
+ "adstack_version": __version__,
154
+ "provider": fresh["provider"],
155
+ "backend": fresh["backend"],
156
+ "account": fresh["account"],
157
+ "target": fresh["target"],
158
+ "plan_sha256": digest,
159
+ "summary": fresh["summary"],
160
+ "changes": fresh["changes"],
161
+ "response": response,
162
+ }
163
+ path = receipts / f"{_now(compact=True)}-{digest[:12]}.json"
164
+ try:
165
+ with path.open("x", encoding="utf-8") as file:
166
+ json.dump(receipt, file, indent=2, ensure_ascii=False)
167
+ file.write("\n")
168
+ except OSError as exc:
169
+ raise ProviderError(
170
+ f"The changes were applied, but writing the receipt to {path} failed ({exc}). "
171
+ "Run plan before making further changes."
172
+ ) from exc
173
+ return receipt, path
174
+
175
+
176
+ def _now(*, compact: bool = False) -> str:
177
+ now = datetime.now(UTC)
178
+ return now.strftime("%Y%m%dT%H%M%SZ") if compact else now.strftime("%Y-%m-%dT%H:%M:%SZ")
adstack/errors.py ADDED
@@ -0,0 +1,17 @@
1
+ """Exceptions that Adstack reports to people as plain messages, without a traceback."""
2
+
3
+
4
+ class AdstackError(Exception):
5
+ """Base class for expected failures: invalid configuration, unsafe plans, API errors."""
6
+
7
+
8
+ class ConfigError(AdstackError):
9
+ """The configuration is invalid."""
10
+
11
+
12
+ class PlanError(AdstackError):
13
+ """A plan cannot be created or applied safely."""
14
+
15
+
16
+ class ProviderError(AdstackError):
17
+ """The ad platform (or the local sandbox) rejected a request or could not be reached."""
adstack/mcp_server.py ADDED
@@ -0,0 +1,330 @@
1
+ """Model Context Protocol server: AI assistants can validate, plan and (optionally) apply configurations.
2
+
3
+ Run it with ``adstack mcp``. Tools accept a configuration path relative to the
4
+ server's root directory, or configuration text. Planning reads the ad account
5
+ and changes nothing. The ``apply`` tool exists only when the server uses the
6
+ sandbox or was started with ``--allow-apply``, and even then it accepts only a
7
+ plan the server created, re-verifies it against the live account, requires the
8
+ account ID as confirmation and the same explicit permissions as the CLI.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import os
14
+ import re
15
+ from collections.abc import Iterator, Mapping
16
+ from contextlib import contextmanager, suppress
17
+ from pathlib import Path
18
+ from typing import Any, Literal
19
+
20
+ from mcp.server import MCPServer
21
+ from mcp.server.mcpserver.exceptions import ToolError
22
+ from mcp.types import ToolAnnotations
23
+
24
+ from . import __version__, engine
25
+ from . import plan as plans
26
+ from .config import Config, load, load_sources
27
+ from .errors import AdstackError, ConfigError, PlanError
28
+ from .providers import get_provider
29
+ from .scaffold import STARTER_CONFIG
30
+
31
+ _PLAN_ID = re.compile(r"[0-9a-f]{16}")
32
+
33
+ _WORKFLOW = """\
34
+ Adstack manages advertising campaigns as code. A YAML configuration declares the campaigns; Adstack \
35
+ compares it with the ad account and plans the changes, like Terraform.
36
+
37
+ Workflow:
38
+ 1. Write or edit a configuration. Call example_config for an annotated example of every option. \
39
+ validate checks a configuration offline and reports the exact problem.
40
+ 2. Call plan to see what would change. Planning reads the account but changes nothing.
41
+ 3. Show the user plan_text (every change, blocker and required permission) and ask whether to apply it.
42
+ """
43
+
44
+ _APPLY_RULES = """\
45
+ 4. Only after the user explicitly approves that specific plan, call apply with its plan_id and the account ID.
46
+
47
+ Rules:
48
+ - Never call apply without the user's explicit approval of the plan, and never reuse an old approval.
49
+ - Set allow_enable, allow_budget_increase or allow_live_changes only when the plan requires it and the user \
50
+ approved that effect.
51
+ - If apply reports that the account changed, plan again and ask for approval again.
52
+ """
53
+
54
+ _NO_APPLY = """\
55
+ This server cannot apply changes. To apply a plan, the user can run 'adstack plan --out FILE' and \
56
+ 'adstack apply FILE' in a terminal, or restart this server with --allow-apply.
57
+ """
58
+
59
+ _NOTES = """\
60
+ Notes: new campaigns are always created PAUSED, and enabling one is a separate plan. Amounts are in the \
61
+ account currency. daily_budget is the platform's average daily budget, not a hard cap.
62
+ """
63
+
64
+
65
+ def instructions(*, sandbox: bool, can_apply: bool) -> str:
66
+ mode = (
67
+ "This server uses a local sandbox account: nothing reaches a real ad platform.\n"
68
+ if sandbox
69
+ else "This server is connected to the real ad platform: applied changes spend real money.\n"
70
+ )
71
+ return _WORKFLOW + (_APPLY_RULES if can_apply else _NO_APPLY) + _NOTES + mode
72
+
73
+
74
+ @contextmanager
75
+ def _tool_errors() -> Iterator[None]:
76
+ """Report Adstack's expected errors to the client with their message."""
77
+ try:
78
+ yield
79
+ except AdstackError as exc:
80
+ raise ToolError(str(exc)) from None
81
+
82
+
83
+ def _inside(root: Path, path: str) -> Path:
84
+ candidate = (root / path).resolve()
85
+ if candidate != root and root not in candidate.parents:
86
+ raise ToolError(f"{path!r} is outside the server's root directory")
87
+ return candidate
88
+
89
+
90
+ def create_server(
91
+ root: str | Path,
92
+ *,
93
+ sandbox: bool = False,
94
+ allow_apply: bool = False,
95
+ env: Mapping[str, str] | None = None,
96
+ ) -> MCPServer:
97
+ root = Path(root).resolve()
98
+ workspace = engine.Workspace(root=root, sandbox=sandbox, env=dict(os.environ) if env is None else dict(env))
99
+ plans_dir = workspace.data_dir / "plans"
100
+ can_apply = allow_apply or sandbox
101
+ server = MCPServer(
102
+ "adstack",
103
+ title="Adstack",
104
+ description="Advertising campaigns as code: validate, plan and apply ad configurations.",
105
+ instructions=instructions(sandbox=sandbox, can_apply=can_apply),
106
+ version=__version__,
107
+ )
108
+
109
+ def read_config(path: str | None, config: str | None) -> Config:
110
+ if config is not None:
111
+ if path:
112
+ raise ToolError("pass either path or config, not both")
113
+ return load_sources({"config.yaml": config})
114
+ return load(_inside(root, path or "."))
115
+
116
+ def store(plan: dict[str, Any]) -> str:
117
+ plan_id = plans.plan_hash(plan)[:16]
118
+ target = plans_dir / f"{plan_id}.json"
119
+ if not target.exists():
120
+ plans_dir.mkdir(parents=True, exist_ok=True)
121
+ with suppress(PlanError): # saved concurrently: identical content
122
+ plans.save(plan, target)
123
+ return plan_id
124
+
125
+ def stored(plan_id: str) -> dict[str, Any]:
126
+ if not _PLAN_ID.fullmatch(plan_id):
127
+ raise ToolError("plan_id must be the 16-character ID returned by the plan tool")
128
+ target = plans_dir / f"{plan_id}.json"
129
+ if not target.is_file():
130
+ raise ToolError(f"no plan with ID {plan_id}; call plan to create one")
131
+ return plans.load(target)
132
+
133
+ def describe(plan: dict[str, Any], plan_id: str | None) -> dict[str, Any]:
134
+ required = [gate for gate, needed in plan["requires"].items() if needed]
135
+ if plan["blockers"]:
136
+ next_step = (
137
+ "This plan is blocked and cannot be applied. Resolve the blockers or plan with prune=true "
138
+ "where suggested."
139
+ )
140
+ elif not plan["operations"]:
141
+ next_step = "Nothing to do: the account matches the configuration."
142
+ elif can_apply:
143
+ permissions = f" with {', '.join(f'{gate}=true' for gate in required)}" if required else ""
144
+ next_step = (
145
+ "Show plan_text to the user and ask for approval. Only if they explicitly approve, call apply with "
146
+ f"plan_id={plan_id} and confirm_account={plan['account']}{permissions}."
147
+ )
148
+ else:
149
+ next_step = "Show plan_text to the user. " + _NO_APPLY.strip()
150
+ return {
151
+ "plan_id": plan_id,
152
+ "target": plan["target"],
153
+ "account": plan["account"],
154
+ "sandbox": plan["backend"] == "sandbox",
155
+ "summary": plan["summary"],
156
+ "has_changes": bool(plan["operations"]),
157
+ "blockers": plan["blockers"],
158
+ "requires": required,
159
+ "plan_text": plans.render(plan),
160
+ "changes": plan["changes"],
161
+ "next_step": next_step,
162
+ }
163
+
164
+ @server.tool(
165
+ annotations=ToolAnnotations(
166
+ title="Validate a configuration", readOnlyHint=True, idempotentHint=True, openWorldHint=False
167
+ )
168
+ )
169
+ def validate(path: str | None = None, config: str | None = None) -> dict[str, Any]:
170
+ """Check an Adstack configuration offline, without contacting the ad platform.
171
+
172
+ Pass `path` (a YAML file or a directory of YAML files, relative to the server's root;
173
+ default: the root) or `config` (YAML text). Returns valid=true with a summary, or
174
+ valid=false with the exact problem.
175
+ """
176
+ try:
177
+ loaded = read_config(path, config)
178
+ except ConfigError as exc:
179
+ return {"valid": False, "error": str(exc)}
180
+ except AdstackError as exc:
181
+ raise ToolError(str(exc)) from None
182
+ return {"valid": True, "provider": loaded.provider, "summary": loaded.summary()}
183
+
184
+ @server.tool(
185
+ annotations=ToolAnnotations(
186
+ title="Plan changes", readOnlyHint=False, destructiveHint=False, idempotentHint=True, openWorldHint=True
187
+ )
188
+ )
189
+ def plan(
190
+ path: str | None = None, config: str | None = None, prune: bool = False, destroy: bool = False
191
+ ) -> dict[str, Any]:
192
+ """Read the ad account and show what applying the configuration would change. Changes nothing.
193
+
194
+ Pass `path` or `config` as for validate. `prune` also pauses or removes managed resources
195
+ that are no longer in the configuration; `destroy` plans to pause every managed campaign.
196
+ Show the returned plan_text to the user. A plan without blockers is saved; its plan_id
197
+ is what apply needs.
198
+ """
199
+ with _tool_errors():
200
+ created = engine.create_plan(read_config(path, config), workspace, prune=prune, destroy=destroy)
201
+ plan_id = store(created) if created["operations"] and not created["blockers"] else None
202
+ return describe(created, plan_id)
203
+
204
+ @server.tool(
205
+ annotations=ToolAnnotations(
206
+ title="Show a saved plan", readOnlyHint=True, idempotentHint=True, openWorldHint=False
207
+ )
208
+ )
209
+ def show_plan(plan_id: str) -> dict[str, Any]:
210
+ """Show a plan created earlier by the plan tool, including when it was created."""
211
+ with _tool_errors():
212
+ saved = stored(plan_id)
213
+ return {**describe(saved, plan_id), "created_at": saved.get("created_at")}
214
+
215
+ if can_apply:
216
+
217
+ @server.tool(
218
+ annotations=ToolAnnotations(
219
+ title="Apply an approved plan",
220
+ readOnlyHint=False,
221
+ destructiveHint=True,
222
+ idempotentHint=False,
223
+ openWorldHint=True,
224
+ )
225
+ )
226
+ def apply(
227
+ plan_id: str,
228
+ confirm_account: str,
229
+ allow_enable: bool = False,
230
+ allow_budget_increase: bool = False,
231
+ allow_live_changes: bool = False,
232
+ ) -> dict[str, Any]:
233
+ """Apply a plan from the plan tool. Call this only after the user explicitly approved that plan.
234
+
235
+ `confirm_account` must be the plan's account ID. Set an allow_* flag only if the plan
236
+ requires it and the user approved that effect: allow_enable (a paused campaign starts
237
+ serving), allow_budget_increase (a budget or bid increases), allow_live_changes (a campaign
238
+ that is serving changes). Adstack re-reads the account first and refuses the plan if anything
239
+ changed since it was created.
240
+ """
241
+ with _tool_errors():
242
+ saved = stored(plan_id)
243
+ if re.sub(r"[^0-9]", "", confirm_account) != saved["account"]:
244
+ raise ToolError(f"confirm_account does not match the plan's account ({saved['target']})")
245
+ allow = {
246
+ gate
247
+ for gate, granted in (
248
+ ("allow_enable", allow_enable),
249
+ ("allow_budget_increase", allow_budget_increase),
250
+ ("allow_live_changes", allow_live_changes),
251
+ )
252
+ if granted
253
+ }
254
+ result = engine.apply(saved, workspace, allow=allow)
255
+ if result is None:
256
+ return {"applied": False, "message": "Nothing to apply: the account already matches the plan."}
257
+ receipt, path = result
258
+ return {
259
+ "applied": True,
260
+ "target": receipt["target"],
261
+ "summary": receipt["summary"],
262
+ "receipt": str(path.relative_to(root)),
263
+ }
264
+
265
+ @server.tool(
266
+ annotations=ToolAnnotations(
267
+ title="List managed resources", readOnlyHint=True, idempotentHint=True, openWorldHint=True
268
+ )
269
+ )
270
+ def state(path: str | None = None, config: str | None = None) -> dict[str, Any]:
271
+ """List what Adstack manages in the account: campaigns, ad groups, keywords and ads with their statuses."""
272
+ with _tool_errors():
273
+ loaded = read_config(path, config)
274
+ backend = engine.connect(loaded, workspace)
275
+ records = get_provider(loaded.provider).inventory(loaded.desired, backend.read())
276
+ return {"target": engine.target_label(loaded.provider, backend), "resources": records}
277
+
278
+ @server.tool(
279
+ annotations=ToolAnnotations(
280
+ title="Performance report", readOnlyHint=True, idempotentHint=True, openWorldHint=True
281
+ )
282
+ )
283
+ def report(
284
+ kind: Literal["performance", "search_terms"] = "performance",
285
+ days: Literal[7, 14, 30] = 7,
286
+ path: str | None = None,
287
+ config: str | None = None,
288
+ all_campaigns: bool = False,
289
+ ) -> dict[str, Any]:
290
+ """Campaign performance or search terms for the last 7, 14 or 30 days, with cost in account currency.
291
+
292
+ By default only campaigns in the configuration's namespace are included.
293
+ """
294
+ with _tool_errors():
295
+ loaded = read_config(path, config)
296
+ backend = engine.connect(loaded, workspace)
297
+ rows = backend.report(kind, days, all_campaigns=all_campaigns)
298
+ return {
299
+ "target": engine.target_label(loaded.provider, backend),
300
+ "kind": kind,
301
+ "days": days,
302
+ "currency": loaded.desired.get("currency"),
303
+ "rows": rows,
304
+ }
305
+
306
+ @server.tool(
307
+ annotations=ToolAnnotations(
308
+ title="Example configuration", readOnlyHint=True, idempotentHint=True, openWorldHint=False
309
+ )
310
+ )
311
+ def example_config() -> dict[str, Any]:
312
+ """An annotated example configuration that documents every option."""
313
+ return {"config": STARTER_CONFIG}
314
+
315
+ @server.resource(
316
+ "adstack://docs/example-config",
317
+ name="example-config",
318
+ title="Annotated example configuration",
319
+ description="An Adstack configuration that documents every option.",
320
+ mime_type="text/yaml",
321
+ )
322
+ def example_config_resource() -> str:
323
+ return STARTER_CONFIG
324
+
325
+ return server
326
+
327
+
328
+ def serve(root: Path, *, sandbox: bool, allow_apply: bool) -> None:
329
+ """Run the server over stdio."""
330
+ create_server(root, sandbox=sandbox, allow_apply=allow_apply).run("stdio")