From 772d94a603f460d3d310798094e3a89edffe1c70 Mon Sep 17 00:00:00 2001 From: Aleksei Zelentsov <37956463+zelentsov-dev@users.noreply.github.com> Date: Thu, 15 Oct 2026 20:45:40 +0300 Subject: [PATCH 1/4] Fix Apple Ads pacing and strategy contracts for v0.3.7 --- .codex-plugin/plugin.json | 2 +- .github/workflows/registry-publish.yml | 2 +- .goreleaser.yml | 13 +- CLAUDE.md | 2 +- CONTRIBUTING.md | 2 +- Dockerfile | 4 +- README.md | 24 +- api-contract/operations.json | 2 +- docs/MIGRATION-v0.3.7.md | 63 +++ go.mod | 4 +- internal/appleads/client.go | 55 ++- internal/appleads/client_test.go | 24 +- internal/appleads/rate_limits.go | 289 +++++++++++++ internal/appleads/rate_limits_test.go | 394 ++++++++++++++++++ internal/appleads/types.go | 45 +- internal/live/mcp_lifecycle_v03_test.go | 14 +- internal/live/mcp_operator_v02_test.go | 2 +- internal/live/mcp_write_v02_test.go | 2 +- internal/mcpserver/schema_test.go | 232 +++++++++++ internal/mcpserver/server.go | 2 +- internal/operations/store.go | 52 ++- internal/operations/store_test.go | 45 ++ internal/optimization/algorithm.go | 16 +- internal/optimization/algorithm_test.go | 53 +++ internal/tools/advanced_mutations.go | 142 ++----- internal/tools/bid_strategy_test.go | 275 ++++++++++++ internal/tools/errors.go | 23 +- internal/tools/mutation_models.go | 8 +- internal/tools/mutation_schema.go | 119 ++++++ internal/tools/mutation_validation.go | 257 +++++++++++- internal/tools/mutations.go | 18 +- internal/tools/mutations_test.go | 5 +- internal/tools/optimization_tools.go | 73 +++- internal/tools/optimization_tools_test.go | 8 + internal/tools/rate_errors_test.go | 90 ++++ internal/tools/report_v037_test.go | 62 +++ internal/tools/types.go | 7 +- scripts/validate_distribution.py | 3 + server.json | 4 +- .../references/tool-routing.md | 2 +- 40 files changed, 2193 insertions(+), 246 deletions(-) create mode 100644 docs/MIGRATION-v0.3.7.md create mode 100644 internal/appleads/rate_limits.go create mode 100644 internal/appleads/rate_limits_test.go create mode 100644 internal/mcpserver/schema_test.go create mode 100644 internal/tools/bid_strategy_test.go create mode 100644 internal/tools/mutation_schema.go create mode 100644 internal/tools/rate_errors_test.go create mode 100644 internal/tools/report_v037_test.go diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json index 5c06908..b0c94cb 100644 --- a/.codex-plugin/plugin.json +++ b/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "apple-ads-mcp", - "version": "0.3.6", + "version": "0.3.7", "description": "Local-first Apple Ads optimizer and App Store campaign operator with typed, receipt-gated lifecycle management.", "author": { "name": "Alexey Zelentsov", diff --git a/.github/workflows/registry-publish.yml b/.github/workflows/registry-publish.yml index 9fdceab..681f4fb 100644 --- a/.github/workflows/registry-publish.yml +++ b/.github/workflows/registry-publish.yml @@ -12,7 +12,7 @@ on: version: description: Released semantic version without a v prefix required: true - default: "0.3.6" + default: "0.3.7" permissions: contents: read diff --git a/.goreleaser.yml b/.goreleaser.yml index 8f53bc3..49fa83f 100644 --- a/.goreleaser.yml +++ b/.goreleaser.yml @@ -30,7 +30,8 @@ archives: - .mcp.json - .codex-plugin/plugin.json - skills/apple-ads-operator/** - - docs/** + - docs/MIGRATION-*.md + - docs/ROADMAP.md - api-contract/** checksum: @@ -51,13 +52,15 @@ release: mode: replace make_latest: true header: | - Apple Ads MCP {{ .Tag }} adds typed, actionable diagnostics across text and structured MCP results. Apple `4xx` details are bounded and sanitized, write gates explain how to opt in safely, and receipt failures now distinguish expired, used, missing, drifted, transport, and ambiguous outcomes. + Apple Ads MCP {{ .Tag }} honors Apple rate-limit headers and Retry-After without shortening the required wait. Concurrent reads share a bounded per-profile cooldown; writes blocked before dispatch are distinguished from ambiguous writes and are never automatically retried. - Targeting-keyword bulk creation now supports zero-based integer correlation IDs and one aggregate receipt across one or more ad groups. Successful item IDs are preserved and verified directly, partial Apple failures remain visible, and semantic object, inventory, relationship, and cascade reservations prevent overlapping mutations from dispatching against stale state. + Bid strategies now validate the matching type and goal, creation versus update rules, account currency, placement, and parent campaign state. Explicit strategy requests do not require optimizer history minimums; conservative optimizer thresholds remain intact. Preview warnings persist with their receipt. - Read tools keep compatible legacy inputs while adding named ID aliases, typed query shortcuts, stricter keyword scopes, zero-metric reports, bounded change-history windows, compact locale output, exact Unicode owned-app fallback, and section-level opportunity diagnostics. Impression-share Apple errors remain honest upstream failures, and empty Search Results ad inventories are explained without synthesizing objects. + Reports reject the retired storefront grouping with a countryOrRegion migration hint and preserve date strings. CPA cap remains available for compatibility, with deprecation annotations and warnings. Tool names remain unchanged. See docs/MIGRATION-v0.3.7.md for compatibility details. - Tool names remain stable. Existing `id`, advanced `filters`, and top-level keyword bulk `adGroupId` inputs remain supported. See `docs/MIGRATION-v0.3.6.md` for the complete compatibility and migration contract. + The build baseline is Go 1.26.9, including the pinned Docker builder, to incorporate standard-library security fixes. + + Validation uses synthetic data and cross-platform CI. This release does not claim live mutation acceptance and does not change advertising campaigns. footer: | Archives include SHA-256 checksums and SPDX SBOMs. See the README for installation, Apple Ads onboarding, safety controls, and known platform behavior. diff --git a/CLAUDE.md b/CLAUDE.md index 0bab426..c8df253 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -8,7 +8,7 @@ The project is independent and is not affiliated with, endorsed by, or sponsored ## Architecture -- Go 1.26.7+ +- Go 1.26.9+ - Official MCP Go SDK - `cmd/apple-ads-mcp` contains only CLI wiring - Production code lives under `internal/` diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0e11f90..b1f79bc 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,6 +1,6 @@ # Contributing -Use Go 1.26.7 or newer and keep the server compatible with the official MCP Go SDK v1.7 line. +Use Go 1.26.9 or newer and keep the server compatible with the official MCP Go SDK v1.7 line. Before opening a pull request: diff --git a/Dockerfile b/Dockerfile index 021ecc7..42566a3 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,5 +1,5 @@ -FROM golang:1.26.7-bookworm@sha256:e8c859f5632dcfde7b32d2012b4351728f6437930887c2f6a91ea242459e5514 AS build -ARG VERSION=0.3.6 +FROM golang:1.26.9-bookworm@sha256:d9c68c2c51161e12fd77e4c6320687c9cd86e1af1e3ad6e6cd63ff970641453c AS build +ARG VERSION=0.3.7 WORKDIR /src COPY go.mod go.sum ./ RUN go mod download diff --git a/README.md b/README.md index c38c4e4..bc2ca3e 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ [![CI](https://github.com/zelentsov-dev/apple-ads-mcp/actions/workflows/ci.yml/badge.svg)](https://github.com/zelentsov-dev/apple-ads-mcp/actions/workflows/ci.yml) [![Release](https://img.shields.io/github/v/release/zelentsov-dev/apple-ads-mcp)](https://github.com/zelentsov-dev/apple-ads-mcp/releases) -[![Go](https://img.shields.io/badge/Go-1.26.7%2B-00ADD8?logo=go)](go.mod) +[![Go](https://img.shields.io/badge/Go-1.26.9%2B-00ADD8?logo=go)](go.mod) [![License](https://img.shields.io/github/license/zelentsov-dev/apple-ads-mcp)](LICENSE) Apple Ads MCP is a local-first [Model Context Protocol](https://modelcontextprotocol.io/) server for the [Apple Ads Platform API v1](https://developer.apple.com/documentation/apple-ads-platform-api). It gives Codex, Claude, and other MCP clients typed tools to research, inspect, and safely operate App Store advertising accounts. @@ -56,7 +56,7 @@ Other useful read-only starters: ## Current release -`v0.3.6` is the current release. It adds typed actionable diagnostics, fixes Apple keyword bulk creation with zero-based integer correlation IDs and one aggregate cross-group receipt, and tightens read/query contracts without removing legacy `id`, `filters`, or top-level bulk `adGroupId` inputs. See the [v0.3.6 release and migration notes](docs/MIGRATION-v0.3.6.md). +`v0.3.7` is the current release. It honors Apple rate-limit timing, validates bid strategies in their campaign and ad-group context, updates report grouping, and deprecates CPA cap without removing existing tools. Explicit strategy requests and optimizer recommendations now have separate history policies. See the [v0.3.7 release and migration notes](docs/MIGRATION-v0.3.7.md). The v0.3.5 version-final archive naming, formula-scoped trust from v0.3.4, exact-path verification from v0.3.3, and one-command onboarding from v0.3.2 remain intact. @@ -84,7 +84,7 @@ Keywords and negative keywords are Search Results resources. The Platform API re | Research | keyword, phrase, category, target-CPA suggestions, search popularity, impression share | | Reports | typed campaign, ad-group, ad, keyword, and search-term reports | | Campaign operation | create/update, budget, countries, schedule, pause, and resume previews | -| Ad-group operation | create/update, schedule, targeting, Search Match, bid, CPA cap, pause, and resume previews | +| Ad-group operation | create/update, schedule, targeting, Search Match, bid, deprecated CPA cap, pause, and resume previews | | Keywords | individual and bulk targeting/negative keyword create/update, bid, pause, and resume previews | | Ads and creatives | typed App Store creative and ad create/update, pause, and resume previews | | Recommendations | read, apply-preview, and dismiss-preview for daily budget and target CPA | @@ -120,15 +120,15 @@ An irreversible delete has five additional gates: `--allow-deletes`, profile `al ## Release validation -The v0.3.6 release requires the complete compatibility suite, MCP stdio contract tests, unit and HTTP tests, the race detector, static analysis, vulnerability and secret scans, and distribution validation. Cross-platform CI runs on macOS, Linux, and Windows. +The v0.3.7 release requires the complete compatibility suite, MCP stdio contract tests, unit and HTTP tests, the race detector, static analysis, vulnerability and secret scans, and distribution validation. Cross-platform CI runs on macOS, Linux, and Windows. -Runtime confirmation is a separate owner-controlled gate. On 2026-08-31, the v0.3.6 P2 read-only matrix and a separately authorized `PAUSED` targeting-keyword bulk fixture with 2 and 28 items passed against Apple Ads API v1. Both aggregate receipts applied and verified every returned keyword ID directly; the campaign and ad group remained `PAUSED` throughout the write acceptance. +This release uses synthetic acceptance only; no live advertising mutations are part of v0.3.7 validation. Runtime confirmation is a separate owner-controlled gate. On 2026-08-31, the v0.3.6 P2 read-only matrix and a separately authorized `PAUSED` targeting-keyword bulk fixture with 2 and 28 items passed against Apple Ads API v1. Both aggregate receipts applied and verified every returned keyword ID directly; the campaign and ad group remained `PAUSED` throughout the write acceptance. -Earlier v0.3.x live acceptance confirmed read-only optimization baselines and plans, `PAUSED` fixture creation and readback, budget/bid/strategy updates, pause/resume, receipt drift checks, item verification, and deletion of disposable campaigns, ad groups, keywords, and negative keywords. All retained fixtures remained `PAUSED` with zero spend. This historical evidence does not replace the new v0.3.6 bulk/P2 acceptance gate. +Earlier v0.3.x live acceptance confirmed read-only optimization baselines and plans, `PAUSED` fixture creation and readback, budget/bid/strategy updates, pause/resume, receipt drift checks, item verification, and deletion of disposable campaigns, ad groups, keywords, and negative keywords. All retained fixtures remained `PAUSED` with zero spend. This historical evidence does not prove v0.3.7 live acceptance. Account-dependent paths have an explicit evidence boundary: -- Active optimization-plan apply and `MAX_CONVERSIONS` remain automated-test verified until a deliberately selected mature campaign satisfies the minimum 14-day data and Apple eligibility gates. +- Active optimization-plan apply and `MAX_CONVERSIONS` changes remain automated-test verified for this release. Optimizer recommendations require the existing history minimums; explicit user-requested previews instead show a warning that statistical readiness has not been established, while preserving contract validation and write gates. - Shared-budget create/update/assignment/delete remain contract- and HTTP-test verified because the live acceptance account uses `PAYG`; Apple requires `LOC`. - Default Product Page ad and creative deletion is confirmed as `not_eligible` because Apple does not allow those resources to be deleted individually. @@ -164,10 +164,10 @@ Download the archive for your platform from [GitHub Releases](https://github.com Apple silicon example: ```bash -curl -LO https://github.com/zelentsov-dev/apple-ads-mcp/releases/download/v0.3.6/apple-ads-mcp_darwin_arm64_0.3.6.tar.gz -curl -LO https://github.com/zelentsov-dev/apple-ads-mcp/releases/download/v0.3.6/checksums.txt +curl -LO https://github.com/zelentsov-dev/apple-ads-mcp/releases/download/v0.3.7/apple-ads-mcp_darwin_arm64_0.3.7.tar.gz +curl -LO https://github.com/zelentsov-dev/apple-ads-mcp/releases/download/v0.3.7/checksums.txt shasum -a 256 -c checksums.txt --ignore-missing -tar -xzf apple-ads-mcp_darwin_arm64_0.3.6.tar.gz +tar -xzf apple-ads-mcp_darwin_arm64_0.3.7.tar.gz sudo install -m 0755 apple-ads-mcp /usr/local/bin/apple-ads-mcp ``` @@ -189,7 +189,7 @@ cd apple-ads-mcp go build -trimpath -o ./apple-ads-mcp ./cmd/apple-ads-mcp ``` -Go 1.26.7 or newer is required. +Go 1.26.9 or newer is required. ## Apple API setup @@ -392,7 +392,7 @@ The server returns these as bounded structured Apple errors and does not convert ## Compatibility -v0.3 preserves all v0.2.1 tool names and schemas, then adds optimization, shared-budget mutation, bid-strategy, and lifecycle tools. v0.3.1 adds a required `maxBid` when bid permission is enabled and fail-closed reconciliation rules; see the [v0.3.1 migration notes](docs/MIGRATION-v0.3.1.md). v0.3.2 changes distribution and onboarding only. v0.3.3 switches release verification to the exact tap formula path, v0.3.4 adds formula-scoped trust for Homebrew 6, and v0.3.5 disambiguates Homebrew version detection by placing the semantic version at the end of archive names. v0.3.6 keeps existing tool names and compatible legacy inputs while adding typed aliases, query shortcuts, diagnostics, and stricter required scopes; see the [v0.3.6 notes](docs/MIGRATION-v0.3.6.md). Older clients should also read the [v0.3 notes](docs/MIGRATION-v0.3.md) and [v0.2 notes](docs/MIGRATION-v0.2.md). +v0.3 preserves all v0.2.1 tool names and schemas, then adds optimization, shared-budget mutation, bid-strategy, and lifecycle tools. v0.3.1 adds a required `maxBid` when bid permission is enabled and fail-closed reconciliation rules; see the [v0.3.1 migration notes](docs/MIGRATION-v0.3.1.md). v0.3.2 changes distribution and onboarding only. v0.3.3 switches release verification to the exact tap formula path, v0.3.4 adds formula-scoped trust for Homebrew 6, and v0.3.5 disambiguates Homebrew version detection by placing the semantic version at the end of archive names. v0.3.6 keeps existing tool names and compatible legacy inputs while adding typed aliases, query shortcuts, diagnostics, and stricter required scopes; see the [v0.3.6 notes](docs/MIGRATION-v0.3.6.md). v0.3.7 adds header-aware request pacing, contextual bid validation, report grouping corrections, and persisted preview warnings; see the [v0.3.7 notes](docs/MIGRATION-v0.3.7.md). Older clients should also read the [v0.3 notes](docs/MIGRATION-v0.3.md) and [v0.2 notes](docs/MIGRATION-v0.2.md). The public tool schema is not frozen before v1.0. API-family scope and operation status are tracked in the [machine-readable operation matrix](api-contract/operations.json). The official Java client baseline and App Store endpoint inventory are tracked in [upstream-baseline.json](api-contract/upstream-baseline.json). diff --git a/api-contract/operations.json b/api-contract/operations.json index 275e023..d318c95 100644 --- a/api-contract/operations.json +++ b/api-contract/operations.json @@ -1,7 +1,7 @@ { "apiFamily": "Apple Ads Platform API", "apiVersion": "v1", - "productVersion": "0.3.6", + "productVersion": "0.3.7", "legacyV5": false, "appleMaps": false, "maximumPageSize": 200, diff --git a/docs/MIGRATION-v0.3.7.md b/docs/MIGRATION-v0.3.7.md new file mode 100644 index 0000000..3a0266c --- /dev/null +++ b/docs/MIGRATION-v0.3.7.md @@ -0,0 +1,63 @@ +# v0.3.7 migration notes + +This release updates Apple Ads Platform API v1 compatibility for App Store advertising. Tool names, default read-only mode, credential handling, and explicit preview/apply gates remain unchanged. It does not introduce background optimization or migrate advertising campaigns. + +## Build baseline + +Source builds now require Go 1.26.9 or newer. Release binaries and the pinned Docker builder use the patched Go 1.26 line to address standard-library vulnerabilities detected by the release security checks. + +## Request pacing + +The client reads `RateLimit-Limit`, `RateLimit-Remaining`, and `RateLimit-Reset` on responses. Modern `Reset` is a duration in seconds. Legacy rate-limit headers remain available as output fallbacks; their reset value is not assumed to use modern delta semantics. + +A `429` waits for `Retry-After`, then modern `RateLimit-Reset`, then exponential fallback starting at two seconds. Server-requested waits are never shortened to five seconds. A low remaining quota (fewer than five requests) pauses the next request in that profile; one read probes the refreshed window before waiting peers continue. If a low-quota response has no usable timing header, the same bounded fallback delay applies. + +Reads retain a maximum of three attempts. Total waiting per client operation is limited to 60 seconds and any earlier caller deadline. If the required delay exceeds the available waiting budget, the client returns a structured rate-limit error with safe timing details instead of sending early. Cooldown coordination is in memory within one profile in one server process, not a distributed quota across clients. + +Positive numeric timing values outside the supported duration range fail closed with `RATE_LIMIT_TIMING_INVALID`; the profile stays blocked rather than guessing a shorter delay. Investigate the upstream header before restarting the server. A newer valid in-flight rate-limit response can also replace that state. + +A mutation encountering an active cooldown fails before dispatch, including while a read probe is needed to confirm the refreshed window. An apply receipt is still single-use once consumed; inspect the operation and create a fresh preview after the cooldown when necessary. Timeouts and server failures after dispatch remain ambiguous and must be verified rather than repeated. + +## Bid strategies + +Every supplied type and goal must be a matching pair: + +| Type | Goal | +| --- | --- | +| `MANUAL_CPT` | `TAP` | +| `MAX_CONVERSIONS` | `INSTALL` | + +Campaign creation requires a strategy. An ad group may omit its strategy at creation to inherit its parent's settings. An explicitly supplied manual creation strategy requires a positive bid. An automated creation strategy may include a positive bid ceiling. + +Manual bid-only updates remain supported. For an ad group under an automated campaign, an update may echo the parent's type and goal with a zero bid; a nonzero bid or a conflicting strategy is rejected. Monetary values use the account currency. Decimal strings are not restricted to two fractional digits. + +Shared validation covers generic updates, specialized previews, and optimizer-generated changes. Parent campaign and account evidence used for validation is bound to the receipt; drift requires a fresh preview. + +Explicit user-requested `MAX_CONVERSIONS` previews no longer require 14 completed reporting days and 70 historical installs. They still validate the App Store placement, billing, currency, and write permissions, and warn that statistical readiness has not been established. This does not promise that Apple will accept every account-dependent request. + +Optimizer recommendations retain the existing minimum of 14 completed days and five tap installs per day on average, or stricter policy settings. Apple's budget guidance for five daily conversions and the two-week learning period are recommendations, not a historical eligibility requirement for explicit requests. + +## Reports and deprecated CPA cap + +`groupBy: ["storefront"]` is rejected with a migration hint to `countryOrRegion`; the client never silently changes the request. Storefront metadata, filters, and app-search storefront inputs remain available. + +General reports preserve date strings, including hourly timestamps. The optimizer continues to consume completed daily UTC intervals and rejects malformed dates rather than silently counting them as zero. + +`cpaCap` and `ad_group_cpa_cap_preview` remain available for compatibility but are deprecated. Schemas and tool descriptions expose the deprecation, and applicable previews contain a warning. Existing values are not converted to a bid strategy, and no removal date is assumed. + +## Preview warnings and validation + +Preview objects may contain an additive `warnings` array of objects with `code` and `message`. Warnings are retained for `operations_inspect`. Consumers should display them alongside the proposed changes before applying a receipt. + +MCP input schemas reject invalid statuses, nonnumeric correlation IDs, mismatched strategy pairs, and malformed bid amounts before the handler. Context-dependent rules, such as the parent's strategy and currency, are checked by the handler. IDs and money remain string-based; bulk correlation IDs continue accepting nonnegative integers and decimal strings within the runtime's integer range. + +Validation for this release uses synthetic unit, HTTP, MCP, concurrency, and receipt tests plus cross-platform CI and security/distribution checks. Live advertising mutations are not part of this release's acceptance. Older live test results do not establish v0.3.7 runtime acceptance. + +Release archives include only public migration and roadmap documents. Private account exports, local research reports, credentials, and fixture identifiers must not enter commits, release notes, or archives. + +## References + +- [Apple rate limits](https://developer.apple.com/documentation/apple-ads-platform-api/rate-limits) +- [Bid strategy creation](https://developer.apple.com/documentation/apple-ads-platform-api/bidstrategycreate) +- [Ad group updates and automatic bidding](https://developer.apple.com/documentation/apple-ads-platform-api/put-adgroups-_id_) +- [Maximize Conversions best practices](https://ads.apple.com/app-store/best-practices/maximize-conversions) diff --git a/go.mod b/go.mod index 57da8a1..d16227e 100644 --- a/go.mod +++ b/go.mod @@ -1,15 +1,15 @@ module github.com/zelentsov-dev/apple-ads-mcp -go 1.26.7 +go 1.26.9 require ( + github.com/google/jsonschema-go v0.4.3 github.com/golang-jwt/jwt/v5 v5.3.1 github.com/modelcontextprotocol/go-sdk v1.7.0 golang.org/x/sys v0.47.0 ) require ( - github.com/google/jsonschema-go v0.4.3 // indirect github.com/segmentio/asm v1.1.3 // indirect github.com/segmentio/encoding v0.5.4 // indirect github.com/yosida95/uritemplate/v3 v3.0.2 // indirect diff --git a/internal/appleads/client.go b/internal/appleads/client.go index 09b4e92..1c5f0cb 100644 --- a/internal/appleads/client.go +++ b/internal/appleads/client.go @@ -29,6 +29,8 @@ type Client struct { tokens TokenSource baseURL *url.URL sleep func(context.Context, time.Duration) error + now func() time.Time + limits rateLimiter } func NewClient(tokens TokenSource) *Client { @@ -43,6 +45,7 @@ func NewClient(tokens TokenSource) *Client { tokens: tokens, baseURL: baseURL, sleep: sleepContext, + now: time.Now, } } @@ -51,7 +54,7 @@ func NewClientForTest(tokens TokenSource, client *http.Client, baseURL string) ( if err != nil { return nil, err } - return &Client{httpClient: client, tokens: tokens, baseURL: parsed, sleep: sleepContext}, nil + return &Client{httpClient: client, tokens: tokens, baseURL: parsed, sleep: sleepContext, now: time.Now}, nil } func (c *Client) Do(ctx context.Context, adAccountID string, operation Operation) (Result, error) { @@ -67,8 +70,14 @@ func (c *Client) Do(ctx context.Context, adAccountID string, operation Operation maxAttempts = 3 } refreshed := false + budget := waitBudget{remaining: maxRateLimitWait} for attempt := 1; attempt <= maxAttempts; attempt++ { + probe, err := c.acquireRateLimit(ctx, operation.mutation, &budget) + if err != nil { + return Result{}, err + } result, response, sent, err := c.doOnce(ctx, adAccountID, operation, body) + c.observeRateLimit(result, response, probe, attempt) if err != nil { if operation.mutation && sent { return Result{}, &AmbiguousWriteError{Cause: err} @@ -76,7 +85,7 @@ func (c *Client) Do(ctx context.Context, adAccountID string, operation Operation if attempt == maxAttempts { return Result{}, err } - if err := c.sleep(ctx, retryDelay(attempt, 0)); err != nil { + if err := c.waitForRetry(ctx, retryDelay(attempt, 0), result.RateLimit, &budget); err != nil { return Result{}, err } continue @@ -88,17 +97,27 @@ func (c *Client) Do(ctx context.Context, adAccountID string, operation Operation continue } if retryableStatus(response.StatusCode) && operation.retryReads && attempt < maxAttempts { + if response.StatusCode == http.StatusTooManyRequests { + continue + } delay := retryDelay(attempt, result.RateLimit.RetryAfter) - if err := c.sleep(ctx, delay); err != nil { + if result.RateLimit.retrySet { + delay = time.Duration(result.RateLimit.RetryAfter) * time.Second + } + if err := c.waitForRetry(ctx, delay, result.RateLimit, &budget); err != nil { return Result{}, err } continue } if operation.mutation && response.StatusCode >= http.StatusInternalServerError { - return Result{}, &AmbiguousWriteError{Cause: apiError(response.StatusCode, result.Data)} + return Result{}, &AmbiguousWriteError{Cause: apiErrorWithRateLimit(response.StatusCode, result.Data, result.RateLimit)} } if response.StatusCode < 200 || response.StatusCode >= 300 { - return Result{}, apiError(response.StatusCode, result.Data) + apiErr := apiErrorWithRateLimit(response.StatusCode, result.Data, result.RateLimit) + if operation.mutation { + apiErr.Retryable = false + } + return Result{}, apiErr } return result, nil } @@ -133,18 +152,20 @@ func (c *Client) doOnce(ctx context.Context, adAccountID string, operation Opera return Result{}, nil, true, fmt.Errorf("execute Apple Ads request: %w", err) } defer resp.Body.Close() + rate := rateLimitFromHeadersAt(resp.Header, c.now()) + partial := Result{Status: resp.StatusCode, RateLimit: rate} data, err := io.ReadAll(io.LimitReader(resp.Body, maxResponseBody+1)) if err != nil { - return Result{}, resp, true, fmt.Errorf("read Apple Ads response: %w", err) + return partial, resp, true, fmt.Errorf("read Apple Ads response: %w", err) } if len(data) > maxResponseBody { - return Result{}, resp, true, errors.New("response from Apple Ads exceeds size limit") + return partial, resp, true, errors.New("response from Apple Ads exceeds size limit") } if len(bytes.TrimSpace(data)) == 0 && (resp.StatusCode < 200 || resp.StatusCode >= 300) { return Result{ Data: map[string]any{"responseFormat": "empty"}, Status: resp.StatusCode, - RateLimit: rateLimitFromHeaders(resp.Header), + RateLimit: rate, }, resp, true, nil } decoded, err := decodeEnvelope(data) @@ -153,13 +174,13 @@ func (c *Client) doOnce(ctx context.Context, adAccountID string, operation Opera return Result{ Data: map[string]any{"message": http.StatusText(resp.StatusCode), "responseFormat": "non_json"}, Status: resp.StatusCode, - RateLimit: rateLimitFromHeaders(resp.Header), + RateLimit: rate, }, resp, true, nil } - return Result{}, resp, true, err + return partial, resp, true, err } decoded.Status = resp.StatusCode - decoded.RateLimit = rateLimitFromHeaders(resp.Header) + decoded.RateLimit = rate return decoded, resp, true, nil } @@ -234,7 +255,7 @@ func stringInt(value any) int { return result } -func apiError(status int, data any) error { +func apiError(status int, data any) *APIError { result := &APIError{HTTPStatus: status, Message: http.StatusText(status), Retryable: retryableStatus(status)} if raw, ok := data.(map[string]any); ok { result.Code = safeErrorText(firstString(raw, "code", "errorCode"), 128) @@ -375,16 +396,6 @@ func retryableStatus(status int) bool { return status == http.StatusTooManyRequests || status >= http.StatusInternalServerError && status <= 599 } -func retryDelay(attempt, retryAfter int) time.Duration { - if retryAfter > 0 { - if retryAfter > 5 { - retryAfter = 5 - } - return time.Duration(retryAfter) * time.Second - } - return time.Duration(attempt*200) * time.Millisecond -} - func sleepContext(ctx context.Context, delay time.Duration) error { timer := time.NewTimer(delay) defer timer.Stop() diff --git a/internal/appleads/client_test.go b/internal/appleads/client_test.go index 8ff9223..f62402d 100644 --- a/internal/appleads/client_test.go +++ b/internal/appleads/client_test.go @@ -7,6 +7,7 @@ import ( "net/http" "net/http/httptest" "strings" + "sync" "sync/atomic" "testing" "time" @@ -94,7 +95,11 @@ func TestRetryAfterAndRateLimit(t *testing.T) { defer server.Close() client := testClient(t, server, &fakeTokens{value: "token"}) var delay time.Duration - client.sleep = func(_ context.Context, value time.Duration) error { delay = value; return nil } + originalSleep := client.sleep + client.sleep = func(ctx context.Context, value time.Duration) error { + delay = value + return originalSleep(ctx, value) + } result, err := client.Do(context.Background(), "", ACLs()) if err != nil { t.Fatal(err) @@ -402,7 +407,22 @@ func testClient(t *testing.T, server *httptest.Server, tokens TokenSource) *Clie if err != nil { t.Fatal(err) } - client.sleep = func(context.Context, time.Duration) error { return nil } + var clockMu sync.Mutex + now := time.Now() + client.now = func() time.Time { + clockMu.Lock() + defer clockMu.Unlock() + return now + } + client.sleep = func(ctx context.Context, delay time.Duration) error { + if err := ctx.Err(); err != nil { + return err + } + clockMu.Lock() + now = now.Add(delay) + clockMu.Unlock() + return nil + } return client } diff --git a/internal/appleads/rate_limits.go b/internal/appleads/rate_limits.go new file mode 100644 index 0000000..3ac0e0c --- /dev/null +++ b/internal/appleads/rate_limits.go @@ -0,0 +1,289 @@ +package appleads + +import ( + "context" + "math" + "net/http" + "strconv" + "strings" + "sync" + "time" +) + +const maxRateLimitWait = 60 * time.Second +const maxRateLimitSeconds = int64(math.MaxInt64 / int64(time.Second)) + +type RateLimitError struct { + Code string + RateLimit RateLimit + Mutation bool + Cause error +} + +func (e *RateLimitError) Error() string { + switch e.Code { + case "RATE_LIMIT_COOLDOWN": + return "Apple Ads mutation was not sent because the profile is rate limited" + case "RATE_LIMIT_WAIT_CANCELED": + return "Apple Ads rate-limit wait was canceled before dispatch" + case "RATE_LIMIT_TIMING_INVALID": + return "Apple Ads rate-limit timing exceeds the supported range; profile requests remain blocked until timing is verified and the server is restarted" + default: + return "Apple Ads rate-limit wait exceeds the available wait budget; request was not dispatched" + } +} + +func (e *RateLimitError) Unwrap() error { return e.Cause } + +func rateLimitFromHeadersAt(header http.Header, now time.Time) RateLimit { + result := RateLimit{ + Limit: numericHeader(header, "RateLimit-Limit", "X-Rate-Limit-Limit", "X-RateLimit-Limit"), + Remaining: numericHeader(header, "RateLimit-Remaining", "X-Rate-Limit-Remaining", "X-RateLimit-Remaining"), + Reset: numericHeader(header, "RateLimit-Reset", "X-Rate-Limit-Reset", "X-RateLimit-Reset"), + } + var resetUnsafe, retryUnsafe bool + result.resetSeconds, result.resetSet, resetUnsafe = durationSeconds(header.Get("RateLimit-Reset")) + result.RetryAfter, result.retrySet, retryUnsafe = durationSeconds(header.Get("Retry-After")) + if !result.retrySet && !retryUnsafe { + if date, err := http.ParseTime(strings.TrimSpace(header.Get("Retry-After"))); err == nil && date.After(now) { + delta := date.Sub(now) + seconds := ceilSeconds(delta) + if seconds <= maxRateLimitSeconds { + result.RetryAfter, result.retrySet = int(seconds), true + } else { + retryUnsafe = true + } + } + } + result.timingUnsafe = retryUnsafe || !result.retrySet && resetUnsafe + return result +} + +func numericHeader(header http.Header, names ...string) string { + for _, name := range names { + value := strings.TrimSpace(header.Get(name)) + if !decimalDigits(value) { + continue + } + if parsed, err := strconv.ParseUint(value, 10, 64); err == nil { + return strconv.FormatUint(parsed, 10) + } + } + return "" +} + +func durationSeconds(value string) (int, bool, bool) { + value = strings.TrimSpace(value) + if !decimalDigits(value) { + return 0, false, false + } + parsed, err := strconv.ParseUint(value, 10, 64) + if err != nil || parsed > uint64(maxRateLimitSeconds) || parsed > uint64(^uint(0)>>1) { + return 0, false, true + } + return int(parsed), true, false +} + +func decimalDigits(value string) bool { + if value == "" { + return false + } + for _, digit := range value { + if digit < '0' || digit > '9' { + return false + } + } + return true +} + +func ceilSeconds(duration time.Duration) int64 { + seconds := int64(duration / time.Second) + if duration%time.Second > 0 { + seconds++ + } + return seconds +} + +func (rate RateLimit) retryDelay(attempt int) time.Duration { + if rate.retrySet { + return time.Duration(rate.RetryAfter) * time.Second + } + if rate.resetSet { + return time.Duration(rate.resetSeconds) * time.Second + } + return retryDelay(attempt, 0) +} + +func retryDelay(attempt, retryAfter int) time.Duration { + if retryAfter > 0 && int64(retryAfter) <= maxRateLimitSeconds { + return time.Duration(retryAfter) * time.Second + } + if attempt < 1 { + attempt = 1 + } + if attempt > 4 { + attempt = 4 + } + return (time.Second * 2) << (attempt - 1) +} + +type rateLimiter struct { + mu sync.Mutex + until time.Time + active bool + probing bool + generation uint64 + changed chan struct{} + rate RateLimit +} + +type rateProbe struct { + active bool + generation uint64 +} + +type waitBudget struct { + remaining time.Duration +} + +func (c *Client) acquireRateLimit(ctx context.Context, mutation bool, budget *waitBudget) (rateProbe, error) { + for { + if err := ctx.Err(); err != nil { + c.limits.mu.Lock() + active, rate := c.limits.active, c.limits.rate + c.limits.mu.Unlock() + if active { + return rateProbe{}, &RateLimitError{Code: "RATE_LIMIT_WAIT_CANCELED", RateLimit: rate, Mutation: mutation, Cause: err} + } + return rateProbe{}, err + } + c.limits.mu.Lock() + if !c.limits.active { + c.limits.mu.Unlock() + return rateProbe{}, nil + } + delay := c.limits.until.Sub(c.now()) + rate := c.limits.rate + if delay > 0 && !rate.timingUnsafe { + rate.RetryAfter = int(ceilSeconds(delay)) + } + if rate.timingUnsafe { + c.limits.mu.Unlock() + return rateProbe{}, &RateLimitError{Code: "RATE_LIMIT_TIMING_INVALID", RateLimit: rate, Mutation: mutation} + } + if mutation { + c.limits.mu.Unlock() + return rateProbe{}, &RateLimitError{Code: "RATE_LIMIT_COOLDOWN", RateLimit: rate, Mutation: true} + } + if delay <= 0 && !c.limits.probing { + c.limits.probing = true + c.limits.changed = make(chan struct{}) + probe := rateProbe{active: true, generation: c.limits.generation} + c.limits.mu.Unlock() + return probe, nil + } + changed := c.limits.changed + c.limits.mu.Unlock() + if changed == nil { + if err := c.waitForRetry(ctx, delay, rate, budget); err != nil { + return rateProbe{}, err + } + } else if err := c.waitForProbe(ctx, changed, rate, budget); err != nil { + return rateProbe{}, err + } + } +} + +func (c *Client) observeRateLimit(result Result, response *http.Response, probe rateProbe, attempt int) { + c.limits.mu.Lock() + defer c.limits.mu.Unlock() + rate := result.RateLimit + limited := response != nil && response.StatusCode == http.StatusTooManyRequests + if remaining, err := strconv.ParseUint(rate.Remaining, 10, 64); err == nil && remaining < 5 { + limited = true + } + if limited { + delay := rate.retryDelay(attempt) + if response.StatusCode != http.StatusTooManyRequests && rate.resetSet { + delay = time.Duration(rate.resetSeconds) * time.Second + } + if rate.timingUnsafe { + delay = maxRateLimitWait + } + until := c.now().Add(delay) + if !c.limits.active || until.After(c.limits.until) || c.limits.rate.timingUnsafe { + c.limits.until = until + c.limits.rate = rate + } + if rate.timingUnsafe { + c.limits.rate = rate + } + c.limits.active = true + c.limits.generation++ + } + if probe.active { + if !limited && probe.generation == c.limits.generation { + if response == nil { + c.limits.until = c.now().Add(retryDelay(attempt, 0)) + } else { + c.limits.active = false + } + } + c.limits.probing = false + close(c.limits.changed) + c.limits.changed = nil + } +} + +func (c *Client) waitForRetry(ctx context.Context, delay time.Duration, rate RateLimit, budget *waitBudget) error { + if rate.timingUnsafe { + return &RateLimitError{Code: "RATE_LIMIT_TIMING_INVALID", RateLimit: rate} + } + if err := ctx.Err(); err != nil { + return &RateLimitError{Code: "RATE_LIMIT_WAIT_CANCELED", RateLimit: rate, Cause: err} + } + if delay <= 0 { + return nil + } + if delay > budget.remaining { + return &RateLimitError{Code: "RATE_LIMIT_WAIT_EXCEEDED", RateLimit: rate} + } + if deadline, ok := ctx.Deadline(); ok && delay > deadline.Sub(c.now()) { + return &RateLimitError{Code: "RATE_LIMIT_WAIT_EXCEEDED", RateLimit: rate, Cause: context.DeadlineExceeded} + } + started := c.now() + if err := c.sleep(ctx, delay); err != nil { + budget.remaining -= c.now().Sub(started) + return &RateLimitError{Code: "RATE_LIMIT_WAIT_CANCELED", RateLimit: rate, Cause: err} + } + elapsed := c.now().Sub(started) + if elapsed < delay { + elapsed = delay + } + budget.remaining -= elapsed + return nil +} + +func (c *Client) waitForProbe(ctx context.Context, changed <-chan struct{}, rate RateLimit, budget *waitBudget) error { + if budget.remaining <= 0 { + return &RateLimitError{Code: "RATE_LIMIT_WAIT_EXCEEDED", RateLimit: rate} + } + started := c.now() + timer := time.NewTimer(budget.remaining) + defer timer.Stop() + defer func() { budget.remaining -= c.now().Sub(started) }() + select { + case <-changed: + return nil + case <-ctx.Done(): + return &RateLimitError{Code: "RATE_LIMIT_WAIT_CANCELED", RateLimit: rate, Cause: ctx.Err()} + case <-timer.C: + return &RateLimitError{Code: "RATE_LIMIT_WAIT_EXCEEDED", RateLimit: rate} + } +} + +func apiErrorWithRateLimit(status int, data any, rate RateLimit) *APIError { + err := apiError(status, data) + err.RateLimit = rate + return err +} diff --git a/internal/appleads/rate_limits_test.go b/internal/appleads/rate_limits_test.go new file mode 100644 index 0000000..4513c30 --- /dev/null +++ b/internal/appleads/rate_limits_test.go @@ -0,0 +1,394 @@ +package appleads + +import ( + "context" + "errors" + "fmt" + "io" + "net/http" + "strings" + "sync" + "sync/atomic" + "testing" + "testing/synctest" + "time" +) + +func TestRateLimitHeadersAreValidated(t *testing.T) { + now := time.Date(2026, 1, 1, 0, 0, 0, 250000000, time.UTC) + for _, test := range []struct { + name string + headers map[string]string + limit string + remaining string + reset string + delay time.Duration + unsafe bool + }{ + {"modern precedence", map[string]string{"RateLimit-Limit": "100", "X-Rate-Limit-Limit": "200", "RateLimit-Remaining": "004", "RateLimit-Reset": "37", "X-Rate-Limit-Reset": "1700000000"}, "100", "4", "37", 37 * time.Second, false}, + {"legacy output only", map[string]string{"X-RateLimit-Limit": "100", "X-Rate-Limit-Remaining": "4", "X-RateLimit-Reset": "1700000000"}, "100", "4", "1700000000", 2 * time.Second, false}, + {"retry preferred", map[string]string{"Retry-After": "37", "RateLimit-Reset": "9"}, "", "", "9", 37 * time.Second, false}, + {"zero retry preferred", map[string]string{"Retry-After": "0", "RateLimit-Reset": "9"}, "", "", "9", 0, false}, + {"date rounds up", map[string]string{"Retry-After": now.Add(37 * time.Second).Format(http.TimeFormat)}, "", "", "", 37 * time.Second, false}, + {"negative and injection rejected", map[string]string{"Retry-After": "-1", "RateLimit-Reset": "-9", "RateLimit-Limit": "secret", "RateLimit-Remaining": "2\nprivate"}, "", "", "", 2 * time.Second, false}, + {"malformed reset ignored", map[string]string{"RateLimit-Reset": "3.2", "Retry-After": "tomorrow"}, "", "", "", 2 * time.Second, false}, + {"overflow fails closed", map[string]string{"Retry-After": "999999999999999999999999"}, "", "", "", 2 * time.Second, true}, + {"duration overflow fails closed", map[string]string{"RateLimit-Reset": "9223372037"}, "", "", "9223372037", 2 * time.Second, true}, + {"valid retry beats invalid reset", map[string]string{"Retry-After": "37", "RateLimit-Reset": "999999999999999999999999"}, "", "", "", 37 * time.Second, false}, + } { + t.Run(test.name, func(t *testing.T) { + header := http.Header{} + for name, value := range test.headers { + header.Set(name, value) + } + rate := rateLimitFromHeadersAt(header, now) + if rate.Limit != test.limit || rate.Remaining != test.remaining || rate.Reset != test.reset || rate.retryDelay(1) != test.delay || rate.timingUnsafe != test.unsafe { + t.Fatalf("rate=%+v delay=%v", rate, rate.retryDelay(1)) + } + }) + } +} + +func TestReadRetryWaitBudgetAndTiming(t *testing.T) { + for _, test := range []struct { + name string + status int + headers map[string]string + failures int32 + wantCalls int32 + wantDelay time.Duration + wantCode string + deadline time.Duration + }{ + {"37 second retry", 429, map[string]string{"Retry-After": "37"}, 1, 2, 37 * time.Second, "", 0}, + {"37 second reset", 429, map[string]string{"RateLimit-Reset": "37"}, 1, 2, 37 * time.Second, "", 0}, + {"three attempts maximum", 429, nil, 10, 3, 6 * time.Second, "", 0}, + {"total wait budget", 429, map[string]string{"RateLimit-Reset": "37"}, 10, 2, 37 * time.Second, "RATE_LIMIT_WAIT_EXCEEDED", 0}, + {"long wait refused", 429, map[string]string{"Retry-After": "61"}, 1, 1, 0, "RATE_LIMIT_WAIT_EXCEEDED", 0}, + {"deadline refused before dispatch", 429, map[string]string{"Retry-After": "37"}, 1, 1, 0, "RATE_LIMIT_WAIT_EXCEEDED", 10 * time.Second}, + {"overflow refused", 429, map[string]string{"Retry-After": "999999999999999999999999"}, 1, 1, 0, "RATE_LIMIT_TIMING_INVALID", 0}, + {"server retry honors long header", 503, map[string]string{"Retry-After": "37"}, 1, 2, 37 * time.Second, "", 0}, + } { + t.Run(test.name, func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + var calls atomic.Int32 + client := rateTestClient(t, func(*http.Request) (*http.Response, error) { + if calls.Add(1) <= test.failures { + return rateResponse(test.status, test.headers), nil + } + return rateResponse(200, map[string]string{"RateLimit-Remaining": "20"}), nil + }) + ctx := context.Background() + if test.deadline > 0 { + var cancel context.CancelFunc + ctx, cancel = context.WithTimeout(ctx, test.deadline) + defer cancel() + } + started := time.Now() + result, err := client.Do(ctx, "", ACLs()) + if calls.Load() != test.wantCalls || time.Since(started) != test.wantDelay { + t.Fatalf("calls=%d elapsed=%v err=%v", calls.Load(), time.Since(started), err) + } + if test.wantCode != "" { + var rateErr *RateLimitError + if !errors.As(err, &rateErr) || rateErr.Code != test.wantCode { + t.Fatalf("error=%v", err) + } + if test.deadline > 0 && !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("deadline cause missing: %v", err) + } + } else if test.failures < test.wantCalls { + if err != nil || result.RateLimit.Remaining != "20" { + t.Fatalf("result=%+v error=%v", result, err) + } + } else { + var apiErr *APIError + if !errors.As(err, &apiErr) || apiErr.HTTPStatus != test.status { + t.Fatalf("error=%v", err) + } + } + }) + }) + } +} + +func TestLowRemainingSharedCooldownAndSingleProbe(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + var calls atomic.Int32 + probeStarted := make(chan struct{}) + finishProbe := make(chan struct{}) + client := rateTestClient(t, func(*http.Request) (*http.Response, error) { + switch calls.Add(1) { + case 1: + return rateResponse(200, map[string]string{"RateLimit-Remaining": "4", "RateLimit-Reset": "37"}), nil + case 2: + close(probeStarted) + <-finishProbe + } + return rateResponse(200, map[string]string{"RateLimit-Remaining": "100"}), nil + }) + if _, err := client.Do(context.Background(), "", ACLs()); err != nil { + t.Fatal(err) + } + other := rateTestClient(t, func(*http.Request) (*http.Response, error) { return rateResponse(200, nil), nil }) + if _, err := other.Do(context.Background(), "", ACLs()); err != nil { + t.Fatalf("unrelated profile blocked: %v", err) + } + mutation, _ := ResourceCreate("campaigns", map[string]any{"name": "synthetic"}) + _, err := client.Do(context.Background(), "1", mutation) + var rateErr *RateLimitError + var ambiguous *AmbiguousWriteError + if !errors.As(err, &rateErr) || !rateErr.Mutation || errors.As(err, &ambiguous) || calls.Load() != 1 { + t.Fatalf("mutation error=%v calls=%d", err, calls.Load()) + } + var group sync.WaitGroup + for range 8 { + group.Go(func() { + if _, err := client.Do(context.Background(), "", ACLs()); err != nil { + t.Error(err) + } + }) + } + <-probeStarted + synctest.Wait() + if calls.Load() != 2 { + t.Fatalf("concurrent probes escaped: %d", calls.Load()) + } + _, err = client.Do(context.Background(), "1", mutation) + if !errors.As(err, &rateErr) || calls.Load() != 2 { + t.Fatalf("mutation during probe error=%v calls=%d", err, calls.Load()) + } + close(finishProbe) + group.Wait() + if calls.Load() != 9 { + t.Fatalf("calls=%d", calls.Load()) + } + }) +} + +func TestRateLimitCancellationDoesNotDispatch(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + var calls atomic.Int32 + client := rateTestClient(t, func(*http.Request) (*http.Response, error) { + calls.Add(1) + return rateResponse(200, map[string]string{"RateLimit-Remaining": "0", "RateLimit-Reset": "37"}), nil + }) + _, _ = client.Do(context.Background(), "", ACLs()) + ctx, cancel := context.WithCancel(context.Background()) + finished := make(chan error, 1) + go func() { _, err := client.Do(ctx, "", ACLs()); finished <- err }() + synctest.Wait() + cancel() + err := <-finished + if !errors.Is(err, context.Canceled) || calls.Load() != 1 { + t.Fatalf("error=%v calls=%d", err, calls.Load()) + } + }) +} + +func TestRateDetailsSurviveAPIError(t *testing.T) { + client := rateTestClient(t, func(*http.Request) (*http.Response, error) { + return rateResponse(403, map[string]string{"RateLimit-Limit": "100", "RateLimit-Remaining": "9", "RateLimit-Reset": "37"}), nil + }) + _, err := client.Do(context.Background(), "", ACLs()) + var apiErr *APIError + if !errors.As(err, &apiErr) || apiErr.RateLimit.Limit != "100" || apiErr.RateLimit.Reset != "37" { + t.Fatalf("error=%+v", err) + } +} + +func rateResponse(status int, headers map[string]string) *http.Response { + header := http.Header{} + for name, value := range headers { + header.Set(name, value) + } + return &http.Response{StatusCode: status, Header: header, Body: io.NopCloser(strings.NewReader(`{"data":[]}`))} +} + +func rateTestClient(t *testing.T, transport func(*http.Request) (*http.Response, error)) *Client { + t.Helper() + client, err := NewClientForTest(&fakeTokens{value: "synthetic"}, &http.Client{Transport: roundTripFunc(transport)}, "https://example.invalid/v1/") + if err != nil { + t.Fatal(fmt.Errorf("create test client: %w", err)) + } + return client +} + +func TestMutationCannotProbeExpiredCooldown(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + var calls atomic.Int32 + client := rateTestClient(t, func(*http.Request) (*http.Response, error) { + if calls.Add(1) == 1 { + return rateResponse(200, map[string]string{"RateLimit-Remaining": "0", "RateLimit-Reset": "1"}), nil + } + return rateResponse(200, map[string]string{"RateLimit-Remaining": "100"}), nil + }) + _, _ = client.Do(context.Background(), "", ACLs()) + time.Sleep(time.Second) + mutation, _ := ResourceCreate("campaigns", map[string]any{"name": "synthetic"}) + _, err := client.Do(context.Background(), "1", mutation) + var rateErr *RateLimitError + if !errors.As(err, &rateErr) || !rateErr.Mutation || calls.Load() != 1 { + t.Fatalf("mutation became probe: error=%v calls=%d", err, calls.Load()) + } + if _, err := client.Do(context.Background(), "", ACLs()); err != nil { + t.Fatal(err) + } + if _, err := client.Do(context.Background(), "1", mutation); err != nil || calls.Load() != 3 { + t.Fatalf("healthy probe did not release cooldown: error=%v calls=%d", err, calls.Load()) + } + }) +} + +func TestProbeWaitSharesTheSixtySecondBudget(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + var calls atomic.Int32 + probeStarted := make(chan struct{}) + finishProbe := make(chan struct{}) + client := rateTestClient(t, func(*http.Request) (*http.Response, error) { + switch calls.Add(1) { + case 1: + return rateResponse(200, map[string]string{"RateLimit-Remaining": "0", "RateLimit-Reset": "1"}), nil + case 2: + close(probeStarted) + <-finishProbe + } + return rateResponse(200, nil), nil + }) + _, _ = client.Do(context.Background(), "", ACLs()) + probeDone := make(chan error, 1) + go func() { _, err := client.Do(context.Background(), "", ACLs()); probeDone <- err }() + <-probeStarted + started := time.Now() + _, err := client.Do(context.Background(), "", ACLs()) + var rateErr *RateLimitError + if !errors.As(err, &rateErr) || rateErr.Code != "RATE_LIMIT_WAIT_EXCEEDED" || time.Since(started) != 60*time.Second || calls.Load() != 2 { + t.Fatalf("error=%v elapsed=%v calls=%d", err, time.Since(started), calls.Load()) + } + close(finishProbe) + if err := <-probeDone; err != nil { + t.Fatal(err) + } + }) +} + +func TestOverflowTimingNeverBecomesShortAutomaticCooldown(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + var calls atomic.Int32 + client := rateTestClient(t, func(*http.Request) (*http.Response, error) { + calls.Add(1) + return rateResponse(429, map[string]string{"Retry-After": "999999999999999999999999"}), nil + }) + _, _ = client.Do(context.Background(), "", ACLs()) + time.Sleep(61 * time.Second) + _, err := client.Do(context.Background(), "", ACLs()) + var rateErr *RateLimitError + if !errors.As(err, &rateErr) || rateErr.Code != "RATE_LIMIT_TIMING_INVALID" || calls.Load() != 1 { + t.Fatalf("unsafe early retry: error=%v calls=%d", err, calls.Load()) + } + }) +} + +func TestMutation429PreservesTimingWithoutRetry(t *testing.T) { + var calls atomic.Int32 + client := rateTestClient(t, func(*http.Request) (*http.Response, error) { + calls.Add(1) + return rateResponse(429, map[string]string{"Retry-After": "37"}), nil + }) + mutation, _ := ResourceCreate("campaigns", map[string]any{"name": "synthetic"}) + _, err := client.Do(context.Background(), "1", mutation) + var apiErr *APIError + if !errors.As(err, &apiErr) || apiErr.Retryable || apiErr.RateLimit.RetryAfter != 37 || calls.Load() != 1 { + t.Fatalf("error=%+v calls=%d", err, calls.Load()) + } +} + +func TestProbeDoesNotClearNewerCooldown(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + var calls atomic.Int32 + firstStarted, finishFirst := make(chan struct{}), make(chan struct{}) + probeStarted, finishProbe := make(chan struct{}), make(chan struct{}) + client := rateTestClient(t, func(*http.Request) (*http.Response, error) { + switch calls.Add(1) { + case 1: + close(firstStarted) + <-finishFirst + return rateResponse(200, map[string]string{"RateLimit-Remaining": "0", "RateLimit-Reset": "37"}), nil + case 2: + return rateResponse(200, map[string]string{"RateLimit-Remaining": "0", "RateLimit-Reset": "1"}), nil + case 3: + close(probeStarted) + <-finishProbe + } + return rateResponse(200, map[string]string{"RateLimit-Remaining": "100"}), nil + }) + firstDone, probeDone := make(chan error, 1), make(chan error, 1) + go func() { _, err := client.Do(context.Background(), "", ACLs()); firstDone <- err }() + <-firstStarted + _, _ = client.Do(context.Background(), "", ACLs()) + go func() { _, err := client.Do(context.Background(), "", ACLs()); probeDone <- err }() + <-probeStarted + close(finishFirst) + if err := <-firstDone; err != nil { + t.Fatal(err) + } + close(finishProbe) + if err := <-probeDone; err != nil { + t.Fatal(err) + } + started := time.Now() + if _, err := client.Do(context.Background(), "", ACLs()); err != nil { + t.Fatal(err) + } + if time.Since(started) != 37*time.Second || calls.Load() != 4 { + t.Fatalf("newer cooldown lost: elapsed=%v calls=%d", time.Since(started), calls.Load()) + } + }) +} + +func TestRemainingFiveDoesNotThrottle(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + client := rateTestClient(t, func(*http.Request) (*http.Response, error) { + return rateResponse(200, map[string]string{"RateLimit-Remaining": "5", "RateLimit-Reset": "37"}), nil + }) + started := time.Now() + for range 2 { + if _, err := client.Do(context.Background(), "", ACLs()); err != nil { + t.Fatal(err) + } + } + if time.Since(started) != 0 { + t.Fatalf("unexpected throttle: %v", time.Since(started)) + } + }) +} + +func TestRetryBackoffIsExponentialAndBounded(t *testing.T) { + for attempt, want := range []time.Duration{2 * time.Second, 4 * time.Second, 8 * time.Second, 16 * time.Second, 16 * time.Second} { + if got := retryDelay(attempt+1, 0); got != want { + t.Fatalf("attempt=%d delay=%v want=%v", attempt+1, got, want) + } + } +} + +func TestLowRemainingWithoutResetUsesFallback(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + var calls atomic.Int32 + client := rateTestClient(t, func(*http.Request) (*http.Response, error) { + if calls.Add(1) == 1 { + return rateResponse(200, map[string]string{"RateLimit-Remaining": "4"}), nil + } + return rateResponse(200, map[string]string{"RateLimit-Remaining": "20"}), nil + }) + if _, err := client.Do(context.Background(), "", ACLs()); err != nil { + t.Fatal(err) + } + started := time.Now() + if _, err := client.Do(context.Background(), "", ACLs()); err != nil { + t.Fatal(err) + } + if calls.Load() != 2 || time.Since(started) != 2*time.Second { + t.Fatalf("calls=%d elapsed=%v", calls.Load(), time.Since(started)) + } + }) +} diff --git a/internal/appleads/types.go b/internal/appleads/types.go index 7b82bc7..a28cabb 100644 --- a/internal/appleads/types.go +++ b/internal/appleads/types.go @@ -3,10 +3,6 @@ package appleads import ( "encoding/json" "fmt" - "net/http" - "strconv" - "strings" - "time" ) const BaseURL = "https://api.ads.apple.com/v1/" @@ -19,6 +15,7 @@ type APIError struct { Body map[string]any `json:"appleBody,omitempty"` ResponseFormat string `json:"responseFormat,omitempty"` Retryable bool `json:"retryable"` + RateLimit RateLimit `json:"rateLimit,omitempty"` } func (e *APIError) Error() string { @@ -33,6 +30,11 @@ type RateLimit struct { Remaining string `json:"remaining,omitempty"` Reset string `json:"reset,omitempty"` RetryAfter int `json:"retryAfterSeconds,omitempty"` + + resetSeconds int + resetSet bool + retrySet bool + timingUnsafe bool } type Pagination struct { @@ -61,41 +63,6 @@ func (e *AmbiguousWriteError) Unwrap() error { return e.Cause } -func rateLimitFromHeaders(header http.Header) RateLimit { - return RateLimit{ - Limit: firstHeader(header, "X-Rate-Limit-Limit", "X-RateLimit-Limit"), - Remaining: firstHeader(header, "X-Rate-Limit-Remaining", "X-RateLimit-Remaining"), - Reset: firstHeader(header, "X-Rate-Limit-Reset", "X-RateLimit-Reset"), - RetryAfter: retryAfterSeconds(header.Get("Retry-After")), - } -} - -func firstHeader(header http.Header, names ...string) string { - for _, name := range names { - if value := strings.TrimSpace(header.Get(name)); value != "" { - return value - } - } - return "" -} - -func retryAfterSeconds(value string) int { - value = strings.TrimSpace(value) - if value == "" { - return 0 - } - if seconds, err := strconv.Atoi(value); err == nil && seconds > 0 { - return seconds - } - if parsed, err := http.ParseTime(value); err == nil { - seconds := int(time.Until(parsed).Seconds()) - if seconds > 0 { - return seconds - } - } - return 0 -} - func normalizeJSON(value any) any { switch typed := value.(type) { case json.Number: diff --git a/internal/live/mcp_lifecycle_v03_test.go b/internal/live/mcp_lifecycle_v03_test.go index 68eacfc..ff30b90 100644 --- a/internal/live/mcp_lifecycle_v03_test.go +++ b/internal/live/mcp_lifecycle_v03_test.go @@ -64,7 +64,7 @@ func TestMCPV03PausedLifecycleAcceptance(t *testing.T) { currency = strings.ToUpper(currency) date := time.Now().UTC().Format("2006-01-02") name := fmt.Sprintf("Apple Ads MCP v0.3 Validation - Lifecycle - %s", date) - campaignID := createV03Campaign(t, ctx, session, profile.Name, accountID, adamID, storefront, currency, dailyBudget, name) + campaignID := createV03Campaign(t, ctx, session, profile.Name, accountID, adamID, storefront, currency, dailyBudget, defaultBid, name) previewApply(t, ctx, session, "campaign_bid_strategy_preview", map[string]any{ "profile": profile.Name, "adAccountId": accountID, "campaignId": campaignID, @@ -97,7 +97,7 @@ func TestMCPV03PausedLifecycleAcceptance(t *testing.T) { previewApplyDelete(t, ctx, session, "ad_group_delete_preview", profile.Name, accountID, deleteGroupID, deleteGroupName) deleteCampaignName := fmt.Sprintf("Apple Ads MCP v0.3 Validation - Delete Campaign - %s", date) - deleteCampaignID := createV03Campaign(t, ctx, session, profile.Name, accountID, adamID, storefront, currency, dailyBudget, deleteCampaignName) + deleteCampaignID := createV03Campaign(t, ctx, session, profile.Name, accountID, adamID, storefront, currency, dailyBudget, defaultBid, deleteCampaignName) previewApplyDelete(t, ctx, session, "campaign_delete_preview", profile.Name, accountID, deleteCampaignID, deleteCampaignName) runV03AdAndCreativeLifecycle(t, ctx, session, profile.Name, accountID, adamID, storefront, currency, dailyBudget, defaultBid, date) @@ -105,12 +105,12 @@ func TestMCPV03PausedLifecycleAcceptance(t *testing.T) { t.Log("v0.3 PAUSED lifecycle acceptance completed with verified deletes and no enabled campaign") } -func createV03Campaign(t *testing.T, ctx context.Context, session *mcp.ClientSession, profile, accountID, adamID, storefront, currency, dailyBudget, name string) string { +func createV03Campaign(t *testing.T, ctx context.Context, session *mcp.ClientSession, profile, accountID, adamID, storefront, currency, dailyBudget, defaultBid, name string) string { t.Helper() - return createV03CampaignForPlacement(t, ctx, session, profile, accountID, adamID, storefront, currency, dailyBudget, name, "APPSTORE_SEARCH_RESULTS") + return createV03CampaignForPlacement(t, ctx, session, profile, accountID, adamID, storefront, currency, dailyBudget, defaultBid, name, "APPSTORE_SEARCH_RESULTS") } -func createV03CampaignForPlacement(t *testing.T, ctx context.Context, session *mcp.ClientSession, profile, accountID, adamID, storefront, currency, dailyBudget, name, placement string) string { +func createV03CampaignForPlacement(t *testing.T, ctx context.Context, session *mcp.ClientSession, profile, accountID, adamID, storefront, currency, dailyBudget, defaultBid, name, placement string) string { t.Helper() if existing := findResourceIDByField(callTool(t, ctx, session, "campaigns_query", map[string]any{ "profile": profile, "adAccountId": accountID, @@ -128,7 +128,7 @@ func createV03CampaignForPlacement(t *testing.T, ctx context.Context, session *m "supplyPlacement": map[string]any{"include": []string{placement}}, "countryOrRegion": map[string]any{"include": []string{storefront}}, }, - "bidStrategy": map[string]any{"bidStrategyType": "MANUAL_CPT", "bidStrategyGoal": "TAP"}, + "bidStrategy": map[string]any{"bidStrategyType": "MANUAL_CPT", "bidStrategyGoal": "TAP", "bid": map[string]any{"amount": defaultBid, "currency": currency}}, }, }) } @@ -157,7 +157,7 @@ func runV03AdAndCreativeLifecycle(t *testing.T, ctx context.Context, session *mc } campaignName := fmt.Sprintf("Apple Ads MCP v0.3 Validation - Ad Delete - %s", date) - campaignID := createV03CampaignForPlacement(t, ctx, session, profile, accountID, adamID, storefront, currency, dailyBudget, campaignName, "APPSTORE_SEARCH_TAB") + campaignID := createV03CampaignForPlacement(t, ctx, session, profile, accountID, adamID, storefront, currency, dailyBudget, defaultBid, campaignName, "APPSTORE_SEARCH_TAB") adGroupName := "Apple Ads MCP v0.3 Validation - Ad Delete Group" adGroupID := createV03AdGroup(t, ctx, session, profile, accountID, campaignID, currency, defaultBid, adGroupName) adName := fmt.Sprintf("Apple Ads MCP v0.3 Validation - Delete Ad - %s", date) diff --git a/internal/live/mcp_operator_v02_test.go b/internal/live/mcp_operator_v02_test.go index bb8cfda..510bb66 100644 --- a/internal/live/mcp_operator_v02_test.go +++ b/internal/live/mcp_operator_v02_test.go @@ -302,7 +302,7 @@ func runV02PreviewMatrix(t *testing.T, ctx context.Context, session *mcp.ClientS "supplyPlacement": map[string]any{"include": []string{"APPSTORE_SEARCH_RESULTS"}}, "countryOrRegion": map[string]any{"include": []string{storefront}}, }, - "bidStrategy": map[string]any{"bidStrategyType": "MANUAL_CPT", "bidStrategyGoal": "TAP"}, + "bidStrategy": map[string]any{"bidStrategyType": "MANUAL_CPT", "bidStrategyGoal": "TAP", "bid": map[string]any{"amount": "0.25", "currency": state.currency}}, }, }) previewOnly(t, ctx, session, "campaign_update_preview", mergeAccount(account, map[string]any{"id": campaignID, "payload": map[string]any{"status": "PAUSED"}})) diff --git a/internal/live/mcp_write_v02_test.go b/internal/live/mcp_write_v02_test.go index f7398fa..3f02893 100644 --- a/internal/live/mcp_write_v02_test.go +++ b/internal/live/mcp_write_v02_test.go @@ -106,7 +106,7 @@ func TestMCPV02PausedFixtures(t *testing.T) { "supplyPlacement": map[string]any{"include": []string{fixture.placement}}, "countryOrRegion": map[string]any{"include": []string{storefront}}, }, - "bidStrategy": map[string]any{"bidStrategyType": "MANUAL_CPT", "bidStrategyGoal": "TAP"}, + "bidStrategy": map[string]any{"bidStrategyType": "MANUAL_CPT", "bidStrategyGoal": "TAP", "bid": map[string]any{"amount": defaultBid, "currency": currency}}, }, } campaignID := findResourceIDByField(callTool(t, ctx, session, "campaigns_query", map[string]any{ diff --git a/internal/mcpserver/schema_test.go b/internal/mcpserver/schema_test.go new file mode 100644 index 0000000..46e36f0 --- /dev/null +++ b/internal/mcpserver/schema_test.go @@ -0,0 +1,232 @@ +package mcpserver + +import ( + "context" + "github.com/modelcontextprotocol/go-sdk/mcp" + "github.com/zelentsov-dev/apple-ads-mcp/internal/appleads" + "github.com/zelentsov-dev/apple-ads-mcp/internal/config" + "io" + "math" + "reflect" + "testing" +) + +func TestMCPMutationSchemasExposeWriteConstraints(t *testing.T) { + clientSession := connectTestServer(t, New(appleads.NewManager(config.Config{}, "none"), false, io.Discard)) + listed, err := clientSession.ListTools(context.Background(), nil) + if err != nil { + t.Fatal(err) + } + tools := make(map[string]*mcp.Tool, len(listed.Tools)) + for _, tool := range listed.Tools { + tools[tool.Name] = tool + } + + statusCases := []struct { + tool string + path []string + }{ + {"campaign_create_preview", []string{"payload", "status"}}, + {"campaign_update_preview", []string{"payload", "status"}}, + {"ad_group_create_preview", []string{"payload", "status"}}, + {"ad_group_update_preview", []string{"payload", "status"}}, + {"keyword_create_preview", []string{"payload", "status"}}, + {"keyword_update_preview", []string{"payload", "status"}}, + {"negative_keyword_create_preview", []string{"payload", "status"}}, + {"negative_keyword_update_preview", []string{"payload", "status"}}, + {"ad_create_preview", []string{"payload", "status"}}, + {"ad_update_preview", []string{"payload", "status"}}, + {"keywords_bulk_create_preview", []string{"items", "[]", "status"}}, + {"keywords_bulk_update_preview", []string{"items", "[]", "status"}}, + {"negative_keywords_bulk_create_preview", []string{"items", "[]", "status"}}, + {"negative_keywords_bulk_update_preview", []string{"items", "[]", "status"}}, + } + for _, test := range statusCases { + t.Run(test.tool+"_status", func(t *testing.T) { + node := toolSchemaNode(t, tools[test.tool], test.path...) + if !reflect.DeepEqual(node["enum"], []any{"ENABLED", "PAUSED"}) { + t.Fatalf("enum=%v", node["enum"]) + } + }) + } + + for _, toolName := range []string{ + "keywords_bulk_create_preview", + "keywords_bulk_update_preview", + "negative_keywords_bulk_create_preview", + "negative_keywords_bulk_update_preview", + } { + t.Run(toolName+"_correlation", func(t *testing.T) { + node := toolSchemaNode(t, tools[toolName], "items", "[]", "correlationId") + branches, ok := node["oneOf"].([]any) + if !ok || len(branches) != 2 { + t.Fatalf("oneOf=%v", node["oneOf"]) + } + integer := branches[0].(map[string]any) + if integer["type"] != "integer" || integer["minimum"] != float64(0) || integer["exclusiveMaximum"] != math.Exp2(63) { + t.Fatalf("integer branch=%v", integer) + } + decimalString := branches[1].(map[string]any) + if decimalString["type"] != "string" || decimalString["minLength"] != float64(1) || decimalString["pattern"] != `^[0-9]+$` { + t.Fatalf("string branch=%v", decimalString) + } + }) + } + +} + +func TestMCPMutationSchemasRejectInvalidArgumentsBeforeHandlers(t *testing.T) { + clientSession := connectTestServer(t, New(appleads.NewManager(config.Config{}, "none"), false, io.Discard)) + keyword := func(status, amount string) map[string]any { + payload := map[string]any{"adGroupId": "456", "text": "voice notes", "matchType": "EXACT", "status": status} + if amount != "" { + payload["bid"] = map[string]any{"amount": amount, "currency": "USD"} + } + return map[string]any{"profile": "owner", "adAccountId": "123", "payload": payload} + } + bulk := func(correlationID any) map[string]any { + return map[string]any{ + "profile": "owner", "adAccountId": "123", "adGroupId": "456", + "items": []any{map[string]any{ + "correlationId": correlationID, "text": "voice notes", "matchType": "EXACT", "status": "PAUSED", + }}, + } + } + + invalidCases := []struct { + name string + tool string + arguments map[string]any + }{ + {"active_status", "keyword_create_preview", keyword("ACTIVE", "")}, + {"descriptive_correlation", "keywords_bulk_create_preview", bulk("k1")}, + {"zero_bid", "keyword_create_preview", keyword("PAUSED", "0")}, + {"leading_zero_bid", "keyword_create_preview", keyword("PAUSED", "01.20")}, + } + for _, test := range invalidCases { + t.Run(test.name, func(t *testing.T) { + result := callTool(t, clientSession, test.tool, test.arguments) + if !result.IsError || result.StructuredContent != nil { + t.Fatalf("result=%+v", result) + } + }) + } + + validCases := []struct { + name string + tool string + arguments map[string]any + }{ + {"enabled_status", "keyword_create_preview", keyword("ENABLED", "")}, + {"one_decimal_bid", "keyword_create_preview", keyword("PAUSED", "1.2")}, + {"two_decimal_bid", "keyword_create_preview", keyword("PAUSED", "1.20")}, + {"three_decimal_bid", "keyword_create_preview", keyword("PAUSED", "1.234")}, + {"subcent_bid", "keyword_create_preview", keyword("PAUSED", "0.001")}, + {"integer_correlation", "keywords_bulk_create_preview", bulk(0)}, + {"digit_string_correlation", "keywords_bulk_create_preview", bulk("1")}, + } + for _, test := range validCases { + t.Run(test.name, func(t *testing.T) { + result := callTool(t, clientSession, test.tool, test.arguments) + if !result.IsError || result.StructuredContent == nil { + t.Fatalf("result=%+v", result) + } + structured := result.StructuredContent.(map[string]any) + diagnostic := structured["error"].(map[string]any) + if diagnostic["type"] != "write_gate_error" { + t.Fatalf("diagnostic=%v", diagnostic) + } + }) + } +} + +func connectTestServer(t *testing.T, server *mcp.Server) *mcp.ClientSession { + t.Helper() + clientTransport, serverTransport := mcp.NewInMemoryTransports() + serverSession, err := server.Connect(context.Background(), serverTransport, nil) + if err != nil { + t.Fatal(err) + } + client := mcp.NewClient(&mcp.Implementation{Name: "contract-test", Version: "1.0.0"}, nil) + clientSession, err := client.Connect(context.Background(), clientTransport, nil) + if err != nil { + serverSession.Close() + t.Fatal(err) + } + t.Cleanup(func() { + clientSession.Close() + serverSession.Close() + }) + return clientSession +} + +func toolSchemaNode(t *testing.T, tool *mcp.Tool, path ...string) map[string]any { + t.Helper() + if tool == nil { + t.Fatal("tool is missing") + } + node := tool.InputSchema.(map[string]any) + for _, part := range path { + if part == "[]" { + node = node["items"].(map[string]any) + continue + } + properties := node["properties"].(map[string]any) + node = properties[part].(map[string]any) + } + return node +} + +func callTool(t *testing.T, session *mcp.ClientSession, name string, arguments map[string]any) *mcp.CallToolResult { + t.Helper() + result, err := session.CallTool(context.Background(), &mcp.CallToolParams{Name: name, Arguments: arguments}) + if err != nil { + t.Fatal(err) + } + return result +} + +func TestMCPStrategySchemaPairsAndDeprecatedCap(t *testing.T) { + session := connectTestServer(t, New(appleads.NewManager(config.Config{}, "none"), false, io.Discard)) + for _, test := range []struct { + name string + strategy map[string]any + valid bool + }{ + {"manual", map[string]any{"bidStrategyType": "MANUAL_CPT", "bidStrategyGoal": "TAP", "bid": map[string]any{"amount": "0.001", "currency": "USD"}}, true}, + {"auto_echo", map[string]any{"bidStrategyType": "MAX_CONVERSIONS", "bidStrategyGoal": "INSTALL", "bid": map[string]any{"amount": "0.00", "currency": "USD"}}, true}, + {"bid_only", map[string]any{"bid": map[string]any{"amount": "1.234", "currency": "USD"}}, true}, + {"missing_goal", map[string]any{"bidStrategyType": "MANUAL_CPT"}, false}, + {"missing_type", map[string]any{"bidStrategyGoal": "TAP"}, false}, + {"mismatched", map[string]any{"bidStrategyType": "MAX_CONVERSIONS", "bidStrategyGoal": "TAP"}, false}, + {"maps", map[string]any{"bidStrategyType": "MANUAL_CPM", "bidStrategyGoal": "IMPRESSION"}, false}, + } { + t.Run(test.name, func(t *testing.T) { + result := callTool(t, session, "ad_group_update_preview", map[string]any{ + "profile": "test", "adAccountId": "123", "id": "456", "payload": map[string]any{"bidStrategy": test.strategy}, + }) + if !result.IsError { + t.Fatalf("read-only server must reject write preview: %+v", result) + } + if test.valid { + diagnostic, ok := result.StructuredContent.(map[string]any) + if !ok || diagnostic["error"].(map[string]any)["type"] != "write_gate_error" { + t.Fatalf("valid schema failed: %+v", result) + } + } else if result.StructuredContent != nil { + t.Fatalf("invalid pair reached handler: %+v", result) + } + }) + } + listed, err := session.ListTools(context.Background(), nil) + if err != nil { + t.Fatal(err) + } + for _, tool := range listed.Tools { + if tool.Name == "ad_group_create_preview" || tool.Name == "ad_group_update_preview" { + if toolSchemaNode(t, tool, "payload", "cpaCap")["deprecated"] != true { + t.Fatal("cpaCap annotation is missing") + } + } + } +} diff --git a/internal/mcpserver/server.go b/internal/mcpserver/server.go index fbf79d8..282467a 100644 --- a/internal/mcpserver/server.go +++ b/internal/mcpserver/server.go @@ -12,7 +12,7 @@ import ( toolset "github.com/zelentsov-dev/apple-ads-mcp/internal/tools" ) -var Version = "0.3.6" +var Version = "0.3.7" type Options struct { AllowWrites bool diff --git a/internal/operations/store.go b/internal/operations/store.go index 7db5a78..0304abe 100644 --- a/internal/operations/store.go +++ b/internal/operations/store.go @@ -37,6 +37,12 @@ type OperationPreview struct { RequiresApply bool `json:"requiresApply"` Impact *OperationImpact `json:"impact,omitempty"` Items []OperationItemPreview `json:"items,omitempty"` + Warnings []OperationWarning `json:"warnings,omitempty"` +} + +type OperationWarning struct { + Code string `json:"code"` + Message string `json:"message"` } type OperationImpact struct { @@ -115,17 +121,21 @@ type RecoveryItem struct { } type VerificationRead struct { - Name string - Operation appleads.Operation - ExpectDeleted bool - RequireComplete bool - Scopes []string + Name string + Operation appleads.Operation + ExpectDeleted bool + RequireComplete bool + Scopes []string + Expected any + ExpectedPagination *appleads.Pagination + Fields []string } type PreviewOptions struct { - Impact *OperationImpact - Items []OperationItemPreview - Create *CreateExpectation + Impact *OperationImpact + Items []OperationItemPreview + Create *CreateExpectation + Warnings []OperationWarning } type CreateExpectation struct { @@ -260,6 +270,7 @@ func (s *Store) PreviewComposite(ctx context.Context, executor Executor, profile RequiresApply: true, Impact: options.Impact, Items: append([]OperationItemPreview(nil), options.Items...), + Warnings: append([]OperationWarning(nil), options.Warnings...), } s.mu.Lock() s.pruneExpiredLocked() @@ -278,7 +289,7 @@ func (s *Store) PreviewComposite(ctx context.Context, executor Executor, profile return preview, nil } -func (s *Store) PreviewSequence(ctx context.Context, executor Executor, profile, adAccountID, name string, targetIDs []string, verify []VerificationRead, steps []SequenceStep, impact *OperationImpact) (OperationPreview, error) { +func (s *Store) PreviewSequence(ctx context.Context, executor Executor, profile, adAccountID, name string, targetIDs []string, verify []VerificationRead, steps []SequenceStep, impact *OperationImpact, warnings ...OperationWarning) (OperationPreview, error) { if len(steps) == 0 || len(steps) > 100 { return OperationPreview{}, errors.New("sequence must contain 1 to 100 mutation steps") } @@ -326,7 +337,7 @@ func (s *Store) PreviewSequence(ctx context.Context, executor Executor, profile, } payload := map[string]any{"actions": payloadItems} placeholder, _ := appleads.ResourceUpdate("campaigns", "sequence-placeholder", map[string]any{"status": "PAUSED"}) - preview, err := s.PreviewComposite(ctx, executor, profile, adAccountID, name, targetIDs, payload, verify, placeholder, PreviewOptions{Impact: impact, Items: items}) + preview, err := s.PreviewComposite(ctx, executor, profile, adAccountID, name, targetIDs, payload, verify, placeholder, PreviewOptions{Impact: impact, Items: items, Warnings: warnings}) if err != nil { return OperationPreview{}, err } @@ -1103,9 +1114,30 @@ func readVerificationState(ctx context.Context, executor Executor, profile, adAc } return nil, nil, nil, fmt.Errorf("read %s: %w", name, err) } + if len(read.Fields) > 0 { + object, ok := result.Data.(map[string]any) + if !ok { + return nil, nil, nil, fmt.Errorf("read %s: expected an object", name) + } + selected := make(map[string]any, len(read.Fields)) + for _, field := range read.Fields { + selected[field] = object[field] + } + result.Data = selected + } if requireComplete && read.RequireComplete && !verificationResultComplete(result) { return nil, nil, nil, fmt.Errorf("read %s: %w", name, ErrVerificationIncomplete) } + if requireComplete && read.ExpectedPagination != nil && *read.ExpectedPagination != result.Pagination { + return nil, nil, nil, fmt.Errorf("read %s: %w", name, ErrStateDrift) + } + if requireComplete && (read.Expected != nil || read.ExpectedPagination != nil) { + expectedHash, expectedErr := valueHash(read.Expected) + actualHash, actualErr := valueHash(result.Data) + if expectedErr != nil || actualErr != nil || expectedHash != actualHash { + return nil, nil, nil, fmt.Errorf("read %s: %w", name, ErrStateDrift) + } + } hashValues[name] = verificationHashValue(result.Data, result.Pagination) currentValues[name] = result.Data objects = append(objects, ObjectVerification{Name: name, Status: "read", Current: result.Data}) diff --git a/internal/operations/store_test.go b/internal/operations/store_test.go index be12ad5..b0c23bf 100644 --- a/internal/operations/store_test.go +++ b/internal/operations/store_test.go @@ -957,3 +957,48 @@ func TestDeleteVerificationTreatsNotFoundAsDeleted(t *testing.T) { t.Fatalf("verification=%+v err=%v", verification, err) } } + +func TestPreviewBindsValidatedDependencyAndPersistsWarnings(t *testing.T) { + store := NewStore() + read, _ := appleads.ResourceGet("campaigns", "123") + write, _ := appleads.ResourceUpdate("campaigns", "123", map[string]any{"status": "PAUSED"}) + before := map[string]any{"status": "ENABLED"} + executor := &fakeExecutor{state: map[string]any{"status": "PAUSED"}} + reads := []VerificationRead{{Name: "validated_campaign", Operation: read, Expected: before}} + options := PreviewOptions{Warnings: []OperationWarning{{Code: "TEST_WARNING", Message: "Synthetic warning"}}} + if _, err := store.PreviewComposite(t.Context(), executor, "synthetic", "456", "pause", []string{"123"}, map[string]any{"status": "PAUSED"}, reads, write, options); !errors.Is(err, ErrStateDrift) { + t.Fatalf("changed between validation and preview: %v", err) + } + executor.state = before + preview, err := store.PreviewComposite(t.Context(), executor, "synthetic", "456", "pause", []string{"123"}, map[string]any{"status": "PAUSED"}, reads, write, options) + if err != nil { + t.Fatal(err) + } + inspected, used, err := store.Inspect(preview.Receipt) + if err != nil || used || len(inspected.Warnings) != 1 || inspected.Warnings[0].Code != "TEST_WARNING" { + t.Fatalf("preview=%+v used=%v err=%v", inspected, used, err) + } + executor.state = map[string]any{"status": "PAUSED"} + if _, err := store.Apply(t.Context(), executor, preview.Receipt); !errors.Is(err, ErrStateDrift) || executor.writes != 0 { + t.Fatalf("writes=%d err=%v", executor.writes, err) + } +} + +func TestVerificationDependencyProjectsOnlyNeededFields(t *testing.T) { + store := NewStore() + read, _ := appleads.AdAccount("456") + write, _ := appleads.ResourceUpdate("campaigns", "123", map[string]any{"status": "PAUSED"}) + executor := &fakeExecutor{state: map[string]any{"currency": "USD", "privateBillingField": "synthetic-private"}} + preview, err := store.PreviewComposite(t.Context(), executor, "synthetic", "456", "pause", nil, map[string]any{"status": "PAUSED"}, []VerificationRead{{Name: "currency", Operation: read, Expected: map[string]any{"currency": "USD"}, Fields: []string{"currency"}}}, write, PreviewOptions{}) + if err != nil { + t.Fatal(err) + } + data, _ := json.Marshal(preview) + if strings.Contains(string(data), "synthetic-private") { + t.Fatalf("unexpected private evidence: %s", data) + } + executor.state = map[string]any{"currency": "USD", "privateBillingField": "changed-private"} + if _, err := store.Apply(t.Context(), executor, preview.Receipt); err != nil || executor.writes != 1 { + t.Fatalf("writes=%d err=%v", executor.writes, err) + } +} diff --git a/internal/optimization/algorithm.go b/internal/optimization/algorithm.go index abbe133..3353fff 100644 --- a/internal/optimization/algorithm.go +++ b/internal/optimization/algorithm.go @@ -313,14 +313,24 @@ func campaignPlan(item CampaignBaseline, policy Policy, thresholds Thresholds, t add(20, "campaign", campaign.CampaignID, "budget_decrease", "CPI exceeded the target in both completed seven-day windows", map[string]any{"dailyBudget": campaign.DailyBudget}, map[string]any{"dailyBudget": after}) } } - if policy.Permissions.Strategy && campaign.BidStrategy == "MANUAL_CPT" && campaign.Placement == "APPSTORE_SEARCH_RESULTS" && campaign.SearchMatch && campaign.MaxConversionsEligible && last14.Days >= thresholds.MaxConversionsMinimumDays { - average := new(big.Rat).Quo(new(big.Rat).SetInt64(last14.TapInstalls), big.NewRat(int64(last14.Days), 1)) + strategyChanges := false + if policy.Permissions.Strategy && campaign.BidStrategy == "MANUAL_CPT" && campaign.Placement == "APPSTORE_SEARCH_RESULTS" && campaign.SearchMatch && campaign.MaxConversionsEligible { + completed, err := completedWindow(campaign.Daily, now, 28) + if err != nil { + return nil, err + } + strategyWindow, err := summarize(tail(completed, thresholds.MaxConversionsMinimumDays), campaign.DailyBudget) + if err != nil { + return nil, err + } + average := new(big.Rat).Quo(new(big.Rat).SetInt64(strategyWindow.TapInstalls), big.NewRat(int64(strategyWindow.Days), 1)) minimum, _ := positiveRat(thresholds.MaxConversionsDailyAvg) if average.Cmp(minimum) >= 0 { + strategyChanges = true add(30, "campaign", campaign.CampaignID, "bid_strategy", "Search Match campaign meets Apple eligibility and completed-data thresholds", map[string]any{"bidStrategy": campaign.BidStrategy}, map[string]any{"bidStrategy": "MAX_CONVERSIONS"}) } } - if policy.Permissions.Bid { + if policy.Permissions.Bid && campaign.BidStrategy == "MANUAL_CPT" && !strategyChanges { for _, biddable := range campaign.Biddables { if biddable.Bid == nil || biddable.Status != "ENABLED" { continue diff --git a/internal/optimization/algorithm_test.go b/internal/optimization/algorithm_test.go index 6da46b9..3203cf7 100644 --- a/internal/optimization/algorithm_test.go +++ b/internal/optimization/algorithm_test.go @@ -333,3 +333,56 @@ func max64(left, right int64) int64 { } return right } + +func TestStrategyUsesConfiguredCompletedWindowAndAverage(t *testing.T) { + now := time.Date(2026, 8, 25, 12, 0, 0, 0, time.UTC) + for _, test := range []struct { + name string + days int + average string + installs int64 + want bool + }{ + {"baseline 70", 14, "5.00", 5, true}, + {"below baseline", 14, "5.00", 4, false}, + {"stricter window", 21, "5.00", 5, true}, + {"stricter average", 21, "6.00", 5, false}, + {"stricter both", 28, "6.00", 6, true}, + } { + t.Run(test.name, func(t *testing.T) { + policy := validPolicy() + policy.Permissions = Permissions{Strategy: true} + policy.Thresholds.MaxConversionsMinimumDays = test.days + policy.Thresholds.MaxConversionsDailyAvg = test.average + evidence := campaignEvidence(now, "30.00", test.installs, "50.00") + evidence.SearchMatch = true + evidence.MaxConversionsEligible = true + plan, err := BuildPlan(policy, []CampaignEvidence{evidence}, History{}, now) + if err != nil || (len(plan.Actions) == 1) != test.want { + t.Fatalf("actions=%+v err=%v", plan.Actions, err) + } + }) + } +} + +func TestAutomaticStrategyNeverGeneratesManualChildBidActions(t *testing.T) { + now := time.Date(2026, 8, 25, 12, 0, 0, 0, time.UTC) + for _, currentStrategy := range []string{"MANUAL_CPT", "MAX_CONVERSIONS"} { + policy := validPolicy() + policy.Permissions = Permissions{Strategy: true, Bid: true} + evidence := campaignEvidence(now, "30.00", 5, "50.00") + evidence.BidStrategy = currentStrategy + evidence.SearchMatch = true + evidence.MaxConversionsEligible = true + evidence.Biddables = []BiddableEvidence{{ResourceType: "ad_group", ResourceID: "10", Status: "ENABLED", Bid: &appleads.Money{Amount: "1.00", Currency: "USD"}, Daily: evidence.Daily}} + plan, err := BuildPlan(policy, []CampaignEvidence{evidence}, History{}, now) + if err != nil { + t.Fatal(err) + } + for _, action := range plan.Actions { + if action.Action == "bid_increase" || action.Action == "bid_decrease" { + t.Fatalf("strategy=%s manual action=%+v", currentStrategy, action) + } + } + } +} diff --git a/internal/tools/advanced_mutations.go b/internal/tools/advanced_mutations.go index 6cc2bdb..45c898a 100644 --- a/internal/tools/advanced_mutations.go +++ b/internal/tools/advanced_mutations.go @@ -45,14 +45,6 @@ func (s *Service) campaignBidStrategyPreview(store *operations.Store) func(conte if err != nil { return failedPreview(err) } - if err := validateBidStrategy(payload["bidStrategy"]); err != nil { - return failedPreview(err) - } - if strings.EqualFold(input.Strategy.BidStrategyType, "MAX_CONVERSIONS") { - if err := s.ensureMaxConversionsEligible(ctx, input.AccountInput, input.CampaignID); err != nil { - return failedPreview(err) - } - } return s.updatePreviewPayload(ctx, store, "campaigns", "campaign_bid_strategy", input.AccountInput, input.CampaignID, payload) } } @@ -70,10 +62,15 @@ func (s *Service) optimizationPlanPreview(store *operations.Store) func(context. return failedPreview(err) } now := s.nowUTC() - evidence, _, err := s.optimizationEvidence(ctx, policy, now) + capture := &optimizationEvidenceCapture{appleAdsManager: s.manager} + evidenceService := &Service{manager: capture} + evidence, _, err := evidenceService.optimizationEvidence(ctx, policy, now) if err != nil { return failedPreview(err) } + if capture.err != nil { + return failedPreview(capture.err) + } plan, err := optimization.BuildPlan(policy, evidence, history, now) if err != nil { return failedPreview(err) @@ -85,14 +82,36 @@ func (s *Service) optimizationPlanPreview(store *operations.Store) func(context. verify := make([]operations.VerificationRead, 0, len(plan.Actions)) seenReads := map[string]struct{}{} targetIDs := make([]string, 0, len(plan.Actions)) + warnings := make([]operations.OperationWarning, 0) for _, action := range plan.Actions { resource, payload, err := optimizationMutation(action) if err != nil { return failedPreview(err) } + payload, err = typedPayloadMap(payload) + if err != nil { + return failedPreview(err) + } + if err := validateTypedResourcePayload(resource, false, payload); err != nil { + return failedPreview(err) + } if err := s.ensureAppStoreMutation(ctx, input.AccountInput, resource, action.ResourceID, payload, false); err != nil { return failedPreview(err) } + evidence, actionWarnings, err := s.bidStrategyEvidence(ctx, input.AccountInput, resource, action.ResourceID, payload, false) + if err != nil { + return failedPreview(err) + } + for index := range evidence { + evidence[index].Name = action.CorrelationID + "_" + evidence[index].Name + } + verify = append(verify, evidence...) + for _, warning := range actionWarnings { + if warning.Code == "MAX_CONVERSIONS_HISTORY_UNCONFIRMED" { + warning = operations.OperationWarning{Code: "MAX_CONVERSIONS_LEARNING_PERIOD", Message: "Allow at least two weeks to assess learning after the strategy change."} + } + warnings = append(warnings, warning) + } mutation, _ := appleads.ResourceUpdate(resource, action.ResourceID, payload) steps = append(steps, operations.SequenceStep{Item: operations.OperationItemPreview{ CorrelationID: action.CorrelationID, CampaignID: action.CampaignID, @@ -113,26 +132,11 @@ func (s *Service) optimizationPlanPreview(store *operations.Store) func(context. targetIDs = append(targetIDs, action.ResourceID) } } - reportEnd := now.UTC().AddDate(0, 0, -1) - reportStart := reportEnd.AddDate(0, 0, -27) - for _, campaignID := range policy.CampaignIDs { - campaignReport, err := optimizationCampaignReportOperation(policy, "campaigns", campaignID, reportStart, reportEnd) - if err != nil { - return failedPreview(err) - } - verify = append(verify, operations.VerificationRead{Name: "report_campaign_" + campaignID, Operation: campaignReport}) - for _, kind := range []string{"adgroups", "keywords"} { - report, err := optimizationBiddableReportOperation(policy, kind, campaignID, reportStart, reportEnd) - if err != nil { - return failedPreview(err) - } - verify = append(verify, operations.VerificationRead{Name: "report_" + kind + "_" + campaignID, Operation: report}) - } - } + verify = append(verify, capture.reads...) preview, err := store.PreviewSequence(ctx, s.manager, input.Profile, input.AdAccountID, "optimization_plan", targetIDs, verify, steps, &operations.OperationImpact{ SpendAffecting: true, ObjectCount: len(steps), Currency: policy.MaxTotalDailyBudget.Currency, MaximumAmount: &policy.MaxTotalDailyBudget, Policy: policy.Name, - }) + }, warnings...) if err != nil { return failedPreview(err) } @@ -145,6 +149,13 @@ func (s *Service) optimizationPlanPreview(store *operations.Store) func(context. func optimizationExpectedBefore(action optimization.PlanAction, resource string) map[string]any { switch action.Action { + case "bid_strategy": + strategyType := fmt.Sprint(action.Before["bidStrategy"]) + goal := "TAP" + if strategyType == "MAX_CONVERSIONS" { + goal = "INSTALL" + } + return map[string]any{"bidStrategy": map[string]any{"bidStrategyType": strategyType, "bidStrategyGoal": goal}} case "budget", "budget_increase", "budget_decrease": if money, ok := moneyFromAnyTool(action.Before["dailyBudget"]); ok { return map[string]any{"dailyBudget": map[string]any{"value": money}} @@ -177,7 +188,12 @@ func optimizationMutation(action optimization.PlanAction) (string, map[string]an } return "campaigns", map[string]any{"dailyBudget": map[string]any{"value": money}}, nil case "bid_strategy": - return "campaigns", map[string]any{"bidStrategy": map[string]any{"bidStrategyType": fmt.Sprint(action.After["bidStrategy"])}}, nil + strategyType := fmt.Sprint(action.After["bidStrategy"]) + goal := "TAP" + if strategyType == "MAX_CONVERSIONS" { + goal = "INSTALL" + } + return "campaigns", map[string]any{"bidStrategy": map[string]any{"bidStrategyType": strategyType, "bidStrategyGoal": goal}}, nil case "bid_increase", "bid_decrease": money, ok := moneyFromAnyTool(action.After["bid"]) if !ok { @@ -203,55 +219,6 @@ func moneyFromAnyTool(value any) (appleads.Money, bool) { } } -func (s *Service) ensureMaxConversionsEligible(ctx context.Context, account AccountInput, campaignID string) error { - if err := s.ensureCampaignPlacement(ctx, account, campaignID, "APPSTORE_SEARCH_RESULTS"); err != nil { - return err - } - campaign, err := s.readResource(ctx, account, "campaigns", campaignID) - if err != nil { - return err - } - if !containsStringValue(campaign, "MAX_CONVERSIONS") && !containsTrueField(campaign, "maxConversionsEligible") { - return errors.New("campaign metadata from Apple does not confirm MAX_CONVERSIONS eligibility") - } - end := time.Now().UTC().AddDate(0, 0, -1) - start := end.AddDate(0, 0, -13) - policy := optimization.Policy{ - Profile: account.Profile, AdAccountID: account.AdAccountID, - MaxTotalDailyBudget: appleads.Money{Amount: "1", Currency: "USD"}, - } - accountOperation, _ := appleads.AdAccount(account.AdAccountID) - accountResult, err := s.manager.Do(ctx, account.Profile, account.AdAccountID, accountOperation) - if err != nil { - return err - } - policy.MaxTotalDailyBudget.Currency = strings.ToUpper(findStringField(accountResult.Data, "currency")) - metrics, err := s.optimizationReport(ctx, policy, "campaigns", campaignID, start, end) - if err != nil { - return fmt.Errorf("verify MAX_CONVERSIONS performance: %w", err) - } - installs := int64(0) - for _, metric := range metrics { - installs += metric.TapInstalls - } - if len(metrics) < 14 || installs < 70 { - return errors.New("MAX_CONVERSIONS requires 14 completed reporting days and at least five tap installs per day on average") - } - request := map[string]any{ - "filters": []any{map[string]any{"field": "campaignId", "operator": "EQUALS", "value": wireID(campaignID)}}, - "pagination": map[string]any{"offset": 0, "pageSize": MaxItems}, - } - query, _ := appleads.ResourceQuery("adgroups", request) - adGroups, err := s.manager.Do(ctx, account.Profile, account.AdAccountID, query) - if err != nil { - return err - } - if !containsTrueField(adGroups.Data, "automatedKeywordsOptIn") { - return errors.New("MAX_CONVERSIONS requires an eligible Search Match ad group") - } - return nil -} - func (s *Service) sharedBudgetCreatePreview(store *operations.Store) func(context.Context, *mcp.CallToolRequest, SharedBudgetCreatePreviewInput) (*mcp.CallToolResult, PreviewOutput, error) { return func(ctx context.Context, _ *mcp.CallToolRequest, input SharedBudgetCreatePreviewInput) (*mcp.CallToolResult, PreviewOutput, error) { if err := s.ensureLOC(ctx, input.AccountInput); err != nil { @@ -713,32 +680,11 @@ func (s *Service) deleteInventory(ctx context.Context, account AccountInput, res return reads, parentIDs, cascadeCount, nil } -func containsTrueField(value any, field string) bool { - switch typed := value.(type) { - case map[string]any: - if current, ok := typed[field].(bool); ok && current { - return true - } - for _, item := range typed { - if containsTrueField(item, field) { - return true - } - } - case []any: - for _, item := range typed { - if containsTrueField(item, field) { - return true - } - } - } - return false -} - func addDeletePreviewTool[In any](server *mcp.Server, item Spec, handler mcp.ToolHandlerFor[In, PreviewOutput]) { destructive := true open := true mcp.AddTool(server, &mcp.Tool{ - Name: item.Name, Description: item.Description, + Name: item.Name, Description: item.Description, InputSchema: mutationInputSchema[In](item.Name), Annotations: &mcp.ToolAnnotations{Title: strings.ReplaceAll(item.Name, "_", " "), ReadOnlyHint: true, IdempotentHint: true, DestructiveHint: &destructive, OpenWorldHint: &open}, }, handler) } diff --git a/internal/tools/bid_strategy_test.go b/internal/tools/bid_strategy_test.go new file mode 100644 index 0000000..75f7f29 --- /dev/null +++ b/internal/tools/bid_strategy_test.go @@ -0,0 +1,275 @@ +package tools + +import ( + "context" + "errors" + "fmt" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/zelentsov-dev/apple-ads-mcp/internal/appleads" + "github.com/zelentsov-dev/apple-ads-mcp/internal/config" + "github.com/zelentsov-dev/apple-ads-mcp/internal/operations" + "github.com/zelentsov-dev/apple-ads-mcp/internal/optimization" +) + +func strategyFixture(strategyType string) map[string]any { + goal := "TAP" + if strategyType == "MAX_CONVERSIONS" { + goal = "INSTALL" + } + return map[string]any{ + "id": "100", "name": "Synthetic campaign", "promotedObjectType": "APPSTORE_APP", "billingEvent": "TAPS", "status": "PAUSED", + "targeting": map[string]any{"supplyPlacement": map[string]any{"include": []any{"APPSTORE_SEARCH_RESULTS"}}}, + "bidStrategy": map[string]any{"bidStrategyType": strategyType, "bidStrategyGoal": goal, "bid": map[string]any{"amount": "1.125", "currency": "USD"}}, + } +} + +func strategyManager(strategyType string) *v036Manager { + return &v036Manager{ + profile: config.Profile{Name: "synthetic", AllowWrites: true}, + responses: map[string][]appleads.Result{ + "acls": {{Data: map[string]any{"acls": []any{map[string]any{"adAccount": map[string]any{"id": "123"}, "roles": []any{"API Campaign Manager"}}}}}}, + "ad-accounts/123": {{Data: map[string]any{"currency": "USD", "privateBillingField": "must-not-be-exposed"}}}, + "campaigns/100": {{Data: strategyFixture(strategyType)}}, + "adgroups/10": {{Data: map[string]any{"id": "10", "campaignId": "100", "pricingModel": "CPT", "status": "PAUSED"}}}, + }, + } +} + +func TestBidStrategyCreateAndUpdateContract(t *testing.T) { + bid := map[string]any{"amount": "0.00125", "currency": "USD"} + for _, test := range []struct { + name string + value any + create, required, valid bool + }{ + {"required campaign", nil, true, true, false}, + {"inherited group", nil, true, false, true}, + {"empty object", map[string]any{}, false, false, false}, + {"type only", map[string]any{"bidStrategyType": "MANUAL_CPT"}, false, false, false}, + {"goal only", map[string]any{"bidStrategyGoal": "TAP"}, false, false, false}, + {"wrong pair", map[string]any{"bidStrategyType": "MAX_CONVERSIONS", "bidStrategyGoal": "TAP"}, false, false, false}, + {"manual creation requires bid", map[string]any{"bidStrategyType": "MANUAL_CPT", "bidStrategyGoal": "TAP"}, true, true, false}, + {"manual precision", map[string]any{"bidStrategyType": "MANUAL_CPT", "bidStrategyGoal": "TAP", "bid": bid}, true, true, true}, + {"auto creation ceiling", map[string]any{"bidStrategyType": "MAX_CONVERSIONS", "bidStrategyGoal": "INSTALL", "bid": bid}, true, true, true}, + {"auto creation no ceiling", map[string]any{"bidStrategyType": "MAX_CONVERSIONS", "bidStrategyGoal": "INSTALL"}, true, true, true}, + {"partial manual bid", map[string]any{"bid": bid}, false, false, true}, + {"create bid only", map[string]any{"bid": bid}, true, false, false}, + {"auto creation zero", map[string]any{"bidStrategyType": "MAX_CONVERSIONS", "bidStrategyGoal": "INSTALL", "bid": map[string]any{"amount": "0", "currency": "USD"}}, true, false, false}, + } { + t.Run(test.name, func(t *testing.T) { + err := validateBidStrategyForOperation(test.value, test.create, test.required) + if (err == nil) != test.valid { + t.Fatalf("valid=%v err=%v", test.valid, err) + } + }) + } +} + +func TestAdGroupContextPreventsStrategyBypass(t *testing.T) { + for _, test := range []struct { + name, parent, amount, strategyType, goal string + create, valid bool + }{ + {"manual partial", "MANUAL_CPT", "0.00125", "", "", false, true}, + {"auto partial rejected", "MAX_CONVERSIONS", "1", "", "", false, false}, + {"auto nonzero rejected", "MAX_CONVERSIONS", "1", "MAX_CONVERSIONS", "INSTALL", false, false}, + {"auto zero echo", "MAX_CONVERSIONS", "0.00", "MAX_CONVERSIONS", "INSTALL", false, true}, + {"auto create ceiling", "MAX_CONVERSIONS", "1.125", "MAX_CONVERSIONS", "INSTALL", true, true}, + {"incompatible manual", "MAX_CONVERSIONS", "1", "MANUAL_CPT", "TAP", false, false}, + {"incompatible auto", "MANUAL_CPT", "0", "MAX_CONVERSIONS", "INSTALL", false, false}, + } { + t.Run(test.name, func(t *testing.T) { + requested := map[string]any{"bid": map[string]any{"amount": test.amount, "currency": "USD"}} + if test.strategyType != "" { + requested["bidStrategyType"], requested["bidStrategyGoal"] = test.strategyType, test.goal + } + err := validateAdGroupStrategyContext(strategyFixture(test.parent), map[string]any{"pricingModel": "CPT"}, requested, test.create) + if (err == nil) != test.valid { + t.Fatalf("valid=%v err=%v", test.valid, err) + } + }) + } + if err := validateAdGroupStrategyContext(strategyFixture("MAX_CONVERSIONS"), map[string]any{"pricingModel": "CPT"}, nil, true); err != nil { + t.Fatal(err) + } +} + +func TestExplicitStrategyPreviewNeedsNoHistoricalReadAndPersistsWarnings(t *testing.T) { + for _, specialized := range []bool{false, true} { + manager := strategyManager("MANUAL_CPT") + service := &Service{manager: manager, allowWrites: true} + store := operations.NewStore() + account := AccountInput{Profile: "synthetic", AdAccountID: "123"} + strategy := BidStrategy{BidStrategyType: "MAX_CONVERSIONS", BidStrategyGoal: "INSTALL"} + var output PreviewOutput + var err error + if specialized { + _, output, err = service.campaignBidStrategyPreview(store)(t.Context(), nil, CampaignBidStrategyPreviewInput{AccountInput: account, CampaignID: "100", Strategy: strategy}) + } else { + _, output, err = typedUpdatePreview[CampaignUpdatePayload](service, store, "campaigns", "campaign_update_preview")(t.Context(), nil, TypedUpdatePreviewInput[CampaignUpdatePayload]{AccountInput: account, ID: "100", Payload: CampaignUpdatePayload{BidStrategy: &strategy}}) + } + if err != nil || output.Error != nil || output.Preview == nil { + t.Fatalf("specialized=%v output=%+v err=%v", specialized, output, err) + } + preview, used, err := store.Inspect(output.Preview.Receipt) + if err != nil || used || len(preview.Warnings) != 2 { + t.Fatalf("preview=%+v used=%v err=%v", preview, used, err) + } + for _, path := range manager.calls { + if strings.Contains(path, "reports/") { + t.Fatalf("unexpected report request %s", path) + } + } + } +} + +func TestAdGroupPreviewBindsParentAndAccount(t *testing.T) { + for _, drift := range []string{"campaigns/100", "ad-accounts/123"} { + manager := strategyManager("MANUAL_CPT") + service := &Service{manager: manager, allowWrites: true} + store := operations.NewStore() + _, output, err := service.adGroupBidPreview(store)(t.Context(), nil, AdGroupBidPreviewInput{AccountInput: AccountInput{Profile: "synthetic", AdAccountID: "123"}, AdGroupID: "10", Amount: "1.125", Currency: "USD"}) + if err != nil || output.Error != nil || output.Preview == nil { + t.Fatalf("output=%+v err=%v", output, err) + } + if strings.Contains(fmt.Sprint(output.Preview.Before), "privateBillingField") { + t.Fatal("account details leaked into preview") + } + if drift == "campaigns/100" { + manager.responses[drift] = []appleads.Result{{Data: strategyFixture("MAX_CONVERSIONS")}} + } else { + manager.responses[drift] = []appleads.Result{{Data: map[string]any{"currency": "EUR"}}} + } + _, err = store.Apply(t.Context(), manager, output.Preview.Receipt) + if !errors.Is(err, operations.ErrStateDrift) { + t.Fatalf("drift=%s err=%v", drift, err) + } + } +} + +func TestLegacyCPACapWarningsSurviveInspect(t *testing.T) { + manager := strategyManager("MANUAL_CPT") + service := &Service{manager: manager, allowWrites: true} + store := operations.NewStore() + _, output, err := service.adGroupCPACapPreview(store)(t.Context(), nil, AdGroupBidPreviewInput{AccountInput: AccountInput{Profile: "synthetic", AdAccountID: "123"}, AdGroupID: "10", Amount: "2.125", Currency: "USD"}) + if err != nil || output.Error != nil || output.Preview == nil { + t.Fatalf("output=%+v err=%v", output, err) + } + preview, _, err := store.Inspect(output.Preview.Receipt) + if err != nil || len(preview.Warnings) != 1 || preview.Warnings[0].Code != "CPA_CAP_DEPRECATED" { + t.Fatalf("preview=%+v err=%v", preview, err) + } +} + +func TestOptimizationStrategyWirePayloadIncludesGoal(t *testing.T) { + _, payload, err := optimizationMutation(optimization.PlanAction{ResourceType: "campaign", Action: "bid_strategy", After: map[string]any{"bidStrategy": "MAX_CONVERSIONS"}}) + if err != nil || stringField(payload["bidStrategy"].(map[string]any), "bidStrategyGoal") != "INSTALL" { + t.Fatalf("payload=%v err=%v", payload, err) + } +} + +func TestCampaignEligibilityUsesDocumentedFields(t *testing.T) { + campaign := strategyFixture("MANUAL_CPT") + if !campaignEvidenceFromObject("100", campaign).MaxConversionsEligible { + t.Fatal("documented contract should establish eligibility without undocumented flags") + } + campaign["billingEvent"] = "IMPRESSIONS" + campaign["unrelated"] = map[string]any{"value": "MAX_CONVERSIONS", "maxConversionsEligible": true} + if campaignEvidenceFromObject("100", campaign).MaxConversionsEligible { + t.Fatal("unrelated strings or flags must not authorize a strategy") + } +} + +func TestCampaignStrategyValidatesFinalTargeting(t *testing.T) { + for _, withStrategy := range []bool{true, false} { + manager := strategyManager("MAX_CONVERSIONS") + service := &Service{manager: manager, allowWrites: true} + payload := map[string]any{"targeting": map[string]any{"supplyPlacement": map[string]any{"include": []any{"APPSTORE_SEARCH_TAB"}}}} + if withStrategy { + payload["bidStrategy"] = map[string]any{"bidStrategyType": "MAX_CONVERSIONS", "bidStrategyGoal": "INSTALL"} + } + _, _, err := service.bidStrategyEvidence(t.Context(), AccountInput{Profile: "synthetic", AdAccountID: "123"}, "campaigns", "100", payload, false) + if err == nil || !strings.Contains(err.Error(), "APPSTORE_SEARCH_RESULTS") { + t.Fatalf("withStrategy=%v err=%v", withStrategy, err) + } + _, output, err := service.updatePreviewPayload(t.Context(), operations.NewStore(), "campaigns", "campaign_update_preview", AccountInput{Profile: "synthetic", AdAccountID: "123"}, "100", payload) + if err != nil || output.Error == nil || output.Preview != nil { + t.Fatalf("withStrategy=%v output=%+v err=%v", withStrategy, output, err) + } + } +} + +func TestAutomaticStrategyRejectsNegativeAndEmptyPairFields(t *testing.T) { + for _, strategy := range []map[string]any{ + {"bidStrategyType": "MAX_CONVERSIONS", "bidStrategyGoal": "INSTALL", "bid": map[string]any{"amount": "-0.1", "currency": "USD"}}, + {"bidStrategyType": "", "bidStrategyGoal": "", "bid": map[string]any{"amount": "1", "currency": "USD"}}, + } { + if err := validateBidStrategy(strategy); err == nil { + t.Fatalf("invalid strategy accepted: %v", strategy) + } + } +} + +type optimizerReportDriftManager struct { + *receiptScopeManager + reportReads int +} + +func (m *optimizerReportDriftManager) Do(ctx context.Context, profile, account string, operation appleads.Operation) (appleads.Result, error) { + result, err := m.receiptScopeManager.Do(ctx, profile, account, operation) + if operation.Path() == "reports/apps/campaigns/query" { + m.reportReads++ + if m.reportReads > 1 { + result.Data = []any{optimizationReportRow(m.now, "100", "campaign", "10.00", 1)} + } + } + return result, err +} + +func TestOptimizerRejectsReportChangeBetweenPlanningAndReceipt(t *testing.T) { + root := t.TempDir() + now := time.Date(2026, 8, 31, 12, 0, 0, 0, time.UTC) + policyPath := filepath.Join(root, "policies.json") + policy := optimization.Policy{Name: "synthetic", Profile: "owner", AdAccountID: "123", PromotedObjectID: "456", CampaignIDs: []string{"100"}, Mode: "active", TargetInstallCPA: &appleads.Money{Amount: "10.00", Currency: "USD"}, MaxTotalDailyBudget: appleads.Money{Amount: "100.00", Currency: "USD"}, MaxCampaignDailyBudget: appleads.Money{Amount: "50.00", Currency: "USD"}, MaxBid: &appleads.Money{Amount: "5.00", Currency: "USD"}, Permissions: optimization.Permissions{Bid: true}, Preset: "balanced"} + if err := optimization.SavePolicies(policyPath, optimization.PolicyFile{Policies: []optimization.Policy{policy}}); err != nil { + t.Fatal(err) + } + manager := &optimizerReportDriftManager{receiptScopeManager: &receiptScopeManager{campaignStatus: "ENABLED", now: now}} + service := &Service{manager: manager, allowWrites: true, policyPath: policyPath, historyRoot: filepath.Join(root, "history"), now: func() time.Time { return now }} + _, output, err := service.optimizationPlanPreview(operations.NewStore())(t.Context(), nil, OptimizationPolicyInput{AccountInput: AccountInput{Profile: "owner", AdAccountID: "123"}, Policy: "synthetic"}) + if err != nil || output.Preview != nil || output.Error == nil || !strings.Contains(output.Error.Message, "drift") || manager.reportReads != 2 || manager.writes.Load() != 0 { + t.Fatalf("output=%+v reads=%d writes=%d err=%v", output, manager.reportReads, manager.writes.Load(), err) + } +} + +func TestOptimizerCaptureBindsEveryReportPage(t *testing.T) { + policy := optimization.Policy{Profile: "synthetic", AdAccountID: "123", MaxTotalDailyBudget: appleads.Money{Currency: "USD"}} + start, end := time.Date(2026, 8, 1, 0, 0, 0, 0, time.UTC), time.Date(2026, 8, 28, 0, 0, 0, 0, time.UTC) + page := func(offset, count int) appleads.Result { + rows := make([]any, count) + for i := range rows { + rows[i] = map[string]any{"metadata": map[string]any{"id": fmt.Sprint(offset + i + 1), "status": "ENABLED"}, "granularMetrics": []any{}} + } + return appleads.Result{Data: rows, Pagination: appleads.Pagination{Offset: offset, PageSize: MaxItems, Total: MaxItems + 1}} + } + first, last := page(0, MaxItems), page(MaxItems, 1) + first.Pagination.Next = "next-page" + changed := page(MaxItems, 1) + changed.Data.([]any)[0].(map[string]any)["metadata"].(map[string]any)["status"] = "PAUSED" + manager := &v036Manager{responses: map[string][]appleads.Result{"reports/apps/adgroups/query": {first, last, first, changed}}} + capture := &optimizationEvidenceCapture{appleAdsManager: manager} + service := &Service{manager: capture} + items, err := service.optimizationBiddables(t.Context(), policy, "adgroups", "100", start, end) + if err != nil || len(items) != MaxItems+1 || len(capture.reads) != 2 { + t.Fatalf("items=%d reads=%d err=%v", len(items), len(capture.reads), err) + } + write, _ := appleads.ResourceUpdate("campaigns", "100", map[string]any{"status": "PAUSED"}) + _, err = operations.NewStore().PreviewComposite(t.Context(), manager, "synthetic", "123", "synthetic", []string{"100"}, map[string]any{"status": "PAUSED"}, capture.reads, write, operations.PreviewOptions{}) + if !errors.Is(err, operations.ErrStateDrift) { + t.Fatalf("second-page drift must be bound: %v", err) + } +} diff --git a/internal/tools/errors.go b/internal/tools/errors.go index 3101fef..831d305 100644 --- a/internal/tools/errors.go +++ b/internal/tools/errors.go @@ -57,12 +57,33 @@ func classifyError(err error) (output ErrorOutput) { } } + var rateError *appleads.RateLimitError + if errors.As(err, &rateError) { + hint := "honor the rate-limit delay; retry reads only, and create a fresh preview before any newly authorized write" + if rateError.Code == "RATE_LIMIT_TIMING_INVALID" { + hint = "inspect the upstream rate-limit timing; restart this server only after timing is verified; do not resubmit a write" + } + return ErrorOutput{ + Type: "rate_limit_error", Message: rateError.Error(), Code: rateError.Code, + Retryable: !rateError.Mutation && rateError.Cause == nil && rateError.Code != "RATE_LIMIT_TIMING_INVALID", + Details: map[string]any{"rateLimit": rateError.RateLimit, "nextRequestSent": false}, + Hint: hint, + } + } + var apiError *appleads.APIError if errors.As(err, &apiError) { + details := make(map[string]any, len(apiError.Details)+1) + for key, value := range apiError.Details { + details[key] = value + } + if rate := apiError.RateLimit; rate.Limit != "" || rate.Remaining != "" || rate.Reset != "" || rate.RetryAfter != 0 { + details["rateLimit"] = rate + } return ErrorOutput{ Type: "apple_api_error", Message: apiError.Message, HTTPStatus: apiError.HTTPStatus, Code: apiError.Code, ResponseFormat: apiError.ResponseFormat, Retryable: apiError.Retryable, - Details: apiError.Details, AppleBody: apiError.Body, Hint: appleAPIHint(apiError), + Details: details, AppleBody: apiError.Body, Hint: appleAPIHint(apiError), } } diff --git a/internal/tools/mutation_models.go b/internal/tools/mutation_models.go index 96058d3..906f87c 100644 --- a/internal/tools/mutation_models.go +++ b/internal/tools/mutation_models.go @@ -27,7 +27,7 @@ type CampaignTargeting struct { type BidStrategy struct { BidStrategyType string `json:"bidStrategyType,omitempty" jsonschema:"Apple bid strategy type"` BidStrategyGoal string `json:"bidStrategyGoal,omitempty" jsonschema:"Apple bid strategy goal"` - Bid *appleads.Money `json:"bid,omitempty" jsonschema:"manual bid amount and account currency"` + Bid *appleads.Money `json:"bid,omitempty" jsonschema:"bid or automated ceiling in account currency; auto-bidding ad group updates require zero"` } type CPAGoal struct { @@ -49,7 +49,7 @@ type CampaignCreatePayload struct { Status string `json:"status" jsonschema:"campaign status"` DailyBudget MoneyValue `json:"dailyBudget" jsonschema:"daily budget value in account currency"` Targeting CampaignTargeting `json:"targeting" jsonschema:"App Store placement and countries"` - BidStrategy *BidStrategy `json:"bidStrategy,omitempty" jsonschema:"optional campaign bid strategy"` + BidStrategy *BidStrategy `json:"bidStrategy" jsonschema:"required type and goal pair; manual strategies require a positive bid"` } type CampaignUpdatePayload struct { @@ -127,7 +127,7 @@ type AdGroupCreatePayload struct { Status string `json:"status"` AutomatedKeywordsRequired *bool `json:"automatedKeywordsRequired,omitempty"` BidStrategy *BidStrategy `json:"bidStrategy,omitempty"` - CPACap *CPAGoal `json:"cpaCap,omitempty"` + CPACap *CPAGoal `json:"cpaCap,omitempty" jsonschema:"Deprecated by Apple; retained for compatibility without automatic strategy conversion"` Targeting *AdGroupTargeting `json:"targeting,omitempty"` } @@ -139,7 +139,7 @@ type AdGroupUpdatePayload struct { Status *string `json:"status,omitempty"` AutomatedKeywordsRequired *bool `json:"automatedKeywordsRequired,omitempty"` BidStrategy *BidStrategy `json:"bidStrategy,omitempty"` - CPACap *CPAGoal `json:"cpaCap,omitempty"` + CPACap *CPAGoal `json:"cpaCap,omitempty" jsonschema:"Deprecated by Apple; retained for compatibility without automatic strategy conversion"` Targeting *AdGroupTargeting `json:"targeting,omitempty"` } diff --git a/internal/tools/mutation_schema.go b/internal/tools/mutation_schema.go new file mode 100644 index 0000000..a5ae7e4 --- /dev/null +++ b/internal/tools/mutation_schema.go @@ -0,0 +1,119 @@ +package tools + +import ( + "fmt" + "math" + "slices" + + "github.com/google/jsonschema-go/jsonschema" +) + +const positiveBidAmountPattern = `^(0\.0*[1-9][0-9]*|[1-9][0-9]*(\.[0-9]+)?)$` + +func mutationInputSchema[In any](toolName string) *jsonschema.Schema { + schema, err := jsonschema.For[In](nil) + if err != nil { + panic(fmt.Sprintf("infer input schema for %s: %v", toolName, err)) + } + applyMutationSchemaConstraints(schema, "", false) + if toolName == "campaign_create_preview" { + payload := schema.Properties["payload"] + if !slices.Contains(payload.Required, "bidStrategy") { + payload.Required = append(payload.Required, "bidStrategy") + } + } + if toolName == "campaign_create_preview" || toolName == "ad_group_create_preview" { + strategy := schema.Properties["payload"].Properties["bidStrategy"] + strategy.Required = []string{"bidStrategyType", "bidStrategyGoal"} + strategy.AllOf = append(strategy.AllOf, &jsonschema.Schema{ + If: &jsonschema.Schema{Properties: map[string]*jsonschema.Schema{ + "bidStrategyType": {Enum: []any{"MANUAL_CPT"}}, + }}, + Then: &jsonschema.Schema{Required: []string{"bid"}}, + }) + } + if toolName == "ad_group_bid_preview" { + if amount := schema.Properties["amount"]; amount != nil { + amount.Pattern = positiveBidAmountPattern + } + } + return schema +} + +func applyMutationSchemaConstraints(schema *jsonschema.Schema, parentName string, inStrategy bool) { + if schema == nil { + return + } + inStrategy = inStrategy || parentName == "bidStrategy" || parentName == "strategy" + for name, property := range schema.Properties { + switch name { + case "status": + property.Enum = []any{"ENABLED", "PAUSED"} + case "correlationId": + description := property.Description + *property = jsonschema.Schema{ + Description: description, + OneOf: []*jsonschema.Schema{ + {Type: "integer", Minimum: jsonschema.Ptr(0.0), ExclusiveMaximum: jsonschema.Ptr(math.Exp2(63))}, + {Type: "string", MinLength: jsonschema.Ptr(1), Pattern: `^[0-9]+$`}, + }, + } + case "cpaCap": + property.Deprecated = true + case "amount": + if parentName == "bid" { + property.Pattern = positiveBidAmountPattern + if inStrategy { + property.Pattern = `^(0|[1-9][0-9]*)(\.[0-9]+)?$` + } + } + } + applyMutationSchemaConstraints(property, name, inStrategy) + } + applyMutationSchemaConstraints(schema.Items, parentName, inStrategy) + applyMutationSchemaConstraints(schema.AdditionalItems, parentName, inStrategy) + applyMutationSchemaConstraints(schema.Contains, parentName, inStrategy) + applyMutationSchemaConstraints(schema.AdditionalProperties, parentName, inStrategy) + applyMutationSchemaConstraints(schema.PropertyNames, parentName, inStrategy) + applyMutationSchemaConstraints(schema.UnevaluatedItems, parentName, inStrategy) + applyMutationSchemaConstraints(schema.UnevaluatedProperties, parentName, inStrategy) + applyMutationSchemaConstraints(schema.Not, parentName, inStrategy) + applyMutationSchemaConstraints(schema.If, parentName, inStrategy) + applyMutationSchemaConstraints(schema.Then, parentName, inStrategy) + applyMutationSchemaConstraints(schema.Else, parentName, inStrategy) + applyMutationSchemaConstraints(schema.ContentSchema, parentName, inStrategy) + for _, collection := range [][]*jsonschema.Schema{schema.PrefixItems, schema.ItemsArray, schema.AllOf, schema.AnyOf, schema.OneOf} { + for _, item := range collection { + applyMutationSchemaConstraints(item, parentName, inStrategy) + } + } + for _, collection := range []map[string]*jsonschema.Schema{ + schema.Defs, + schema.Definitions, + schema.DependencySchemas, + schema.DependentSchemas, + schema.PatternProperties, + } { + for _, item := range collection { + applyMutationSchemaConstraints(item, parentName, inStrategy) + } + } + if (parentName == "bidStrategy" || parentName == "strategy") && schema.Properties["bidStrategyType"] != nil && schema.Properties["bidStrategyGoal"] != nil { + schema.Properties["bidStrategyType"].Enum = []any{"MANUAL_CPT", "MAX_CONVERSIONS"} + schema.Properties["bidStrategyGoal"].Enum = []any{"TAP", "INSTALL"} + schema.DependentRequired = map[string][]string{ + "bidStrategyType": {"bidStrategyGoal"}, + "bidStrategyGoal": {"bidStrategyType"}, + } + for _, pair := range [][2]string{{"MANUAL_CPT", "TAP"}, {"MAX_CONVERSIONS", "INSTALL"}} { + schema.AllOf = append(schema.AllOf, &jsonschema.Schema{ + If: &jsonschema.Schema{Required: []string{"bidStrategyType"}, Properties: map[string]*jsonschema.Schema{ + "bidStrategyType": {Enum: []any{pair[0]}}, + }}, + Then: &jsonschema.Schema{Properties: map[string]*jsonschema.Schema{ + "bidStrategyGoal": {Enum: []any{pair[1]}}, + }}, + }) + } + } +} diff --git a/internal/tools/mutation_validation.go b/internal/tools/mutation_validation.go index 01aa960..3f07c51 100644 --- a/internal/tools/mutation_validation.go +++ b/internal/tools/mutation_validation.go @@ -1,6 +1,7 @@ package tools import ( + "context" "encoding/json" "errors" "fmt" @@ -10,6 +11,7 @@ import ( "time" "github.com/zelentsov-dev/apple-ads-mcp/internal/appleads" + "github.com/zelentsov-dev/apple-ads-mcp/internal/operations" ) var decimalIDPattern = regexp.MustCompile(`^[1-9][0-9]*$`) @@ -100,6 +102,9 @@ func validateCampaignPayload(payload map[string]any, create bool) error { } else if create { return errors.New("campaign targeting is required") } + if err := validateBidStrategyForOperation(payload["bidStrategy"], create, create); err != nil { + return err + } return validateSchedule(payload) } @@ -166,7 +171,7 @@ func validateAdGroupPayload(payload map[string]any, create bool) error { if status := stringField(payload, "status"); status != "" && !allowedStatus(status) { return fmt.Errorf("unsupported ad group status %q", status) } - if err := validateBidStrategy(payload["bidStrategy"]); err != nil { + if err := validateBidStrategyForOperation(payload["bidStrategy"], create, false); err != nil { return err } if err := validateCPAGoal(payload["cpaCap"]); err != nil { @@ -330,20 +335,55 @@ func parseISOTimestamp(value string) (time.Time, error) { } func validateBidStrategy(value any) error { - strategy, ok := value.(map[string]any) - if !ok { + return validateBidStrategyForOperation(value, false, false) +} + +func validateBidStrategyForOperation(value any, create, required bool) error { + if value == nil { + if required { + return errors.New("campaign creation requires bidStrategy") + } return nil } - strategyType := strings.ToUpper(stringField(strategy, "bidStrategyType")) - if strategyType != "" && strategyType != "MANUAL_CPT" && strategyType != "MAX_CONVERSIONS" { - return fmt.Errorf("bidStrategyType %q is outside App Store Ads scope", strategyType) + strategy, ok := value.(map[string]any) + if !ok || len(strategy) == 0 { + return errors.New("bidStrategy must be a nonempty object") } - if strategyType == "MAX_CONVERSIONS" { - if _, exists := strategy["bid"]; exists { - return errors.New("MAX_CONVERSIONS must not include a manual bid") + strategyType := stringField(strategy, "bidStrategyType") + goal := stringField(strategy, "bidStrategyGoal") + _, hasType := strategy["bidStrategyType"] + _, hasGoal := strategy["bidStrategyGoal"] + if hasType || hasGoal || create { + if strategyType != "MANUAL_CPT" && strategyType != "MAX_CONVERSIONS" { + return errors.New("bidStrategyType must be MANUAL_CPT or MAX_CONVERSIONS") + } + expected := "TAP" + if strategyType == "MAX_CONVERSIONS" { + expected = "INSTALL" } + if goal != expected { + return fmt.Errorf("%s requires bidStrategyGoal %s; send type and goal together", strategyType, expected) + } + } + _, hasBid := strategy["bid"] + if create && strategyType == "MANUAL_CPT" && !hasBid { + return errors.New("MANUAL_CPT creation requires a positive bid") } - return validateOptionalMoneyFields(strategy, "bid") + if strategyType == "" && !hasBid { + return errors.New("bidStrategy update requires a type and goal pair or a bid") + } + if hasBid { + if err := validateMoneyField(strategy, "bid", create || strategyType != "MAX_CONVERSIONS"); err != nil { + return err + } + bid := strategy["bid"].(map[string]any) + amount, ok := new(big.Rat).SetString(stringField(bid, "amount")) + if !ok || amount.Sign() < 0 { + return errors.New("bid must not be negative") + } + return nil + } + return nil } func validateCPAGoal(value any) error { @@ -437,3 +477,200 @@ func stringSlice(value any) []string { return nil } } + +func (s *Service) bidStrategyEvidence(ctx context.Context, account AccountInput, resource, id string, payload map[string]any, create bool) ([]operations.VerificationRead, []operations.OperationWarning, error) { + warnings := mutationWarnings(payload) + if resource != "campaigns" && resource != "adgroups" { + return nil, warnings, nil + } + reads := make([]operations.VerificationRead, 0, 3) + readObject := func(name, kind, objectID string) (map[string]any, error) { + op, err := appleads.ResourceGet(kind, objectID) + if err != nil { + return nil, err + } + result, err := s.manager.Do(ctx, account.Profile, account.AdAccountID, op) + if err != nil { + return nil, err + } + object, ok := result.Data.(map[string]any) + if !ok { + return nil, fmt.Errorf("%s strategy evidence must be an object", kind) + } + reads = append(reads, operations.VerificationRead{Name: name, Operation: op, Expected: cloneObject(object), Scopes: []string{operations.ObjectMutationScope(objectID)}}) + return object, nil + } + currencies := collectFieldValues(payload, "currency", MaxItems) + if len(currencies) > 0 { + op, err := appleads.AdAccount(account.AdAccountID) + if err != nil { + return nil, nil, err + } + result, err := s.manager.Do(ctx, account.Profile, account.AdAccountID, op) + if err != nil { + return nil, nil, err + } + accountObject, ok := result.Data.(map[string]any) + if !ok { + return nil, nil, errors.New("account currency evidence must be an object") + } + currency := strings.ToUpper(stringField(accountObject, "currency")) + if currency == "" { + return nil, nil, errors.New("account currency is unavailable") + } + for _, value := range currencies { + if !strings.EqualFold(value, currency) { + return nil, nil, errors.New("bid and budget currencies must match the ad account") + } + } + reads = append(reads, operations.VerificationRead{Name: "strategy_account", Operation: op, Expected: map[string]any{"currency": accountObject["currency"]}, Fields: []string{"currency"}}) + } + strategy, hasStrategy := payload["bidStrategy"].(map[string]any) + if resource == "campaigns" { + _, hasTargeting := payload["targeting"] + if !hasStrategy && !hasTargeting { + return reads, warnings, nil + } + campaign := payload + if !create { + var err error + campaign, err = readObject("strategy_campaign", "campaigns", id) + if err != nil { + return nil, nil, err + } + } + proposedCampaign := cloneObject(campaign) + if targeting, ok := payload["targeting"].(map[string]any); ok { + proposedTargeting := cloneObject(findMapField(campaign, "targeting")) + if proposedTargeting == nil { + proposedTargeting = map[string]any{} + } + for key, value := range targeting { + proposedTargeting[key] = value + } + proposedCampaign["targeting"] = proposedTargeting + } + if err := validateCampaignStrategyContext(proposedCampaign, strategy); err != nil { + return nil, nil, err + } + return reads, warnings, nil + } + if !create && !hasStrategy { + return reads, warnings, nil + } + adGroup := payload + if !create { + var err error + adGroup, err = readObject("strategy_adgroup", "adgroups", id) + if err != nil { + return nil, nil, err + } + } + campaignID := stringField(adGroup, "campaignId") + if !decimalIDPattern.MatchString(campaignID) { + return nil, nil, errors.New("ad group strategy requires a confirmed parent campaign") + } + campaign, err := readObject("strategy_parent_campaign", "campaigns", campaignID) + if err != nil { + return nil, nil, err + } + if err := validateAdGroupStrategyContext(campaign, adGroup, strategy, create); err != nil { + return nil, nil, err + } + return reads, warnings, nil +} + +func mutationWarnings(payload map[string]any) []operations.OperationWarning { + warnings := make([]operations.OperationWarning, 0, 3) + if _, exists := payload["cpaCap"]; exists { + warnings = append(warnings, operations.OperationWarning{Code: "CPA_CAP_DEPRECATED", Message: "Apple has deprecated cpaCap. This preview preserves the legacy field and does not convert the campaign strategy."}) + } + strategy, _ := payload["bidStrategy"].(map[string]any) + if stringField(strategy, "bidStrategyType") == "MAX_CONVERSIONS" { + warnings = append(warnings, + operations.OperationWarning{Code: "MAX_CONVERSIONS_HISTORY_UNCONFIRMED", Message: "This explicit strategy request does not verify the optimizer's minimum of 14 completed days and 70 tap installs. Allow at least two weeks to assess learning after the change."}, + operations.OperationWarning{Code: "MAX_CONVERSIONS_BUDGET_GUIDANCE", Message: "Apple recommends a daily budget sufficient for approximately five conversions. This guidance is not an eligibility requirement."}, + ) + } + return warnings +} + +func effectiveBidStrategy(current, requested map[string]any) (map[string]any, error) { + strategy := cloneObject(current) + if strategy == nil { + strategy = map[string]any{} + } + for key, value := range requested { + strategy[key] = value + } + if stringField(strategy, "bidStrategyType") == "" || stringField(strategy, "bidStrategyGoal") == "" { + return nil, errors.New("current bid strategy type and goal are required for a partial update") + } + if err := validateBidStrategy(strategy); err != nil { + return nil, err + } + return strategy, nil +} + +func validateCampaignStrategyContext(campaign, requested map[string]any) error { + if stringField(campaign, "promotedObjectType") != "APPSTORE_APP" { + return errors.New("bid strategies require an APPSTORE_APP campaign") + } + current, _ := campaign["bidStrategy"].(map[string]any) + strategy, err := effectiveBidStrategy(current, requested) + if err != nil { + return err + } + if stringField(campaign, "billingEvent") != "TAPS" { + return errors.New("App Store bid strategies require campaign billingEvent TAPS") + } + targeting, _ := campaign["targeting"].(map[string]any) + placement, _ := targeting["supplyPlacement"].(map[string]any) + placements := stringSlice(placement["include"]) + if len(placements) != 1 { + return errors.New("bid strategy requires exactly one confirmed App Store placement") + } + switch placements[0] { + case "APPSTORE_SEARCH_RESULTS", "APPSTORE_SEARCH_TAB", "APPSTORE_TODAY_TAB", "APPSTORE_PRODUCT_PAGES": + default: + return errors.New("bid strategy placement is outside App Store scope") + } + if stringField(strategy, "bidStrategyType") == "MAX_CONVERSIONS" && placements[0] != "APPSTORE_SEARCH_RESULTS" { + return errors.New("MAX_CONVERSIONS requires APPSTORE_SEARCH_RESULTS") + } + return nil +} + +func validateAdGroupStrategyContext(campaign, adGroup, requested map[string]any, create bool) error { + parent, _ := campaign["bidStrategy"].(map[string]any) + if err := validateCampaignStrategyContext(campaign, parent); err != nil { + return err + } + if stringField(adGroup, "pricingModel") != "CPT" { + return errors.New("App Store ad group strategies require pricingModel CPT") + } + current, _ := adGroup["bidStrategy"].(map[string]any) + if current == nil || create { + current = parent + } + strategy, err := effectiveBidStrategy(current, requested) + if err != nil { + return err + } + if stringField(strategy, "bidStrategyType") != stringField(parent, "bidStrategyType") || stringField(strategy, "bidStrategyGoal") != stringField(parent, "bidStrategyGoal") { + return errors.New("ad group bid strategy must match the parent campaign type and goal") + } + if !create && stringField(parent, "bidStrategyType") == "MAX_CONVERSIONS" && requested != nil { + if stringField(requested, "bidStrategyType") != "MAX_CONVERSIONS" || stringField(requested, "bidStrategyGoal") != "INSTALL" { + return errors.New("automated ad group updates must echo the parent MAX_CONVERSIONS and INSTALL pair") + } + if _, exists := requested["bid"]; exists { + bid, _ := requested["bid"].(map[string]any) + amount, ok := new(big.Rat).SetString(stringField(bid, "amount")) + if !ok || amount.Sign() != 0 { + return errors.New("automated ad group updates may only echo a zero bid") + } + } + } + return nil +} diff --git a/internal/tools/mutations.go b/internal/tools/mutations.go index 5a64c7f..60e4a53 100644 --- a/internal/tools/mutations.go +++ b/internal/tools/mutations.go @@ -62,7 +62,7 @@ func MutationSpecs() []Spec { {Name: "ad_group_search_match_preview", Description: "Preview enabling or disabling Apple Search Match for a Search Results ad group.", Class: "mutation_preview"}, {Name: "ad_group_targeting_preview", Description: "Preview App Store-only ad-group targeting.", Class: "mutation_preview"}, {Name: "ad_group_bid_preview", Description: "Preview an ad-group default bid update with decimal amount and currency.", Class: "mutation_preview"}, - {Name: "ad_group_cpa_cap_preview", Description: "Preview an ad-group CPA cap update with decimal amount and currency.", Class: "mutation_preview"}, + {Name: "ad_group_cpa_cap_preview", Description: "Deprecated by Apple: preview a legacy ad-group CPA cap update; retained for compatibility without automatic strategy conversion.", Class: "mutation_preview"}, {Name: "keyword_create_preview", Description: "Preview creation of one targeting keyword.", Class: "mutation_preview"}, {Name: "keyword_update_preview", Description: "Preview a targeting keyword update.", Class: "mutation_preview"}, {Name: "keyword_bid_preview", Description: "Preview a targeting keyword bid update.", Class: "mutation_preview"}, @@ -267,7 +267,12 @@ func (s *Service) createPreviewPayload(ctx context.Context, store *operations.St if err != nil { return failedPreview(err) } - preview, err := store.PreviewComposite(ctx, s.manager, account.Profile, account.AdAccountID, name, nil, payload, []operations.VerificationRead{{Name: "affected_inventory", Operation: verify, Scopes: resourceMutationScopes(resource, impact, payload, true)}}, mutation, operations.PreviewOptions{Impact: impact, Create: &operations.CreateExpectation{Resource: resource, Expected: payload}}) + evidence, warnings, err := s.bidStrategyEvidence(ctx, account, resource, "", payload, true) + if err != nil { + return failedPreview(err) + } + reads := append([]operations.VerificationRead{{Name: "affected_inventory", Operation: verify, Scopes: resourceMutationScopes(resource, impact, payload, true)}}, evidence...) + preview, err := store.PreviewComposite(ctx, s.manager, account.Profile, account.AdAccountID, name, nil, payload, reads, mutation, operations.PreviewOptions{Impact: impact, Warnings: warnings, Create: &operations.CreateExpectation{Resource: resource, Expected: payload}}) if err != nil { return failedPreview(err) } @@ -336,7 +341,12 @@ func (s *Service) updatePreviewPayloadWithScopes(ctx context.Context, store *ope } scopes := resourceMutationScopes(resource, impact, payload, false) scopes = append(scopes, extraScopes...) - preview, err := store.PreviewComposite(ctx, s.manager, account.Profile, account.AdAccountID, name, []string{id}, payload, []operations.VerificationRead{{Name: "current", Operation: verify, Scopes: scopes}}, mutation, operations.PreviewOptions{Impact: impact}) + evidence, warnings, err := s.bidStrategyEvidence(ctx, account, resource, id, payload, false) + if err != nil { + return failedPreview(err) + } + reads := append([]operations.VerificationRead{{Name: "current", Operation: verify, Scopes: scopes}}, evidence...) + preview, err := store.PreviewComposite(ctx, s.manager, account.Profile, account.AdAccountID, name, []string{id}, payload, reads, mutation, operations.PreviewOptions{Impact: impact, Warnings: warnings}) if err != nil { return failedPreview(err) } @@ -1162,7 +1172,7 @@ func addPreviewTool[In any](server *mcp.Server, item Spec, handler mcp.ToolHandl destructive := false open := true mcp.AddTool(server, &mcp.Tool{ - Name: item.Name, Description: item.Description, + Name: item.Name, Description: item.Description, InputSchema: mutationInputSchema[In](item.Name), Annotations: &mcp.ToolAnnotations{Title: strings.ReplaceAll(item.Name, "_", " "), ReadOnlyHint: true, IdempotentHint: true, DestructiveHint: &destructive, OpenWorldHint: &open}, }, handler) } diff --git a/internal/tools/mutations_test.go b/internal/tools/mutations_test.go index c641ed9..6bd6556 100644 --- a/internal/tools/mutations_test.go +++ b/internal/tools/mutations_test.go @@ -29,6 +29,7 @@ func TestTypedCampaignAndCreativeValidation(t *testing.T) { campaign := map[string]any{ "name": "Fixture", "billingEvent": "TAPS", "promotedObjectType": "APPSTORE_APP", "promotedObjectId": "1234567890", "status": "PAUSED", "dailyBudget": map[string]any{"value": map[string]any{"amount": "10.00", "currency": "USD"}}, + "bidStrategy": map[string]any{"bidStrategyType": "MANUAL_CPT", "bidStrategyGoal": "TAP", "bid": map[string]any{"amount": "1.00", "currency": "USD"}}, "targeting": map[string]any{ "supplySource": map[string]any{"include": []any{"APPSTORE"}}, "supplyPlacement": map[string]any{"include": []any{"APPSTORE_SEARCH_RESULTS"}}, @@ -181,10 +182,10 @@ func TestAppStoreBidStrategyValidation(t *testing.T) { t.Fatalf("expected strategy rejection: %#v", strategy) } } - if err := validateBidStrategy(map[string]any{"bidStrategyType": "MANUAL_CPT", "bid": map[string]any{"amount": "1.00", "currency": "USD"}}); err != nil { + if err := validateBidStrategy(map[string]any{"bidStrategyType": "MANUAL_CPT", "bidStrategyGoal": "TAP", "bid": map[string]any{"amount": "1.00", "currency": "USD"}}); err != nil { t.Fatal(err) } - if err := validateBidStrategy(map[string]any{"bidStrategyType": "MAX_CONVERSIONS"}); err != nil { + if err := validateBidStrategy(map[string]any{"bidStrategyType": "MAX_CONVERSIONS", "bidStrategyGoal": "INSTALL"}); err != nil { t.Fatal(err) } } diff --git a/internal/tools/optimization_tools.go b/internal/tools/optimization_tools.go index 0a975aa..f354c96 100644 --- a/internal/tools/optimization_tools.go +++ b/internal/tools/optimization_tools.go @@ -1,7 +1,9 @@ package tools import ( + "bytes" "context" + "encoding/json" "errors" "fmt" "math/big" @@ -11,6 +13,7 @@ import ( "github.com/modelcontextprotocol/go-sdk/mcp" "github.com/zelentsov-dev/apple-ads-mcp/internal/appleads" + "github.com/zelentsov-dev/apple-ads-mcp/internal/operations" "github.com/zelentsov-dev/apple-ads-mcp/internal/optimization" ) @@ -260,21 +263,30 @@ func (s *Service) attachOptimizationRecommendations(ctx context.Context, policy } func campaignEvidenceFromObject(campaignID string, value any) optimization.CampaignEvidence { - budget := findMapField(value, "dailyBudget") - if nested := findMapField(budget, "value"); nested != nil { + object, _ := value.(map[string]any) + budget, _ := object["dailyBudget"].(map[string]any) + if nested, ok := budget["value"].(map[string]any); ok { budget = nested } - strategy := findMapField(value, "bidStrategy") + strategy, _ := object["bidStrategy"].(map[string]any) + targeting, _ := object["targeting"].(map[string]any) + placementData, _ := targeting["supplyPlacement"].(map[string]any) + placements := stringSlice(placementData["include"]) + placement := "" + if len(placements) == 1 { + placement = placements[0] + } + eligible := validateCampaignStrategyContext(object, map[string]any{"bidStrategyType": "MAX_CONVERSIONS", "bidStrategyGoal": "INSTALL"}) == nil return optimization.CampaignEvidence{ CampaignID: campaignID, - Name: findStringField(value, "name"), - Status: strings.ToUpper(findStringField(value, "status")), - SystemStatus: strings.ToUpper(findStringField(value, "systemStatus")), - Placement: strings.ToUpper(firstNonEmptyTool(findStringField(value, "supplyPlacement"), findStringField(value, "adChannelType"))), - BidStrategy: strings.ToUpper(firstNonEmptyTool(findStringField(strategy, "bidStrategyType"), findStringField(value, "bidStrategyType"))), - DailyBudget: appleads.Money{Amount: findStringField(budget, "amount"), Currency: strings.ToUpper(findStringField(budget, "currency"))}, - MaxConversionsEligible: containsStringValue(value, "MAX_CONVERSIONS") || containsTrueField(value, "maxConversionsEligible"), - ModificationTime: findStringField(value, "modificationTime"), + Name: stringField(object, "name"), + Status: strings.ToUpper(stringField(object, "status")), + SystemStatus: strings.ToUpper(stringField(object, "systemStatus")), + Placement: placement, + BidStrategy: stringField(strategy, "bidStrategyType"), + DailyBudget: appleads.Money{Amount: stringField(budget, "amount"), Currency: strings.ToUpper(stringField(budget, "currency"))}, + MaxConversionsEligible: eligible, + ModificationTime: stringField(object, "modificationTime"), } } @@ -562,3 +574,42 @@ func publicErrorMessage(err error) string { } return "request failed" } + +type optimizationEvidenceCapture struct { + appleAdsManager + reads []operations.VerificationRead + err error +} + +func (capture *optimizationEvidenceCapture) Do(ctx context.Context, profile, account string, operation appleads.Operation) (appleads.Result, error) { + if operation.IsMutation() { + return appleads.Result{}, errors.New("optimization evidence must be read-only") + } + if len(capture.reads) >= 400 { + capture.err = errors.New("optimization evidence exceeds the bounded read count") + return appleads.Result{}, capture.err + } + result, err := capture.appleAdsManager.Do(ctx, profile, account, operation) + if err != nil { + return result, err + } + data, err := json.Marshal(result.Data) + if err != nil { + capture.err = err + return appleads.Result{}, err + } + var expected any + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.UseNumber() + if err := decoder.Decode(&expected); err != nil { + capture.err = err + return appleads.Result{}, err + } + pagination := result.Pagination + read := operations.VerificationRead{Name: fmt.Sprintf("optimizer_evidence_%03d", len(capture.reads)), Operation: operation, Expected: expected, ExpectedPagination: &pagination} + if strings.HasPrefix(operation.Path(), "campaigns/") && !strings.HasSuffix(operation.Path(), "/query") { + read.Scopes = []string{operations.ObjectMutationScope(strings.TrimPrefix(operation.Path(), "campaigns/"))} + } + capture.reads = append(capture.reads, read) + return result, nil +} diff --git a/internal/tools/optimization_tools_test.go b/internal/tools/optimization_tools_test.go index 83f4e72..06f4b61 100644 --- a/internal/tools/optimization_tools_test.go +++ b/internal/tools/optimization_tools_test.go @@ -137,3 +137,11 @@ func reportMetricFixtures(days int) []any { } return result } + +func TestDailyOptimizerRejectsHourlyAndMalformedDatesEvenForEmptyMetrics(t *testing.T) { + for _, date := range []any{"2026-08-24T01:00:00Z", "2026-08-24 01:00", "2026-02-30", "2026-8-24", "", nil, 20260824} { + if _, err := granularDailyMetrics(map[string]any{"granularMetrics": []any{map[string]any{"date": date}}}, "USD"); err == nil { + t.Fatalf("date %v must not become empty zero metrics", date) + } + } +} diff --git a/internal/tools/rate_errors_test.go b/internal/tools/rate_errors_test.go new file mode 100644 index 0000000..8f5837c --- /dev/null +++ b/internal/tools/rate_errors_test.go @@ -0,0 +1,90 @@ +package tools + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "strings" + "testing" + "time" + + "github.com/zelentsov-dev/apple-ads-mcp/internal/appleads" + "github.com/zelentsov-dev/apple-ads-mcp/internal/operations" +) + +func TestRateLimitErrorClassification(t *testing.T) { + for _, test := range []struct { + name string + err error + kind string + retryable bool + }{ + {"read wait budget", &appleads.RateLimitError{Code: "RATE_LIMIT_WAIT_EXCEEDED", RateLimit: appleads.RateLimit{RetryAfter: 37}}, "rate_limit_error", true}, + {"write cooldown", &appleads.RateLimitError{Code: "RATE_LIMIT_COOLDOWN", RateLimit: appleads.RateLimit{RetryAfter: 37}, Mutation: true}, "rate_limit_error", false}, + {"invalid timing", &appleads.RateLimitError{Code: "RATE_LIMIT_TIMING_INVALID"}, "rate_limit_error", false}, + {"canceled read", &appleads.RateLimitError{Code: "RATE_LIMIT_WAIT_CANCELED", Cause: context.Canceled}, "rate_limit_error", false}, + {"ambiguous takes precedence", &appleads.AmbiguousWriteError{Cause: &appleads.APIError{HTTPStatus: 503, Retryable: true}}, "ambiguous_write", false}, + } { + t.Run(test.name, func(t *testing.T) { + output := classifyError(fmt.Errorf("request: %w", test.err)) + if output.Type != test.kind || output.Retryable != test.retryable { + t.Fatalf("output=%+v", output) + } + if test.kind == "rate_limit_error" { + if output.Details["nextRequestSent"] != false { + t.Fatalf("not-sent diagnostic missing: %+v", output) + } + } + }) + } +} + +func TestAPIErrorPreservesRateMetadataWithoutChangingOriginalDetails(t *testing.T) { + apiErr := &appleads.APIError{HTTPStatus: 429, Message: "Too Many Requests", Details: map[string]any{"code": "LIMIT"}, RateLimit: appleads.RateLimit{Limit: "100", Remaining: "0", Reset: "37", RetryAfter: 37}} + output := classifyError(apiErr) + encoded, err := json.Marshal(output) + if err != nil { + t.Fatal(err) + } + if output.Details["code"] != "LIMIT" || !strings.Contains(string(encoded), `"retryAfterSeconds":37`) { + t.Fatalf("output=%s", encoded) + } + if _, mutated := apiErr.Details["rateLimit"]; mutated { + t.Fatal("classification mutated upstream error details") + } +} + +type rateReceiptExecutor struct { + mutationErr error + writes int + state map[string]any +} + +func (executor *rateReceiptExecutor) Do(_ context.Context, _, _ string, operation appleads.Operation) (appleads.Result, error) { + if operation.IsMutation() { + executor.writes++ + return appleads.Result{}, executor.mutationErr + } + return appleads.Result{Status: 200, Data: executor.state}, nil +} + +func TestRateLimitRejectionConsumesReceiptWithoutAmbiguousOutcome(t *testing.T) { + now := time.Now() + store := operations.NewStoreForTest(func() time.Time { return now }, 10*time.Minute) + executor := &rateReceiptExecutor{mutationErr: &appleads.RateLimitError{Code: "RATE_LIMIT_COOLDOWN", Mutation: true}, state: map[string]any{"status": "PAUSED"}} + read, _ := appleads.ResourceGet("campaigns", "1") + write, _ := appleads.ResourceUpdate("campaigns", "1", map[string]any{"status": "ENABLED"}) + preview, err := store.Preview(context.Background(), executor, "synthetic", "1", "campaign_update", []string{"1"}, map[string]any{"status": "ENABLED"}, read, write) + if err != nil { + t.Fatal(err) + } + receipt, err := store.Apply(context.Background(), executor, preview.Receipt) + var rateErr *appleads.RateLimitError + if !errors.As(err, &rateErr) || receipt.Status == "unknown" || executor.writes != 1 { + t.Fatalf("receipt=%+v error=%v attempts=%d", receipt, err, executor.writes) + } + if _, err := store.Apply(context.Background(), executor, preview.Receipt); !errors.Is(err, operations.ErrReceiptUsed) { + t.Fatalf("receipt could be reused: %v", err) + } +} diff --git a/internal/tools/report_v037_test.go b/internal/tools/report_v037_test.go new file mode 100644 index 0000000..167e0aa --- /dev/null +++ b/internal/tools/report_v037_test.go @@ -0,0 +1,62 @@ +package tools + +import ( + "context" + "reflect" + "strings" + "testing" + + "github.com/zelentsov-dev/apple-ads-mcp/internal/appleads" +) + +func TestReportStorefrontGroupByMigration(t *testing.T) { + for _, kind := range []string{"campaigns", "adgroups", "keywords", "ads", "searchterms"} { + t.Run(kind, func(t *testing.T) { + manager := &v036Manager{} + service := &Service{manager: manager} + _, output, err := service.reportHandler("report", kind)(context.Background(), nil, QueryInput{ + AccountInput: AccountInput{Profile: "test", AdAccountID: "123"}, GroupBy: []string{"storefront"}, + }) + if err != nil || output.Error == nil || !strings.Contains(output.Error.Message, "countryOrRegion") || len(manager.calls) != 0 { + t.Fatalf("output=%+v err=%v calls=%v", output, err, manager.calls) + } + input := QueryInput{GroupBy: []string{"countryOrRegion"}} + request, err := input.reportRequest(kind) + if err != nil || !reflect.DeepEqual(request["groupBy"], input.GroupBy) { + t.Fatalf("request=%v err=%v", request, err) + } + }) + } + for _, kind := range []string{"campaigns", "adgroups"} { + _, err := (QueryInput{Filters: []QueryFilterInput{{Field: "storefront", Operator: "EQUALS", Value: "US"}}}).reportRequest(kind) + if err != nil { + t.Fatalf("metadata storefront must remain available: %v", err) + } + } +} + +func TestGeneralReportsPreserveDateStringsAndEmptyRows(t *testing.T) { + for _, test := range []struct { + name, granularity string + data any + }{ + {"daily", "DAILY", []any{map[string]any{"granularMetrics": []any{map[string]any{"date": "2026-09-01", "tapInstalls": "0"}}}}}, + {"hourly", "HOURLY", []any{map[string]any{"granularMetrics": []any{map[string]any{"date": "2026-09-01T03:00:00.000", "tapInstalls": "1"}}}}}, + {"future_date_format", "HOURLY", []any{map[string]any{"granularMetrics": []any{map[string]any{"date": "2026-09-01T03:00:00Z"}}}}}, + {"empty", "DAILY", []any{}}, + } { + t.Run(test.name, func(t *testing.T) { + manager := &v036Manager{responses: map[string][]appleads.Result{ + "reports/apps/campaigns/query": {{Data: test.data, Status: 200}}, + }} + service := &Service{manager: manager} + _, output, err := service.reportHandler("report", "campaigns")(context.Background(), nil, QueryInput{ + AccountInput: AccountInput{Profile: "test", AdAccountID: "123"}, + TimeRange: &TimeRangeInput{Start: "2026-09-01", End: "2026-09-01", Granularity: test.granularity, TimeZone: "UTC"}, + }) + if err != nil || output.Error != nil || !reflect.DeepEqual(output.Data, test.data) { + t.Fatalf("output=%+v err=%v", output, err) + } + }) + } +} diff --git a/internal/tools/types.go b/internal/tools/types.go index 21936ad..43f3a07 100644 --- a/internal/tools/types.go +++ b/internal/tools/types.go @@ -517,6 +517,11 @@ func (input QueryInput) reportRequest(kind string) (map[string]any, error) { return nil, fmt.Errorf("sorting order %q is not supported", sorting.Order) } } + for _, dimension := range input.GroupBy { + if dimension == "storefront" { + return nil, errors.New("groupBy storefront is not supported; use countryOrRegion for country reporting") + } + } groupBy := reportGroupBy(kind) if err := validateSelectedFields("groupBy", input.GroupBy, groupBy); err != nil { return nil, err @@ -606,7 +611,7 @@ func reportMetadataFields() map[string][]string { func reportGroupBy(kind string) map[string]struct{} { values := []string{"deviceClass", "countryOrRegion"} if kind == "campaigns" || kind == "adgroups" { - values = append(values, "ageRange", "gender", "countryCode", "adminArea", "locality", "storefront") + values = append(values, "ageRange", "gender", "countryCode", "adminArea", "locality") } result := make(map[string]struct{}, len(values)) for _, value := range values { diff --git a/scripts/validate_distribution.py b/scripts/validate_distribution.py index 6944d22..7ec92db 100644 --- a/scripts/validate_distribution.py +++ b/scripts/validate_distribution.py @@ -94,6 +94,9 @@ def main() -> None: require("--allow-deletes" in readme and "APPLE_ADS_ALLOW_DELETES" in readme, "README delete gates missing") require("optimization policy init" in readme and "optimization_plan" in readme, "README optimizer setup missing") require("maxBid" in readme and "reconciliation" in readme.lower(), "README optimizer safety migration missing") + require((ROOT / "docs/MIGRATION-v0.3.7.md").is_file(), "v0.3.7 migration notes missing") + require(" - docs/**" not in goreleaser, "release archives must not include private research documents") + require(" - docs/MIGRATION-*.md" in goreleaser and " - docs/ROADMAP.md" in goreleaser, "public release documentation allowlist missing") require("scripts/audit_upstream.py" in (ROOT / ".github/workflows/upstream-audit.yml").read_text(), "upstream audit script is not scheduled") for source in ROOT.rglob("*.go"): if source.name.endswith("_test.go"): diff --git a/server.json b/server.json index c223310..d9eaa09 100644 --- a/server.json +++ b/server.json @@ -7,11 +7,11 @@ "url": "https://github.com/zelentsov-dev/apple-ads-mcp", "source": "github" }, - "version": "0.3.6", + "version": "0.3.7", "packages": [ { "registryType": "oci", - "identifier": "ghcr.io/zelentsov-dev/apple-ads-mcp:v0.3.6", + "identifier": "ghcr.io/zelentsov-dev/apple-ads-mcp:v0.3.7", "runtimeHint": "docker", "transport": { "type": "stdio" diff --git a/skills/apple-ads-operator/references/tool-routing.md b/skills/apple-ads-operator/references/tool-routing.md index 81d9c69..3c843b8 100644 --- a/skills/apple-ads-operator/references/tool-routing.md +++ b/skills/apple-ads-operator/references/tool-routing.md @@ -64,7 +64,7 @@ Use the most specific preview tool: budget, countries, schedule, targeting, Sear Apply only through `operations_apply`. After apply, call `operations_verify` and the matching get/query tool. After an ambiguous result, verify before any new write; `operations_inspect` only reports receipt metadata. There is no raw API tool. -Use `campaign_bid_strategy_preview` for MANUAL_CPT or an Apple-eligible Search Results `MAX_CONVERSIONS` change. Use typed shared-budget previews only when `ad_account_get` reports `LOC`; MCP input contains a local `billingProfile` name, never billing PII. +Use `campaign_bid_strategy_preview` for `MANUAL_CPT` + `TAP` or Search Results `MAX_CONVERSIONS` + `INSTALL`. Explicit requests show a statistical-readiness warning without requiring optimizer history minimums; optimizer recommendations retain their conservative history thresholds. Inspect persisted preview warnings before applying. `ad_group_cpa_cap_preview` and `cpaCap` are deprecated compatibility surfaces; do not recommend them for new setups or silently convert existing caps. Use typed shared-budget previews only when `ad_account_get` reports `LOC`; MCP input contains a local `billingProfile` name, never billing PII. Delete tools are specialized by resource. Use them only for an explicitly authorized irreversible task after reading the full cascade inventory and exact expected text. Delete is never part of optimization. From 5fad37820a73a0a1d3b6df3bbc3e5dba19e5bc9e Mon Sep 17 00:00:00 2001 From: Aleksei Zelentsov <37956463+zelentsov-dev@users.noreply.github.com> Date: Thu, 15 Oct 2026 20:48:56 +0300 Subject: [PATCH 2/4] Align release example and remove superseded report helpers --- README.md | 2 +- internal/tools/optimization_tools.go | 8 -------- 2 files changed, 1 insertion(+), 9 deletions(-) diff --git a/README.md b/README.md index bc2ca3e..c7b3570 100644 --- a/README.md +++ b/README.md @@ -176,7 +176,7 @@ Windows users should verify `checksums.txt`, extract the matching ZIP, and regis ### OCI image ```bash -docker pull ghcr.io/zelentsov-dev/apple-ads-mcp:0.3.6 +docker pull ghcr.io/zelentsov-dev/apple-ads-mcp:0.3.7 ``` The image runs `serve --stdio` by default. Mount `accounts.json` and its referenced private key read-only. diff --git a/internal/tools/optimization_tools.go b/internal/tools/optimization_tools.go index f354c96..6231036 100644 --- a/internal/tools/optimization_tools.go +++ b/internal/tools/optimization_tools.go @@ -166,10 +166,6 @@ func (s *Service) optimizationReport(ctx context.Context, policy optimization.Po return dailyMetrics(rows, resourceID, policy.MaxTotalDailyBudget.Currency) } -func optimizationCampaignReportOperation(policy optimization.Policy, kind, resourceID string, start, end time.Time) (appleads.Operation, error) { - return optimizationCampaignReportOperationAtOffset(policy, kind, resourceID, start, end, 0) -} - func optimizationCampaignReportOperationAtOffset(policy optimization.Policy, kind, resourceID string, start, end time.Time, offset int) (appleads.Operation, error) { request, err := optimizationCampaignReportRequest(policy, kind, resourceID, start, end, offset) if err != nil { @@ -204,10 +200,6 @@ func (s *Service) optimizationBiddables(ctx context.Context, policy optimization return biddableRows(rows, resourceType, policy.MaxTotalDailyBudget.Currency) } -func optimizationBiddableReportOperation(policy optimization.Policy, kind, campaignID string, start, end time.Time) (appleads.Operation, error) { - return optimizationBiddableReportOperationAtOffset(policy, kind, campaignID, start, end, 0) -} - func optimizationBiddableReportOperationAtOffset(policy optimization.Policy, kind, campaignID string, start, end time.Time, offset int) (appleads.Operation, error) { request, err := optimizationBiddableReportRequest(policy, kind, campaignID, start, end, offset) if err != nil { From 7515d94671bd4faa0a8709b301481132ae4ed8dd Mon Sep 17 00:00:00 2001 From: Aleksei Zelentsov <37956463+zelentsov-dev@users.noreply.github.com> Date: Thu, 15 Oct 2026 20:50:02 +0300 Subject: [PATCH 3/4] Align correlation bounds and deprecated CPA preview schema --- docs/MIGRATION-v0.3.7.md | 2 +- internal/mcpserver/schema_test.go | 13 +++++++++---- internal/tools/mutation_schema.go | 5 ++++- 3 files changed, 14 insertions(+), 6 deletions(-) diff --git a/docs/MIGRATION-v0.3.7.md b/docs/MIGRATION-v0.3.7.md index 3a0266c..166d841 100644 --- a/docs/MIGRATION-v0.3.7.md +++ b/docs/MIGRATION-v0.3.7.md @@ -49,7 +49,7 @@ General reports preserve date strings, including hourly timestamps. The optimize Preview objects may contain an additive `warnings` array of objects with `code` and `message`. Warnings are retained for `operations_inspect`. Consumers should display them alongside the proposed changes before applying a receipt. -MCP input schemas reject invalid statuses, nonnumeric correlation IDs, mismatched strategy pairs, and malformed bid amounts before the handler. Context-dependent rules, such as the parent's strategy and currency, are checked by the handler. IDs and money remain string-based; bulk correlation IDs continue accepting nonnegative integers and decimal strings within the runtime's integer range. +MCP input schemas reject invalid statuses, nonnumeric correlation IDs, mismatched strategy pairs, and malformed bid amounts before the handler. Context-dependent rules, such as the parent's strategy and currency, are checked by the handler. IDs and money remain string-based; bulk correlation IDs accept nonnegative numeric safe integers up to 2^53 - 1, or decimal strings within the int64 range. Validation for this release uses synthetic unit, HTTP, MCP, concurrency, and receipt tests plus cross-platform CI and security/distribution checks. Live advertising mutations are not part of this release's acceptance. Older live test results do not establish v0.3.7 runtime acceptance. diff --git a/internal/mcpserver/schema_test.go b/internal/mcpserver/schema_test.go index 46e36f0..f5e21a3 100644 --- a/internal/mcpserver/schema_test.go +++ b/internal/mcpserver/schema_test.go @@ -2,13 +2,14 @@ package mcpserver import ( "context" - "github.com/modelcontextprotocol/go-sdk/mcp" - "github.com/zelentsov-dev/apple-ads-mcp/internal/appleads" - "github.com/zelentsov-dev/apple-ads-mcp/internal/config" "io" "math" "reflect" "testing" + + "github.com/modelcontextprotocol/go-sdk/mcp" + "github.com/zelentsov-dev/apple-ads-mcp/internal/appleads" + "github.com/zelentsov-dev/apple-ads-mcp/internal/config" ) func TestMCPMutationSchemasExposeWriteConstraints(t *testing.T) { @@ -63,7 +64,7 @@ func TestMCPMutationSchemasExposeWriteConstraints(t *testing.T) { t.Fatalf("oneOf=%v", node["oneOf"]) } integer := branches[0].(map[string]any) - if integer["type"] != "integer" || integer["minimum"] != float64(0) || integer["exclusiveMaximum"] != math.Exp2(63) { + if integer["type"] != "integer" || integer["minimum"] != float64(0) || integer["maximum"] != math.Exp2(53)-1 { t.Fatalf("integer branch=%v", integer) } decimalString := branches[1].(map[string]any) @@ -100,6 +101,7 @@ func TestMCPMutationSchemasRejectInvalidArgumentsBeforeHandlers(t *testing.T) { }{ {"active_status", "keyword_create_preview", keyword("ACTIVE", "")}, {"descriptive_correlation", "keywords_bulk_create_preview", bulk("k1")}, + {"unsafe_numeric_correlation", "keywords_bulk_create_preview", bulk(uint64(1) << 53)}, {"zero_bid", "keyword_create_preview", keyword("PAUSED", "0")}, {"leading_zero_bid", "keyword_create_preview", keyword("PAUSED", "01.20")}, } @@ -223,6 +225,9 @@ func TestMCPStrategySchemaPairsAndDeprecatedCap(t *testing.T) { t.Fatal(err) } for _, tool := range listed.Tools { + if tool.Name == "ad_group_cpa_cap_preview" && toolSchemaNode(t, tool)["deprecated"] != true { + t.Fatal("CPA cap tool annotation is missing") + } if tool.Name == "ad_group_create_preview" || tool.Name == "ad_group_update_preview" { if toolSchemaNode(t, tool, "payload", "cpaCap")["deprecated"] != true { t.Fatal("cpaCap annotation is missing") diff --git a/internal/tools/mutation_schema.go b/internal/tools/mutation_schema.go index a5ae7e4..db7c025 100644 --- a/internal/tools/mutation_schema.go +++ b/internal/tools/mutation_schema.go @@ -16,6 +16,9 @@ func mutationInputSchema[In any](toolName string) *jsonschema.Schema { panic(fmt.Sprintf("infer input schema for %s: %v", toolName, err)) } applyMutationSchemaConstraints(schema, "", false) + if toolName == "ad_group_cpa_cap_preview" { + schema.Deprecated = true + } if toolName == "campaign_create_preview" { payload := schema.Properties["payload"] if !slices.Contains(payload.Required, "bidStrategy") { @@ -54,7 +57,7 @@ func applyMutationSchemaConstraints(schema *jsonschema.Schema, parentName string *property = jsonschema.Schema{ Description: description, OneOf: []*jsonschema.Schema{ - {Type: "integer", Minimum: jsonschema.Ptr(0.0), ExclusiveMaximum: jsonschema.Ptr(math.Exp2(63))}, + {Type: "integer", Minimum: jsonschema.Ptr(0.0), Maximum: jsonschema.Ptr(math.Exp2(53) - 1)}, {Type: "string", MinLength: jsonschema.Ptr(1), Pattern: `^[0-9]+$`}, }, } From f0c1cbb319e7c006cceabbb6828ff97cf58581b9 Mon Sep 17 00:00:00 2001 From: Aleksei Zelentsov <37956463+zelentsov-dev@users.noreply.github.com> Date: Thu, 15 Oct 2026 20:50:43 +0300 Subject: [PATCH 4/4] Omit build-machine paths from public release binaries --- .goreleaser.yml | 2 ++ scripts/validate_distribution.py | 1 + 2 files changed, 3 insertions(+) diff --git a/.goreleaser.yml b/.goreleaser.yml index 49fa83f..c2c81e1 100644 --- a/.goreleaser.yml +++ b/.goreleaser.yml @@ -4,6 +4,8 @@ builds: - id: apple-ads-mcp main: ./cmd/apple-ads-mcp binary: apple-ads-mcp + flags: + - -trimpath env: - CGO_ENABLED=0 goos: diff --git a/scripts/validate_distribution.py b/scripts/validate_distribution.py index 7ec92db..7500e2d 100644 --- a/scripts/validate_distribution.py +++ b/scripts/validate_distribution.py @@ -44,6 +44,7 @@ def main() -> None: require(f"ARG VERSION={version}" in dockerfile, "Docker default version mismatch") require(f"`v{version}` is the current release" in readme, "README release status mismatch") require("release:" in goreleaser and 'name_template: "{{ .Tag }}"' in goreleaser, "GoReleaser release metadata missing") + require(" - -trimpath" in goreleaser, "release binaries must omit build-machine paths") require("first public release" not in goreleaser, "GoReleaser still assumes a first public release") archive_name_template = '{{ .ProjectName }}_{{ .Os }}_{{ .Arch }}_{{ .Version }}' require(f'name_template: "{archive_name_template}"' in goreleaser, "release archive version must be the final filename component")