diff --git a/MIGRATION_v9_to_v10.md b/MIGRATION_v9_to_v10.md index f23691da3..6509665c7 100644 --- a/MIGRATION_v9_to_v10.md +++ b/MIGRATION_v9_to_v10.md @@ -16,7 +16,7 @@ existed in the 10.0 prereleases, the entries listed under 10.0.0-beta.0 that | Change | Update your integration | | --- | --- | -| The wire pin is AdCP `3.3.0` | `get_adcp_version()` returns `3.3.0`; the SDK speaks `adcp_version: "3.3"` by default and advertises `3.0`, `3.1`, `3.2`, `3.3` and the `3.2-rc.7` alias. `10.0.0-beta.0` and `10.0.0-beta.1` pinned `3.3.0-beta.0`, `10.0.0-beta.2` pinned `3.3.0-beta.1`, `10.0.0-beta.3` pinned `3.3.0-beta.2`, `10.0.0-beta.4` through `10.0.0-beta.11` pinned `3.3.0-beta.3`, `10.0.0-beta.12` pinned `3.3.0-beta.4`, `10.0.0-beta.13` through `10.0.0-beta.16` pinned `3.3.0-beta.5`, `10.0.0-beta.17` through `10.0.0-beta.19` pinned `3.3.0-beta.6`, `10.0.0-beta.20` through `10.0.0-beta.22` pinned `3.3.0-rc.0`, and `10.0.0-beta.23` through `10.0.0-rc.9` pinned `3.3.0-rc.3`; none of those prereleases is advertised or accepted as an `adcp_version` pin any more (`ConfigurationError`), and a `3.3-beta.0`, `3.3-beta.1`, `3.3-beta.2`, `3.3-beta.3`, `3.3-beta.4`, `3.3-beta.5`, `3.3-beta.6`, `3.3-rc.0` or `3.3-rc.3` peer is negotiated like any other unserved prerelease (down to `3.2`). There is no `3.3-rc.3` alias: 3.3.0 bounds fields rc.3 left unbounded, so an rc.3 payload is not always a valid 3.3.0 payload. Re-pin to `3.3`, or omit the pin. Pin `adcp_version="3.2"` on a server whose handlers must keep running on the 3.2 contract (see "A server pin governs its handlers" below). On a client, `adcp_version` is a negotiation ceiling; its application models remain current. Generated types, bundled schemas and the versioned validators follow the 3.3 bundle. | +| The wire pin is AdCP `3.3.0` | `get_adcp_version()` returns `3.3.0`; the SDK speaks `adcp_version: "3.3"` by default and advertises `3.0`, `3.1`, `3.2`, `3.3` and the `3.2-rc.7` and `3.3-rc.3` aliases (`3.3-rc.3` was added after 10.0.0). `10.0.0-beta.0` and `10.0.0-beta.1` pinned `3.3.0-beta.0`, `10.0.0-beta.2` pinned `3.3.0-beta.1`, `10.0.0-beta.3` pinned `3.3.0-beta.2`, `10.0.0-beta.4` through `10.0.0-beta.11` pinned `3.3.0-beta.3`, `10.0.0-beta.12` pinned `3.3.0-beta.4`, `10.0.0-beta.13` through `10.0.0-beta.16` pinned `3.3.0-beta.5`, `10.0.0-beta.17` through `10.0.0-beta.19` pinned `3.3.0-beta.6`, `10.0.0-beta.20` through `10.0.0-beta.22` pinned `3.3.0-rc.0`, and `10.0.0-beta.23` through `10.0.0-rc.9` pinned `3.3.0-rc.3`. Except `3.3-rc.3`, none of those prereleases is advertised or accepted as an `adcp_version` pin any more (`ConfigurationError`), and a `3.3-beta.0`, `3.3-beta.1`, `3.3-beta.2`, `3.3-beta.3`, `3.3-beta.4`, `3.3-beta.5`, `3.3-beta.6` or `3.3-rc.0` peer is negotiated like any other unserved prerelease (down to `3.2`). `3.3-rc.3` is a deprecated compatibility alias of `3.3`, like `3.2-rc.7` of `3.2`, removed in 11.0 (adcontextprotocol/adcp#9223): the rc.3 to 3.3.0 schema delta only adds `maxItems`/`maxLength` bounds, so an rc.3 claim is served and validated as 3.3, and an rc.3 payload over a new bound fails validation. 10.0.0 refused it. A seller without `supported_versions` now accepts and advertises `3.3-rc.3` by default; to refuse it, pass an explicit `supported_versions` that omits it. A seller still running a request rewrite for it can drop that, or serve other wire versions with `serve(version_aliases=...)`. On a client, a seller that advertises `3.3-rc.3` is negotiated as `3.3-rc.3` and spoken to as 3.3, and its responses are validated against the 3.3.0 schemas, including the new bounds (strict by default, warn under `ADCP_ENV=production`). Re-pin to `3.3`, or omit the pin. Pin `adcp_version="3.2"` on a server whose handlers must keep running on the 3.2 contract (see "A server pin governs its handlers" below). On a client, `adcp_version` is a negotiation ceiling; its application models remain current. Generated types, bundled schemas and the versioned validators follow the 3.3 bundle. | | AdCP 3.3.0-beta.1 adds account requests, media-buy issues and reporting subscriptions | New tasks are wired through `ADCPClient` / `ADCPMultiAgentClient`, `ADCPHandler` (each returns `not_supported()` until overridden), the MCP and A2A adapters, the MCP tool list and the CLI: `request_account` (experimental `account.requests`; it opens, matches or, with `account_id`, changes an account, guarded by `revision`), `report_media_buy_issue` and `get_media_buy_issue`. `RequestAccountRequest` / `Response`, `ReportMediaBuyIssueRequest` / `Response` and `GetMediaBuyIssueRequest` / `Response` are exported from `adcp.types`. `list_accounts` gains `include_requests`, `request_ids` and `requests_pagination`, returning `account_requests[]` and `account_requests_pagination`. Experimental principal-level `reporting_subscriptions` land on `sync_principal` / `get_principal`, with `subscription_coverage[]` on `get_reporting_status`, `configuration_tasks[]` on `media_buy.reporting_delivery`, the `ReportingDimension` enum and the `principal.changed` reason `reporting_subscription_changed`. `sync_accounts` is unchanged and stays supported. Generated class names that the generator numbers can renumber with the bundle; import the semantic names from `adcp.types` rather than a numbered class from a domain module. | | AdCP 3.3.0-beta.2 withdraws definition pins, purchase rights and installment selection | adcontextprotocol/adcp#8537 moves all three to 4.0, so their generated types leave `adcp.types.domains.*`, `adcp.types._generated` and `adcp.types.error_details`: `DefinitionPin*`, `DefinitionPinReferenceKind`, `ReferenceDefinitionChangedDetails` (and `ErrorCode.REFERENCE_DEFINITION_CHANGED`), `DriftedPin`, `RightsScope`, `InstallmentChangeSet`, `commercial_terms.definition_pins`, `purchases[].rights` / `installments`, `installment_changes` and the `definition_changed` refinement reason. `TestControllerStore.definition_pin_probe` and the `definition_pin_probe` controller scenario are removed. Delete code that builds or reads them; a seller stops listing `media_buy.purchase_rights` and `media_buy.installment_selection` in `experimental_features`. | | AdCP 3.3.0-beta.2 adds separate-account outcomes, seller offers and measurement provenance | `RequestAccountRequest.allow_separate_account` (default `false`) lets a change request resolve as `created` (a new account carrying the change) or `matched` (an account the caller already holds), and the new correctable error code `ACCOUNT_CHANGE_REQUIRES_NEW_ACCOUNT` reports a change the seller would take only on a new account. Experimental seller offers add `proposal_initiator`, `offer_reason` on `list_proposals` rows and the `proposal.offered` notification (`ProposalOfferedWebhook`); experimental measurement provenance adds `CollectionMechanism`, `counting_mechanisms` and `vendor_metric_provenance[]` (`VendorMetricProvenance`). The reporting-subscription fields settled after beta.1 (`standard_dimensions`, `unmapped_dimensions`, `inactive_intervals`, `prior_versions[].configuration`, per-offering `offering_id`, `previous_timezone`) are now generated. `principal_kind` and `expected_principal_kind` are deprecated. `NotificationConfig.product_payload_view` loses its schema default: it is `None` when unset, and a product subscription's dump no longer adds `product_payload_view: "legacy"` (absent means legacy); read `config.product_payload_view or "legacy"`. These are generated types, imported from their domain packages (for example `adcp.types.domains.core.ProposalOfferedWebhook`); no task was added. | @@ -142,8 +142,9 @@ These APIs did not exist in 9.6.x, so they affect only code written against a - **Experimental agent identity and Web Bot Auth**: the experimental API was reshaped to the final AdCP 3.3 profile during the prereleases; see [the identity migration notes](docs/agent-identity-3-3-migration.md#breaking-changes-to-the-experimental-api). -- **Prerelease wire pins**: every `3.3-beta.N`, `3.3-rc.0` and `3.3-rc.3` pin - is refused; see the first row of the table. +- **Prerelease wire pins**: every `3.3-beta.N` and `3.3-rc.0` pin is refused; + `3.3-rc.3` is served as a deprecated alias of `3.3` until 11.0. See the + first row of the table. ## Listed under 10.0.0-beta.0, already in 9.x diff --git a/README.md b/README.md index 8901c56df..1b807168f 100644 --- a/README.md +++ b/README.md @@ -386,9 +386,11 @@ Guides: [seller](docs/reporting-subscriptions-seller.md) · [buyer](docs/reporti SDK 10 is built against **AdCP 3.3.0**, the AdCP 3.3 general-availability release, and keeps canonical creatives the primary Python contract. It negotiates AdCP 3.0, 3.1, 3.2 and 3.3. On the wire, 3.3 is `"3.3"`, because -`adcp_version` carries release precision only. The 3.3 release candidates -(`"3.3-rc.3"` and earlier) are not accepted pins; a peer that advertises only -one of them negotiates down to `"3.2"`. AdCP 3.2.0 was withdrawn and is not a +`adcp_version` carries release precision only. `"3.3-rc.3"`, the last 3.3 release +candidate, is a deprecated alias of `"3.3"` (removed in 11.0), like +`"3.2-rc.7"` of `"3.2"`: it is accepted, advertised by default, and served as +3.3. Earlier release candidates are not accepted pins; a peer that advertises +only one of them negotiates down to `"3.2"`. AdCP 3.2.0 was withdrawn and is not a supported target. The SDK package version and protocol version are intentionally independent: diff --git a/docs/adcp-3.3-sdk-inventory.md b/docs/adcp-3.3-sdk-inventory.md index a6be3d26b..ac0f93b6d 100644 --- a/docs/adcp-3.3-sdk-inventory.md +++ b/docs/adcp-3.3-sdk-inventory.md @@ -404,7 +404,7 @@ adcontextprotocol/adcp#8913 (PR #8951), #8625 (PR #8876), #8512, #8956, | Item | Detail | SDK status | | --- | --- | --- | -| Wire pin | `3.3.0` / `3.3`; bundle key `3.3`. `3.3-rc.3` is no longer advertised or accepted as a pin and gets no alias, because 3.3.0 bounds fields rc.3 left unbounded. Its cache and compliance trees stay in the source tree and leave the wheel. | done | +| Wire pin | `3.3.0` / `3.3`; bundle key `3.3`. `3.3-rc.3` is served as a deprecated alias of `3.3` until 11.0 (adcontextprotocol/adcp#9223): the rc.3 to 3.3.0 delta only adds bounds, so an rc.3 payload over one fails validation. Its cache and compliance trees stay in the source tree and leave the wheel. | done | | Bounds on new and experimental fields (#8512) | 657 `maxItems` / `maxLength` keywords on 158 schemas, only on fields absent from 3.2.12 or experimental; `get_adcp_capabilities` and stable fields are untouched. This includes the TMP `targeting_kvs` `key` and `value` (255 characters). | generated: the models enforce the bounds, and constrained string items are `ScalarStr` subclasses (still `str`). No carve-out: the SDK ships no TMP router, so the `targeting_kvs` bounds only reach the generated `TargetingKv` model. `core.reporting_subscription.AccountId7` is folded into `AccountId` | | Operator is a registrable domain (#8913) | `operator` in `account-ref`, `canonical-account-ref`, `sync_accounts`, `request_account`, brand.json `authorized_operator.domain`, `operator-identity` and the SI `paying_principal` is the eTLD+1 of the operating organization; a seller MAY refuse a subdomain. The patterns are unchanged. | descriptions regenerated; the SDK does not refuse a subdomain operator | | Repeated `format_kind` needs `format_option_ref` (#8625) | A seller MUST reject a manifest without `format_option_ref` when two or more `format_options` share its `format_kind`, and MUST NOT infer the option. The `canonical_formats` storyboard (1.2.0) checks it for sellers with `inline_creative_management`. | `find_declaration_by_kind` raises `FormatOptionRefRequiredError` (`VALIDATION_ERROR` on `format_option_ref`) instead of returning the first match. The legacy `format_id` projection already sets `format_option_ref` | diff --git a/docs/handler-authoring.md b/docs/handler-authoring.md index e36de66f2..eae89238c 100644 --- a/docs/handler-authoring.md +++ b/docs/handler-authoring.md @@ -2154,6 +2154,63 @@ Independent servers can select different subsets without mutating their shared handler. A custom external A2A `request_handler` owns dispatch, so its factory rejects an explicit SDK selection rather than advertising unenforced versions. +### Serve extra wire versions + +`version_aliases` serves another wire version as one of the server's releases, +for buyers built against a prerelease whose contract the release still +accepts: + +```python +serve(MySeller(), version_aliases={"3.3-rc.2": "3.3"}) +``` + +`serve`, `ServeConfig`, `create_mcp_server`, `create_a2a_server`, +`adcp.decisioning.serve`, `MCPToolSet`, `create_tool_caller` and the testing +helpers accept it. A request claiming an alias is accepted on every tool and +transport, task polling (`get_task_status`, `list_tasks`) and +`comply_test_controller` included. It is validated, converted and handled as +its target: `ToolContext.resolved_adcp_version` is the target, never the alias. +`get_adcp_capabilities` advertises each alias in `adcp.supported_versions` +while it advertises the target (after the `response_enhancer` runs, so an +enhancer cannot drop it), `VERSION_UNSUPPORTED` lists it in +`details.supported_versions`, and responses echo it where the target's response +schema admits `adcp_version` (see "Response `adcp_version`" in +`docs/validation-contract.md`). + +Each key must be a release-precision prerelease of its target's own release +line that the SDK does not serve natively: `3.3-rc.2` for `3.3` is accepted, +while a stable key (`3.4` for `3.3`) or another line's prerelease +(`3.3-beta.1` for `3.2`) is refused, since it would advertise a release the +server does not serve and break the spec's downshift rule. Targets must be +native releases the server serves (in `supported_versions`, when given). Configuration errors raise +`ConfigurationError` at construction. With `supported_versions`, the aliases +follow the selection: `supported_versions=["3.3"], version_aliases={"3.3-rc.2": +"3.3"}` serves `["3.3", "3.3-rc.2"]`. + +The built-in aliases need no entry: `3.2-rc.7` (served as `3.2`) and +`3.3-rc.3` (served as `3.3`; the rc.3 to 3.3.0 schema delta only adds +`maxItems`/`maxLength` bounds, adcontextprotocol/adcp#9223). The `3.3-rc.3` +alias is deprecated and is removed in SDK 11.0; a seller that still needs it +then passes `version_aliases={"3.3-rc.3": "3.3"}`. An explicit +`supported_versions` list must name a built-in alias (or restate it in +`version_aliases`) to serve it. + +### Pre-validation hooks and middleware + +`pre_validation_hooks` maps a tool name to a hook or an ordered list of hooks. +The `"*"` key (`adcp.server.GLOBAL_PRE_VALIDATION_HOOK_KEY`) runs for every +tool, before that tool's own hooks, so a cross-cutting hook covers tools added +later. `"*"` hooks never apply to `comply_test_controller`, and the SDK's +managed controller (`test_controller=`) runs no pre-validation hooks at all. + +`SkillMiddleware` runs before hooks: the middleware chain wraps the tool +caller, so each middleware receives the caller's raw request. Each hook +receives a shallow copy of the args, so a hook that sets top-level keys or +returns a new dict never changes what middleware holds, before or after +`call_next()`. Middleware can therefore pair the original request with the +response. Nested values are shared; a hook must copy one before mutating it in +place. + ### HTTP Host and Origin policy `serve`, `ServeConfig`, `create_mcp_server`, `create_a2a_server` and diff --git a/docs/validation-contract.md b/docs/validation-contract.md index 9065c1a8f..151f48bac 100644 --- a/docs/validation-contract.md +++ b/docs/validation-contract.md @@ -143,8 +143,17 @@ with the issue that tracks it, and the list only shrinks: - Validation selects the schema bundle matching the negotiated wire version, so strict current-version behavior does not tighten legacy 2.5, 3.0, or 3.1 traffic against the 3.2 schema. -- `"3.2-rc.7"` is an explicit wire compatibility alias for `"3.2"`, validated - against the stable bundle. Direct schema-loader calls using full historical +- `"3.2-rc.7"` and `"3.3-rc.3"` are explicit wire compatibility aliases for + `"3.2"` and `"3.3"`, validated against the stable bundle (`"3.3-rc.3"` is + deprecated and removed in SDK 11.0). Both are on by default: a server + without `supported_versions` accepts and advertises `3.3-rc.3`; pass an + explicit `supported_versions` (for example `["3.0", "3.1", "3.2", "3.3"]`) + to refuse it. A client that negotiates with a seller advertising + `3.3-rc.3` speaks 3.3 to it under that alias and validates its responses + against the 3.3.0 schemas, including bounds rc.3 lacked (strict by default, + warn under `ADCP_ENV=production`). A server adds its own aliases with + `serve(version_aliases=...)`; see "Serve extra wire versions" in + `docs/handler-authoring.md`. Direct schema-loader calls using full historical identifiers such as `"3.2.0-rc.7"` retain exact bundle lookup. - Missing validators for an explicit native-tool version produce `VERSION_UNSUPPORTED`, with `field="adcp_version"` and `supported_versions` @@ -153,6 +162,32 @@ with the issue that tracks it, and the list only shrinks: - Pre-validation hooks can raise `AdcpError` or `ADCPTaskError` to deliberately reject a request. The dispatcher preserves their structured fields; other hook exceptions produce `INVALID_REQUEST` with the failing hook's name. +- The dispatcher's own `VERSION_UNSUPPORTED` lists the server's effective served + versions in `details.supported_versions`: its `supported_versions` selection + (or every version the SDK serves), followed by its `version_aliases`. + +### Response `adcp_version` + +The server adds `adcp_version` to a response in two cases, and only where the +schema of the release it served admits a top-level `adcp_version` for that +response variant: + +1. **Version conversion.** When the caller's release differs from the release + the handler runs on, the converted response carries the served release. +2. **Alias echo.** When the caller claimed an alias (built-in, or from + `version_aliases`), the response carries the caller's alias, so clients + built against that prerelease can select their response validator. The + claim is read from the caller's raw request, before pre-validation hooks; + when the caller sent none, a version a hook supplied counts as the claim. + +Otherwise the SDK adds nothing (a handler or `response_enhancer` may set the +field itself). A schema that is closed (`additionalProperties: false`) without +declaring `adcp_version` never gets it: the compact AdCP 3.2 roots of +`list_products`, `buy_products`, `control_media_buy`, `accept_proposal` and +`decline_proposals` are answered without it, even to a `3.2-rc.7` caller. The +check is conservative: any composed object schema that forbids the field +suppresses the echo. Whether every response should carry the served version is +an open spec question (adcontextprotocol/adcp#9370). ### Payload size diff --git a/src/adcp/_version.py b/src/adcp/_version.py index 2be0be983..12eb02898 100644 --- a/src/adcp/_version.py +++ b/src/adcp/_version.py @@ -23,25 +23,41 @@ from __future__ import annotations import re +from collections.abc import Mapping # Release-precision versions this SDK can speak. Patch-level pinning is # intentionally absent — patches don't change the wire contract by # definition, so making them part of the pin is a category error. COMPATIBLE_ADCP_VERSIONS: tuple[str, ...] = ("3.0", "3.1", "3.2", "3.3") -# Explicit compatibility bridge for buyers shipped with adcp 8.0.0rc3. -# rc.7 requests remain valid under the additive 3.2.1 contract. Other -# prereleases retain their own schema contracts; never infer aliases by pattern. -# An alias is advertised only while its target is. -_ADCP_VERSION_ALIASES: dict[str, str] = {"3.2-rc.7": "3.2"} - - -def resolve_adcp_version_alias(version: str) -> str: +# Explicit compatibility bridges, served as their stable target release: +# +# * ``3.2-rc.7`` for buyers shipped with adcp 8.0.0rc3; rc.7 requests remain +# valid under the additive 3.2.1 contract. +# * ``3.3-rc.3`` for buyers shipped against the AdCP 3.3 release candidate +# (adcp 10.0.0rc / @adcp/sdk 17 prereleases); the rc.3 -> 3.3.0 schema delta +# only adds ``maxItems`` / ``maxLength`` bounds (adcontextprotocol/adcp#9223). +# Deprecated: removed in SDK 11.0. Sellers that still need it then pass +# ``serve(version_aliases={"3.3-rc.3": "3.3"})``. +# +# Other prereleases retain their own schema contracts; never infer aliases by +# pattern. An alias is advertised only while its target is. Per-server aliases +# (``serve(version_aliases=...)``) extend this map for one server only. +_ADCP_VERSION_ALIASES: dict[str, str] = {"3.2-rc.7": "3.2", "3.3-rc.3": "3.3"} + + +def resolve_adcp_version_alias(version: str, aliases: Mapping[str, str] | None = None) -> str: """Resolve an exact wire alias to the release the SDK actually serves. Full historical bundle identifiers remain exact: only release-precision wire values are aliased. This preserves archival schema access. + ``aliases`` adds one server's ``version_aliases`` to the built-in map; + they cannot override a built-in alias (the server builder refuses that). """ + if aliases: + target = aliases.get(version) + if target is not None: + return target return _ADCP_VERSION_ALIASES.get(version, version) @@ -205,7 +221,8 @@ def resolve_adcp_version(pin: str | None) -> str: is advertised by this SDK. - Cross-major pin → raises :class:`ConfigurationError`. - Unparseable string → raises :class:`ConfigurationError`. - - The explicit ``3.2-rc.7`` compatibility alias resolves to ``3.2``. + - The explicit ``3.2-rc.7`` and ``3.3-rc.3`` compatibility aliases + resolve to ``3.2`` and ``3.3``. All resolved pins are normalized to release-precision before being returned, per the spec's wire-value rule diff --git a/src/adcp/decisioning/serve.py b/src/adcp/decisioning/serve.py index 9b89e3630..cd8ca306d 100644 --- a/src/adcp/decisioning/serve.py +++ b/src/adcp/decisioning/serve.py @@ -31,7 +31,7 @@ import os import warnings -from collections.abc import Sequence +from collections.abc import Mapping, Sequence from concurrent.futures import ThreadPoolExecutor from dataclasses import replace from typing import TYPE_CHECKING, Any, Literal @@ -539,6 +539,7 @@ def serve( validate_at_init: bool = True, adcp_version: str | None = None, supported_versions: Sequence[str] | None = None, + version_aliases: Mapping[str, str] | None = None, account_activity: ReportingActivityProjector | None = None, reporting_activity: ReportingActivitySupport | None = None, reporting_status: ReportingStatusSupport | None = None, @@ -638,6 +639,11 @@ def serve( The hook receives a shallow copy of the wire args, so it may mutate its argument freely or return a new dict — either style is safe. Context echo always reflects the original wire input. + The ``"*"`` key runs its hooks for every tool, before that tool's + own. + :param version_aliases: Extra wire versions to serve as one of this + server's releases, e.g. ``{"3.3-rc.3": "3.3"}``. See + :func:`adcp.server.serve`. :param signer_keys: Turns on framework RFC 9421 request-signature verification, enforcing the platform's declared ``capabilities.request_signing`` block (``required_for``, @@ -758,6 +764,8 @@ def serve( debug_traffic_source = mock_ad_server.get_traffic if mock_ad_server is not None else None if pre_validation_hooks is not None: serve_kwargs["pre_validation_hooks"] = pre_validation_hooks + if version_aliases is not None: + serve_kwargs["version_aliases"] = version_aliases # The SDK owns the parent lifespan for the dual-transport server, so # attach the platform's upstream pool drain there. Single-transport diff --git a/src/adcp/server/__init__.py b/src/adcp/server/__init__.py index 2b88d4946..98b2a7d3c 100644 --- a/src/adcp/server/__init__.py +++ b/src/adcp/server/__init__.py @@ -55,6 +55,7 @@ async def get_products(params, context=None): from adcp._principal_ref import PrincipalRef from adcp.capabilities import validate_capabilities from adcp.server._hooks import ( + GLOBAL_PRE_VALIDATION_HOOK_KEY, PreValidationHook, PreValidationHookChain, PreValidationHookError, @@ -354,6 +355,7 @@ async def get_products(params, context=None): "PreValidationHookError", "PreValidationHooks", "compose_pre_validation_hooks", + "GLOBAL_PRE_VALIDATION_HOOK_KEY", "spec_compat_hooks", # DX helpers "AccountError", diff --git a/src/adcp/server/_hooks.py b/src/adcp/server/_hooks.py index dbef35455..f52dcc62d 100644 --- a/src/adcp/server/_hooks.py +++ b/src/adcp/server/_hooks.py @@ -22,14 +22,34 @@ """One hook or an ordered sequence of hooks for a single tool.""" PreValidationHooks: TypeAlias = dict[str, PreValidationHookChain] -"""Type alias for the ``pre_validation_hooks`` parameter of ``serve()``.""" +"""Type alias for the ``pre_validation_hooks`` parameter of ``serve()``. + +Keys are tool names. The :data:`GLOBAL_PRE_VALIDATION_HOOK_KEY` key (``"*"``) +holds cross-cutting hooks that run for every tool, before that tool's own. +""" + +GLOBAL_PRE_VALIDATION_HOOK_KEY = "*" +"""``pre_validation_hooks`` key whose hooks run for every tool. + +Its chain runs first, then the tool's own chain, so a cross-cutting rewrite +(version bridging, unknown-field policy) is in place before tool-specific +hooks see the args, and a tool added later is covered without being listed. +The ``"*"`` chain never applies to ``comply_test_controller``: the +compliance controller is a test surface whose scenario payloads a production +rewrite must not touch. The SDK's managed controller (``test_controller=``) +runs no pre-validation hooks at all. +""" + +_GLOBAL_HOOK_EXEMPT_TOOLS = frozenset({"comply_test_controller"}) __all__ = [ + "GLOBAL_PRE_VALIDATION_HOOK_KEY", "PreValidationHook", "PreValidationHookChain", "PreValidationHookError", "PreValidationHooks", "compose_pre_validation_hooks", + "pre_validation_hooks_for_tool", ] @@ -71,6 +91,25 @@ def _flatten_pre_validation_hooks( return flattened +def pre_validation_hooks_for_tool( + hooks: Mapping[str, PreValidationHookChain] | None, + tool_name: str, +) -> tuple[PreValidationHook, ...]: + """The ordered hook chain that runs for ``tool_name``. + + The ``"*"`` chain runs first, then the tool's own chain. + ``comply_test_controller`` gets only its own chain. + """ + if not hooks: + return () + global_chain = ( + () + if tool_name in _GLOBAL_HOOK_EXEMPT_TOOLS + else _flatten_pre_validation_hooks(hooks.get(GLOBAL_PRE_VALIDATION_HOOK_KEY)) + ) + return (*global_chain, *_flatten_pre_validation_hooks(hooks.get(tool_name))) + + def _apply_pre_validation_hooks( hooks: tuple[PreValidationHook, ...], tool_name: str, @@ -113,9 +152,10 @@ def compose_pre_validation_hooks( ) -> dict[str, tuple[PreValidationHook, ...]]: """Compose ordered pre-validation hook maps. - Later maps append to earlier maps for overlapping tool names. Each - tool's hooks run left-to-right, feeding the returned args from one hook - into the next. + Later maps append to earlier maps for overlapping tool names (the + ``"*"`` key included). Each tool's hooks run left-to-right, feeding the + returned args from one hook into the next; ``"*"`` hooks run before a + tool's own. """ composed: dict[str, list[PreValidationHook]] = {} for hook_map in hook_maps: diff --git a/src/adcp/server/a2a_server.py b/src/adcp/server/a2a_server.py index d07377f80..724037fbc 100644 --- a/src/adcp/server/a2a_server.py +++ b/src/adcp/server/a2a_server.py @@ -43,12 +43,12 @@ from adcp._a2a_numbers import A2AStructNumberMiddleware, restore_struct_integers from adcp.exceptions import ADCPError -from adcp.server._hooks import PreValidationHooks +from adcp.server._hooks import PreValidationHooks, pre_validation_hooks_for_tool from adcp.server.base import ADCPHandler, ToolContext from adcp.server.helpers import ResponseEnhancer, _apply_response_enhancer if TYPE_CHECKING: - from collections.abc import Sequence + from collections.abc import Mapping, Sequence from a2a.server.agent_execution.active_task import ActiveTask from a2a.server.events.event_queue import Event @@ -792,6 +792,7 @@ def __init__( test_controller_account_resolver: Any | None = None, response_enhancer: ResponseEnhancer | None = None, supported_versions: Sequence[str] | None = None, + version_aliases: Mapping[str, str] | None = None, ) -> None: self._handler = handler self._context_factory = context_factory @@ -821,7 +822,10 @@ def __init__( ) supported_versions = resolve_supported_versions( - supported_versions, handler=handler, adcp_version=resolved_adcp_version + supported_versions, + handler=handler, + adcp_version=resolved_adcp_version, + version_aliases=version_aliases, ) self._supported_versions = supported_versions self._default_adcp_version = resolved_adcp_version @@ -837,9 +841,11 @@ def __init__( ) for tool_def in tool_defs: name = tool_def["name"] - if name == "comply_test_controller" and test_controller is None: + if name == "comply_test_controller": + # Served by the managed controller registered below (without + # pre-validation hooks), or not at all without a store. continue - hook = (pre_validation_hooks or {}).get(name) + hook = pre_validation_hooks_for_tool(pre_validation_hooks, name) self._tool_callers[name] = create_tool_caller( handler, name, @@ -1778,6 +1784,7 @@ def create_a2a_server( public_url: str | PublicUrlResolver | None = None, response_enhancer: ResponseEnhancer | None = None, supported_versions: Sequence[str] | None = None, + version_aliases: Mapping[str, str] | None = None, ) -> Any: """Create an A2A Starlette application from an ADCP handler. @@ -1950,10 +1957,14 @@ def agent_card_url(request: Request) -> str: ) if request_handler is not None: - if supported_versions is not None or getattr(handler, "_supported_adcp_versions", None): + if ( + supported_versions is not None + or version_aliases + or getattr(handler, "_supported_adcp_versions", None) + ): raise ValueError( - "supported_versions cannot be combined with request_handler=: " - "the custom request handler owns dispatch" + "supported_versions and version_aliases cannot be combined with " + "request_handler=: the custom request handler owns dispatch" ) if auth is not None and auth.a2a_discovery_skills is not None: raise ValueError( @@ -1989,6 +2000,7 @@ def agent_card_url(request: Request) -> str: test_controller_account_resolver=test_controller_account_resolver, response_enhancer=response_enhancer, supported_versions=supported_versions, + version_aliases=version_aliases, ) if request_handler is None and task_store is None: diff --git a/src/adcp/server/mcp_tools.py b/src/adcp/server/mcp_tools.py index f3d5fb8b1..a452ebbd2 100644 --- a/src/adcp/server/mcp_tools.py +++ b/src/adcp/server/mcp_tools.py @@ -22,7 +22,7 @@ import difflib import logging import re -from collections.abc import Callable, Iterable, Sequence +from collections.abc import Callable, Iterable, Mapping, Sequence from typing import Any, Literal, cast from adcp._idempotency import is_mutating @@ -32,6 +32,7 @@ PreValidationHooks, _apply_pre_validation_hooks, _flatten_pre_validation_hooks, + pre_validation_hooks_for_tool, ) from adcp.server.base import ADCPHandler, ToolContext from adcp.server.helpers import ResponseEnhancer, _apply_response_enhancer @@ -3753,6 +3754,7 @@ def create_tool_caller( response_enhancer: ResponseEnhancer | None = None, supported_versions: Sequence[str] | None = None, adcp_version: str | None = None, + version_aliases: Mapping[str, str] | None = None, ) -> Callable[..., Any]: """Create a tool caller function for an ADCP handler method. @@ -3789,10 +3791,15 @@ def create_tool_caller( replaces the wire args before schema validation and Pydantic ``model_validate`` run. Pass either one hook or an ordered sequence of hooks; sequences run left-to-right. The framework passes a shallow - copy of the incoming params dict to each hook, so a hook may mutate - its argument freely or return a brand-new dict — either style is safe. + copy of the incoming params dict to each hook, so a hook may set or + delete top-level keys freely or return a brand-new dict — either style + is safe. Nested values are shared with the caller's request (and with + what :data:`~adcp.server.SkillMiddleware` holds, since middleware runs + before the tool caller); copy one before mutating it in place. The original wire params are captured before the copy is made, so - context echo always reflects what the buyer sent. Use this to apply + context echo and the version-alias echo reflect what the buyer sent. + Transports compose a server's hooks per tool: the ``"*"`` entry of + ``pre_validation_hooks`` first, then the tool's own entry. Use this to apply spec-mandated defaults for pre-v3 buyers that omit required fields (e.g. ``buying_mode``, ``format_id`` shape coercion, ``asset_type`` inference). The hook runs on every call; keep it fast. @@ -3838,6 +3845,28 @@ def create_tool_caller( :func:`adcp.server.version_policy.resolve_supported_versions`. adcp_version: Trusted server pin. Defaults to the handler's own ``get_adcp_version()`` / ``_adcp_version`` pin. + version_aliases: Extra wire versions served as a release this + server serves (``{"3.3-rc.3": "3.3"}``). See **Version aliases**. + + **Version aliases.** A request claiming an alias (built-in, or from + ``version_aliases``) is routed, converted, validated and handled exactly + as its target release; ``ToolContext.resolved_adcp_version`` is the + target. The alias is accepted on every tool, task polling included, + advertised in ``get_adcp_capabilities`` and listed in + ``VERSION_UNSUPPORTED`` details. + + **Response ``adcp_version`` echo.** Besides version conversion (a + converted response carries the release it was converted to), the SDK + adds ``adcp_version`` to a response in one case: the caller claimed an + alias (its raw request's ``adcp_version``, before pre-validation hooks; + or, when the caller sent none, the value a hook supplied), and the + served release's response schema for that response variant admits a + top-level ``adcp_version``. The value is the caller's alias, so clients + built against the prerelease can select their response validator. A + schema that is closed without declaring the field (the compact AdCP 3.2 + roots of ``list_products``, ``buy_products``, ``control_media_buy``, + ``accept_proposal``, ``decline_proposals``) gets no echo. A handler or + ``response_enhancer`` may still set the field itself. **Application version.** The handler runs on one release: the server's pin, else the newest of ``supported_versions``, else the release @@ -3935,13 +3964,21 @@ def create_tool_caller( selected_versions = resolve_supported_versions( supported_versions, handler=handler, + version_aliases=version_aliases, ) accepted_versions = selected_versions or SUPPORTED_WIRE_VERSIONS from adcp._version import resolve_adcp_version_alias from adcp.compat.versions import is_convertible_version from adcp.server.version_policy import resolve_application_adcp_version + from adcp.validation.envelope import served_version_aliases + from adcp.validation.schema_validator import response_admits_property - served_contracts = {resolve_adcp_version_alias(version) for version in accepted_versions} + served_aliases = served_version_aliases(accepted_versions) + + def resolve_alias(version: str) -> str: + return resolve_adcp_version_alias(version, served_aliases) + + served_contracts = {resolve_alias(version) for version in accepted_versions} # The release the handler runs on. Requests are converted to it and # responses from it; wire-side validation keeps the buyer's version. application_version = resolve_application_adcp_version( @@ -3957,7 +3994,9 @@ def unsupported_version_error(exc: UnsupportedVersionError) -> ADCPTaskError: message=str(exc), details={ "claimed_version": exc.wire_value, - "supported_versions": list(exc.supported), + # The server's effective served list, aliases + # included, whichever check refused the claim. + "supported_versions": list(accepted_versions), }, ) ], @@ -4193,9 +4232,7 @@ async def _call_tool( # selected set as explicit version claims, even when schema # validation is off. effective_version = wire_version or application_version - effective_version = resolve_adcp_version_alias( - normalize_to_release_precision(effective_version) - ) + effective_version = resolve_alias(normalize_to_release_precision(effective_version)) if effective_version not in served_contracts: raise unsupported_version_error( UnsupportedVersionError(effective_version, accepted_versions) @@ -4203,11 +4240,23 @@ async def _call_tool( if wire_version is not None: wire_version = effective_version - claimed_release = params.get("adcp_version") + # The alias to echo is the caller's own claim: the raw request, not + # what a pre-validation hook rewrote it to. A hook that supplies a + # missing envelope still counts as the claim. + claimed_release = raw_params.get("adcp_version") if isinstance(raw_params, dict) else None + if not (isinstance(claimed_release, str) and claimed_release): + claimed_release = params.get("adcp_version") if isinstance(params, dict) else None bridged_response_version: str | None = None - if isinstance(claimed_release, str) and claimed_release: - normalized_claim = normalize_to_release_precision(claimed_release) - if normalized_claim != wire_version: + if isinstance(claimed_release, str) and claimed_release and wire_version is not None: + try: + normalized_claim: str | None = normalize_to_release_precision(claimed_release) + except ValueError: + normalized_claim = None + if ( + normalized_claim is not None + and normalized_claim != wire_version + and resolve_alias(normalized_claim) == wire_version + ): bridged_response_version = normalized_claim ctx.resolved_adcp_version = wire_version @@ -4324,8 +4373,7 @@ async def _call_tool( convert_minor_version = ( legacy_adapter is None and wire_version is not None - and resolve_adcp_version_alias(normalize_to_release_precision(wire_version)) - != application_version + and resolve_alias(normalize_to_release_precision(wire_version)) != application_version and wire_version.startswith("3.") and is_convertible_version(wire_version) # A frozen historical prerelease mount serves its own contract. @@ -4655,12 +4703,23 @@ async def _call_tool( # ADCP requires echoing context from request to response — read # from the raw dict the transport sent, not from the validated # model (which won't carry the wire ``context`` field). + echoed_version: str | None = None + if ( + bridged_response_version is not None + and isinstance(result, dict) + and response_admits_property( + method_name, result, "adcp_version", version=response_validator_version + ) + ): + # Old prerelease clients (rc.7, rc.3) select their response + # validator from this field. Never stamp it where the served + # release's response schema forbids it (#2007). + echoed_version = bridged_response_version if isinstance(result, dict): - if bridged_response_version is not None: - # Old rc.7 clients have no stable validator. Retain the wire - # alias for their response lookup while routing and validating - # internally against the compatible stable contract. - result["adcp_version"] = bridged_response_version + if echoed_version is not None: + # Retain the wire alias for the client's response lookup while + # routing and validating internally against the target release. + result["adcp_version"] = echoed_version _normalize_response_envelope( method_name, result, @@ -4747,8 +4806,8 @@ async def _call_tool( ) result = converted.payload ctx.metadata[CONVERSION_METADATA_KEY]["losses"].extend(converted.metadata()) - if bridged_response_version is not None: - result["adcp_version"] = bridged_response_version + if echoed_version is not None: + result["adcp_version"] = echoed_version if response_mode is not None and response_mode != "off" and isinstance(result, dict): # Skip validation when the handler returned the AdCP L3 @@ -4828,6 +4887,7 @@ def __init__( adcp_version: str | None = None, schema_mode: SchemaMode = "lean", advertise_output_schemas: bool = False, + version_aliases: Mapping[str, str] | None = None, ): """Create tool set from handler. @@ -4842,7 +4902,8 @@ def __init__( tool caller. See :func:`create_tool_caller`. pre_validation_hooks: Optional dict mapping tool name to a ``(tool_name, args) -> args`` callable or ordered sequence. - Applied before schema + Pydantic validation. See + Applied before schema + Pydantic validation. The ``"*"`` + key runs for every tool, before the tool's own hooks. See :func:`create_tool_caller`. response_enhancer: Optional server-wide :data:`ResponseEnhancer` applied to every successful response. See @@ -4851,13 +4912,18 @@ def __init__( :func:`get_tools_for_handler`. advertise_output_schemas: Include each tool's ``outputSchema`` in ``tool_definitions``. See :func:`get_tools_for_handler`. + version_aliases: Extra wire versions served as one of this + server's releases. See :func:`create_tool_caller`. """ self.handler = handler resolved_adcp_version = _resolve_handler_adcp_version(handler, adcp_version) from adcp.server.version_policy import default_adcp_version, resolve_supported_versions supported_versions = resolve_supported_versions( - supported_versions, handler=handler, adcp_version=resolved_adcp_version + supported_versions, + handler=handler, + adcp_version=resolved_adcp_version, + version_aliases=version_aliases, ) # Discovery describes the release the handlers run on: the pin, else # the newest of ``supported_versions`` (the application version, as @@ -4883,7 +4949,7 @@ def __init__( # Create tool callers only for filtered tools for tool_def in self._filtered_definitions: name = tool_def["name"] - hook = (pre_validation_hooks or {}).get(name) + hook = pre_validation_hooks_for_tool(pre_validation_hooks, name) self._tools[name] = create_tool_caller( handler, name, @@ -4935,6 +5001,7 @@ def create_mcp_tools( adcp_version: str | None = None, schema_mode: SchemaMode = "lean", advertise_output_schemas: bool = False, + version_aliases: Mapping[str, str] | None = None, ) -> MCPToolSet: """Create MCP tools from an ADCP handler. @@ -4971,7 +5038,8 @@ async def call_tool(name: str, arguments: dict): :func:`create_tool_caller` for mode semantics. pre_validation_hooks: Optional dict mapping tool name to a ``(tool_name, args) -> args`` callable or ordered sequence. - Applied before schema + Pydantic validation. See + Applied before schema + Pydantic validation. The ``"*"`` key + runs for every tool, before the tool's own hooks. See :func:`create_tool_caller`. response_enhancer: Optional server-wide :data:`ResponseEnhancer` applied to every successful response. See @@ -5001,4 +5069,5 @@ async def call_tool(name: str, arguments: dict): adcp_version=adcp_version, schema_mode=schema_mode, advertise_output_schemas=advertise_output_schemas, + version_aliases=version_aliases, ) diff --git a/src/adcp/server/serve.py b/src/adcp/server/serve.py index 8cbc8726c..bdf84b1d8 100644 --- a/src/adcp/server/serve.py +++ b/src/adcp/server/serve.py @@ -26,7 +26,7 @@ async def get_adcp_capabilities(self, params, context=None): import os import sys import warnings -from collections.abc import AsyncIterator, Awaitable, Callable, Sequence +from collections.abc import AsyncIterator, Awaitable, Callable, Mapping, Sequence from contextvars import ContextVar from copy import deepcopy from dataclasses import dataclass @@ -37,7 +37,7 @@ async def get_adcp_capabilities(self, params, context=None): _ADCP_MCP_REQUEST_CONTEXT: ContextVar[Any] = ContextVar("adcp_mcp_request_context") from adcp._json_bounds import MAX_JSON_MEMBERS -from adcp.server._hooks import PreValidationHooks +from adcp.server._hooks import PreValidationHooks, pre_validation_hooks_for_tool from adcp.server.base import ADCPHandler, ToolContext from adcp.server.helpers import ResponseEnhancer from adcp.server.http_policy import ( @@ -350,6 +350,7 @@ class ServeConfig: pre_validation_hooks: PreValidationHooks | None = None response_enhancer: ResponseEnhancer | None = None supported_versions: Sequence[str] | None = None + version_aliases: Mapping[str, str] | None = None # --- Discovery manifest --- base_url: str | None = None @@ -376,6 +377,13 @@ def __post_init__(self) -> None: object.__setattr__( self, "supported_versions", resolve_supported_versions(self.supported_versions) ) + if self.version_aliases is not None: + # Check (and freeze) the aliases now; serve() folds them into the + # served set with the handler it is given. + resolve_supported_versions( + self.supported_versions, version_aliases=self.version_aliases + ) + object.__setattr__(self, "version_aliases", dict(self.version_aliases)) _a2a_only = ( "task_store", "push_config_store", @@ -479,6 +487,18 @@ async def middleware( layer sees by mutating ``params`` — transforms happen on the return side only, by modifying the value returned from ``call_next()``. +**Ordering against pre-validation hooks (a stable contract).** Middleware +runs first: the whole chain wraps the tool caller, so every middleware +receives the caller's raw request, before ``pre_validation_hooks``, version +aliasing, conversion and validation. Pre-validation hooks run inside +``call_next()``, and each hook receives a *shallow copy* of the args. A hook +that rebinds a top-level key (``args["adcp_version"] = "3.3"``) or returns a +new dict therefore never changes the ``params`` middleware holds, before or +after ``call_next()`` returns, so middleware can read the caller's original +request on the return side (to pair it with the response, say). A hook that +mutates a *nested* object in place is visible to middleware; copy nested +values before changing them. + Multiple middlewares compose outermost-first, matching Starlette/ASGI semantics — if you pass ``middleware=[Audit(), RateLimit(), Metrics()]``, the runtime order is:: @@ -1044,6 +1064,7 @@ def serve( pre_validation_hooks: PreValidationHooks | None = None, response_enhancer: ResponseEnhancer | None = None, supported_versions: Sequence[str] | None = None, + version_aliases: Mapping[str, str] | None = None, enable_debug_endpoints: bool = False, debug_traffic_source: Callable[[], dict[str, int]] | None = None, session_count_source: Callable[[], dict[str, Any]] | None = None, @@ -1282,6 +1303,31 @@ class of bug that shipped the ``pricing_options`` ``ValidationHookConfig(requests="off", responses="off")`` or ``validation=None``. Applies to both MCP and A2A transports. + pre_validation_hooks: Optional dict mapping a tool name to a + ``(tool_name, args) -> args`` hook or ordered hook sequence, + run before schema validation. The ``"*"`` key + (:data:`~adcp.server.GLOBAL_PRE_VALIDATION_HOOK_KEY`) runs for + every tool except ``comply_test_controller``, before that tool's + own hooks. Each hook receives a + shallow copy of the args; :data:`SkillMiddleware` runs first and + keeps the caller's raw request (see its "Ordering" section). + supported_versions: Wire versions this server serves; a buyer + claiming another is refused with ``VERSION_UNSUPPORTED``. + Defaults to every version the SDK serves. + version_aliases: Extra wire versions to serve as one of this + server's releases, e.g. ``{"3.3-rc.3": "3.3"}``. A request + claiming an alias is accepted on every tool and transport + (task polling included), validated and handled as the target + release, and answered with the alias echoed in + ``adcp_version`` where the target response schema allows the + field. Aliases are advertised in ``get_adcp_capabilities`` + ``adcp.supported_versions`` (while their target is) and listed + in ``VERSION_UNSUPPORTED`` details. Each key must be a + release-precision prerelease of its target's release line + (``3.3-rc.2`` for ``3.3``, never ``3.4`` or ``3.3-beta.1`` for + ``3.2``) that the SDK does not already serve; targets must be + native releases in ``supported_versions``. The SDK's built-in aliases + (``3.2-rc.7``, and ``3.3-rc.3`` until 11.0) need no entry. response_enhancer: Optional server-wide :data:`~adcp.server.ResponseEnhancer` applied to framework-tool successes, custom-tool successes, the pre-auth @@ -1446,6 +1492,7 @@ async def force_account_status(self, account_id, status): pre_validation_hooks = config.pre_validation_hooks response_enhancer = config.response_enhancer supported_versions = config.supported_versions + version_aliases = config.version_aliases enable_debug_endpoints = config.enable_debug_endpoints debug_traffic_source = config.debug_traffic_source session_count_source = config.session_count_source @@ -1492,6 +1539,7 @@ async def force_account_status(self, account_id, status): supported_versions, handler=handler, adcp_version=_resolve_handler_adcp_version(handler, None), + version_aliases=version_aliases, ) # AdCP 3.3 ``adcp.implementation``: report this SDK and the components @@ -2923,6 +2971,7 @@ def create_mcp_server( allowed_origins: Sequence[str] | None = None, enable_dns_rebinding_protection: bool | None = None, host_validator: HostValidator | None = None, + version_aliases: Mapping[str, str] | None = None, ) -> Any: """Create a FastMCP server from an ADCP handler without starting it. @@ -3094,6 +3143,7 @@ def create_mcp_server( supported_versions, handler=handler, adcp_version=_resolve_handler_adcp_version(handler, None), + version_aliases=version_aliases, ) resolved_port = port or int(os.environ.get("PORT", "3001")) # Intentional server default, configurable by argument or deployment env. @@ -3427,7 +3477,7 @@ def _register_handler_tools( description = tool_def.get("description", "") input_schema = tool_def.get("inputSchema", {"type": "object", "properties": {}}) output_schema = tool_def.get("outputSchema") - hook = (pre_validation_hooks or {}).get(tool_name) + hook = pre_validation_hooks_for_tool(pre_validation_hooks, tool_name) caller = create_tool_caller( handler, tool_name, diff --git a/src/adcp/server/version_policy.py b/src/adcp/server/version_policy.py index 09eb63a7a..f5d10da77 100644 --- a/src/adcp/server/version_policy.py +++ b/src/adcp/server/version_policy.py @@ -2,14 +2,86 @@ from __future__ import annotations -from collections.abc import Sequence +from collections.abc import Iterable, Mapping, Sequence from typing import Any -from adcp._version import normalize_to_release_precision, resolve_adcp_version_alias +from adcp._version import ( + _ADCP_VERSION_ALIASES, + ADCP_MAJOR_VERSION, + normalize_to_release_precision, + parse_adcp_major_version, + resolve_adcp_version_alias, +) from adcp.exceptions import ConfigurationError -from adcp.validation.envelope import SUPPORTED_WIRE_VERSIONS +from adcp.validation.envelope import SUPPORTED_WIRE_VERSIONS, served_version_aliases from adcp.validation.schema_loader import list_validator_keys +VersionAliases = Mapping[str, str] +"""``serve(version_aliases=...)``: extra wire version -> the release served for it.""" + + +class ServedVersions(tuple[str, ...]): + """A server's frozen served-version selection and its wire aliases. + + It is the tuple of wire versions the server accepts, alias keys + included, so it travels wherever ``supported_versions`` does. The + server's own alias map is :attr:`aliases`. :attr:`explicit` is ``False`` + when the adopter passed ``version_aliases`` without ``supported_versions``: + the server then serves the SDK default set plus the aliases, and keeps + the default behavior wherever an explicit selection changes it (the + handler's release and the advertised version list). + + Build it with :func:`resolve_supported_versions`; the constructor does + not validate. + """ + + _aliases: tuple[tuple[str, str], ...] + explicit: bool + + def __new__( + cls, + versions: Iterable[str], + *, + aliases: Mapping[str, str] | None = None, + explicit: bool = True, + ) -> ServedVersions: + self = super().__new__(cls, versions) + self._aliases = tuple((aliases or {}).items()) + self.explicit = explicit + return self + + @property + def aliases(self) -> dict[str, str]: + """This server's ``version_aliases`` (a copy): alias -> target release.""" + return dict(self._aliases) + + def __repr__(self) -> str: + return ( + f"ServedVersions({tuple(self)!r}, aliases={self.aliases!r}, " + f"explicit={self.explicit!r})" + ) + + +def explicit_selection(supported_versions: Sequence[str] | None) -> Sequence[str] | None: + """The adopter's explicit selection, or ``None`` for the SDK default set. + + A :class:`ServedVersions` built only from ``version_aliases`` is the + default set plus aliases; code whose behavior depends on an explicit + choice (the handler's release, the advertised version list) treats it + as no selection. + """ + if isinstance(supported_versions, ServedVersions) and not supported_versions.explicit: + return None + return supported_versions + + +def served_versions_list(supported_versions: Sequence[str] | None) -> list[str]: + """Every wire version the server accepts, aliases included. + + This is what ``VERSION_UNSUPPORTED`` reports in ``details.supported_versions``. + """ + return list(SUPPORTED_WIRE_VERSIONS if supported_versions is None else supported_versions) + def default_adcp_version( adcp_version: str | None, supported_versions: Sequence[str] | None @@ -22,6 +94,7 @@ def default_adcp_version( while the SDK's own default pin is a newer line. ``None`` keeps the SDK default when nothing is restricted. """ + supported_versions = explicit_selection(supported_versions) if adcp_version is not None or not supported_versions: return adcp_version from adcp._version import is_adcp_version_at_least, resolve_adcp_version @@ -106,28 +179,74 @@ def resolve_supported_versions( *, handler: Any = None, adcp_version: str | None = None, + version_aliases: VersionAliases | None = None, ) -> tuple[str, ...] | None: """Freeze an explicit selection, checking routing, bundles and trusted pin. A handler created by Decisioning composition carries its selection to subsequent transport factories. Ordinary handlers retain the SDK defaults when no selection is supplied. The handler is never mutated here. + + ``version_aliases`` maps extra wire versions to a release this server + serves (``{"3.3-rc.3": "3.3"}``). The result is then a + :class:`ServedVersions` listing the selection (or the SDK default set) + followed by the alias keys. A request claiming an alias is routed, + validated and handled as its target release. Each key must be a + release-precision prerelease of its target's own release line + (``3.3-rc.3`` for ``3.3``) that the SDK does not already serve + natively; each target must be a native 3.x release in the selection. + A built-in alias may be restated with its own target. + + Passing a :class:`ServedVersions` back returns it unchanged, or merged + with any further ``version_aliases``. """ if supported_versions is None: supported_versions = getattr(handler, "_supported_adcp_versions", None) - if supported_versions is None: - return None - if isinstance(supported_versions, (str, bytes)) or not isinstance(supported_versions, Sequence): - raise ConfigurationError("supported_versions must be a non-empty sequence of wire versions") - versions = tuple(supported_versions) - if not versions or any(not isinstance(version, str) for version in versions): - raise ConfigurationError("supported_versions must be a non-empty sequence of wire versions") - versions = tuple(dict.fromkeys(versions)) + inherited: dict[str, str] = {} + selection: tuple[str, ...] | None = None + if isinstance(supported_versions, ServedVersions): + if not version_aliases: + return supported_versions + inherited = supported_versions.aliases + if supported_versions.explicit: + selection = tuple(supported_versions) + elif supported_versions is not None: + if isinstance(supported_versions, (str, bytes)) or not isinstance( + supported_versions, Sequence + ): + raise ConfigurationError( + "supported_versions must be a non-empty sequence of wire versions" + ) + selection = tuple(supported_versions) + if not selection or any(not isinstance(version, str) for version in selection): + raise ConfigurationError( + "supported_versions must be a non-empty sequence of wire versions" + ) + selection = tuple(dict.fromkeys(selection)) + added = _check_alias_mapping(version_aliases) if version_aliases else {} + # Restating a built-in alias with its own target selects it natively. + builtin = [alias for alias in added if alias in _ADCP_VERSION_ALIASES] + aliases = {**inherited, **{key: value for key, value in added.items() if key not in builtin}} + if selection is not None: + selection = (*selection, *(alias for alias in builtin if alias not in selection)) + if not aliases: + if selection is None: + return None + _check_native_selection(selection) + _check_pin_in_selection(selection, adcp_version, aliases=None) + return selection + # An alias key listed in supported_versions is served through its alias. + base = None if selection is None else tuple(v for v in selection if v not in aliases) + return _build_served_versions(base, aliases, adcp_version=adcp_version, order=selection) + + +def _check_native_selection(versions: tuple[str, ...]) -> None: unsupported = [version for version in versions if version not in SUPPORTED_WIRE_VERSIONS] if unsupported: raise ConfigurationError( f"supported_versions contains unsupported wire versions {unsupported!r}; " - f"choose from {list(SUPPORTED_WIRE_VERSIONS)!r}" + f"choose from {list(SUPPORTED_WIRE_VERSIONS)!r}, or serve another wire " + "version as an alias of one of them with version_aliases=" ) unavailable = [] for version in versions: @@ -140,18 +259,117 @@ def resolve_supported_versions( raise ConfigurationError( f"supported_versions requires installed schema bundles for {unavailable!r}" ) - if adcp_version is not None: + + +def _check_pin_in_selection( + versions: tuple[str, ...], adcp_version: str | None, *, aliases: Mapping[str, str] | None +) -> None: + if adcp_version is None: + return + try: + pin = resolve_adcp_version_alias(normalize_to_release_precision(adcp_version), aliases) + except ValueError as exc: + raise ConfigurationError(f"adcp_version={adcp_version!r} is not a valid version") from exc + if pin not in {resolve_adcp_version_alias(version, aliases) for version in versions}: + raise ConfigurationError( + f"adcp_version={adcp_version!r} is outside supported_versions={list(versions)!r}" + ) + + +def _check_alias_mapping(version_aliases: VersionAliases) -> dict[str, str]: + """Shape-check ``version_aliases``; targets are checked against the selection.""" + if not isinstance(version_aliases, Mapping): + raise ConfigurationError( + "version_aliases must be a mapping of wire version to served release, " + 'e.g. {"3.3-rc.3": "3.3"}' + ) + from adcp.compat.legacy import LEGACY_ADAPTER_VERSIONS + + checked: dict[str, str] = {} + for alias, target in version_aliases.items(): + if not isinstance(alias, str) or not isinstance(target, str): + raise ConfigurationError("version_aliases keys and values must be strings") try: - pin = resolve_adcp_version_alias(normalize_to_release_precision(adcp_version)) - except ValueError as exc: + normalized = normalize_to_release_precision(alias) + major = parse_adcp_major_version(alias) + except ValueError: + raise ConfigurationError( + f"version_aliases key {alias!r} is not a valid AdCP version" + ) from None + if normalized != alias: + raise ConfigurationError( + f"version_aliases key {alias!r} must be release precision ({normalized!r}): " + "buyers' claims are normalized to release precision before lookup" + ) + if major != ADCP_MAJOR_VERSION: + raise ConfigurationError( + f"version_aliases key {alias!r} targets major {major}; this SDK serves " + f"AdCP {ADCP_MAJOR_VERSION}.x and cannot alias another major" + ) + builtin = _ADCP_VERSION_ALIASES.get(alias) + if builtin is not None and builtin != target: + raise ConfigurationError( + f"version_aliases key {alias!r} is a built-in alias of {builtin!r}; " + f"it cannot be served as {target!r}" + ) + if builtin is None and ( + alias in SUPPORTED_WIRE_VERSIONS or alias in LEGACY_ADAPTER_VERSIONS + ): raise ConfigurationError( - f"adcp_version={adcp_version!r} is not a valid version" - ) from exc - if pin not in {resolve_adcp_version_alias(version) for version in versions}: + f"version_aliases key {alias!r} is a release this SDK serves natively; " + "select it with supported_versions instead" + ) + release_line = target.split("-", 1)[0] + if "-" not in alias or alias.split("-", 1)[0] != release_line: + # A stable key (3.4) or another line's prerelease (3.3-beta.1 for + # 3.2) would advertise a release the server does not serve and + # break the spec's downshift to the highest supported release. raise ConfigurationError( - f"adcp_version={adcp_version!r} is outside supported_versions={list(versions)!r}" + f"version_aliases key {alias!r} must be a prerelease of its target's " + f"release line, e.g. {release_line + '-rc.1'!r} for {target!r}" ) - return versions + checked[alias] = target + return checked + + +def _build_served_versions( + base: tuple[str, ...] | None, + aliases: dict[str, str], + *, + adcp_version: str | None, + order: tuple[str, ...] | None = None, +) -> ServedVersions: + """Combine a native selection (``None``: the SDK default) with its aliases.""" + from adcp.compat.legacy import LEGACY_ADAPTER_VERSIONS + + explicit = base is not None + if base is not None: + if not base: + raise ConfigurationError( + "supported_versions must list at least one natively served release " + "besides its version_aliases keys" + ) + _check_native_selection(base) + native = base if base is not None else SUPPORTED_WIRE_VERSIONS + targets = [ + version + for version in native + if version not in LEGACY_ADAPTER_VERSIONS + and resolve_adcp_version_alias(version) == version + and version not in aliases + ] + for alias, target in aliases.items(): + if target not in targets: + raise ConfigurationError( + f"version_aliases maps {alias!r} to {target!r}, which this server does not " + f"serve natively; choose a target from {targets!r}" + ) + served = list(order if order is not None else native) + served.extend(alias for alias in aliases if alias not in served) + selection = ServedVersions(served, aliases=aliases, explicit=explicit) + if explicit: + _check_pin_in_selection(tuple(selection), adcp_version, aliases=aliases) + return selection def enforce_selected_version( @@ -169,11 +387,14 @@ def enforce_selected_version( from adcp.types import Error from adcp.validation.envelope import UnsupportedVersionError, detect_wire_version + aliases = served_version_aliases(supported_versions) try: version = detect_wire_version(payload, supported=supported_versions) version = version or default or resolve_adcp_version(None) - version = resolve_adcp_version_alias(normalize_to_release_precision(version)) - if version not in {resolve_adcp_version_alias(value) for value in supported_versions}: + version = resolve_adcp_version_alias(normalize_to_release_precision(version), aliases) + if version not in { + resolve_adcp_version_alias(value, aliases) for value in supported_versions + }: raise UnsupportedVersionError(version, supported_versions) except UnsupportedVersionError as exc: raise ADCPTaskError( @@ -184,7 +405,7 @@ def enforce_selected_version( message=str(exc), details={ "claimed_version": exc.wire_value, - "supported_versions": list(exc.supported), + "supported_versions": served_versions_list(supported_versions), }, ) ], @@ -195,9 +416,31 @@ def enforce_selected_version( def project_supported_versions( response: dict[str, Any], supported_versions: tuple[str, ...] | None ) -> dict[str, Any]: - """Copy capability metadata to match this server's accepted wire versions.""" + """Copy capability metadata to match this server's accepted wire versions. + + An explicit selection replaces ``adcp.supported_versions`` (aliases + included). Aliases served on the SDK default set are appended to the + handler's own list, each only while its target is advertised. + """ if supported_versions is None: return response + if explicit_selection(supported_versions) is None: + adcp_block = response.get("adcp") + if not isinstance(adcp_block, dict): + return response + advertised = adcp_block.get("supported_versions") + if not isinstance(advertised, list): + return response + extra = [ + alias + for alias, target in served_version_aliases(supported_versions).items() + if target in advertised and alias not in advertised + ] + if not extra: + return response + projected = dict(response) + projected["adcp"] = {**adcp_block, "supported_versions": [*advertised, *extra]} + return projected projected = dict(response) adcp = dict(response.get("adcp") or {}) adcp["supported_versions"] = list(supported_versions) diff --git a/src/adcp/testing/decisioning.py b/src/adcp/testing/decisioning.py index a90a38741..0537ad857 100644 --- a/src/adcp/testing/decisioning.py +++ b/src/adcp/testing/decisioning.py @@ -171,6 +171,7 @@ def build_asgi_app( mcp_result_text: MCPResultText | None = None, on_startup: Sequence[LifespanHook] | None = None, on_shutdown: Sequence[LifespanHook] | None = None, + version_aliases: Mapping[str, str] | None = None, **factory_kwargs: Any, ) -> Any: """Build a Starlette ASGI app for in-process integration tests. @@ -275,6 +276,9 @@ def build_asgi_app( :func:`create_mcp_server`, so in-process tests exercise the same enhancer wiring your production :func:`serve` call uses. ``None`` → no enhancer (default). + :param version_aliases: Extra wire versions served as one of the + server's releases, as :func:`adcp.server.serve`'s + ``version_aliases``. ``None`` → built-in aliases only (default). :param on_startup: Async zero-argument hooks run after the MCP and A2A framework lifespans start. Requires ``transport="both"``. :param on_shutdown: Async zero-argument hooks run before the MCP and A2A @@ -340,6 +344,17 @@ def build_asgi_app( supported_versions=supported_versions, **factory_kwargs, ) + from adcp.server.mcp_tools import _resolve_handler_adcp_version + from adcp.server.version_policy import resolve_supported_versions + + # Fold in the server-level aliases once for every transport below, and + # check the handler's pin against the result exactly as serve() does. + supported_versions = resolve_supported_versions( + supported_versions, + handler=handler, + adcp_version=_resolve_handler_adcp_version(handler, None), + version_aliases=version_aliases, + ) server_name = name or type(platform).__name__ if transport == "both": # TODO(#1047): expose A2A-only message_parser/public_url and task / @@ -478,6 +493,7 @@ async def build_test_client( mcp_result_text: MCPResultText | None = None, on_startup: Sequence[LifespanHook] | None = None, on_shutdown: Sequence[LifespanHook] | None = None, + version_aliases: Mapping[str, str] | None = None, **factory_kwargs: Any, ) -> AsyncIterator[httpx.AsyncClient]: """Async context manager yielding an ``httpx.AsyncClient`` wired against @@ -539,6 +555,7 @@ async def build_test_client( Pass ``base_url`` here if your tests exercise ``/.well-known/adcp-agents.json``. :param pre_validation_hooks: Forwarded to :func:`build_asgi_app`. + :param version_aliases: Forwarded to :func:`build_asgi_app`. Install the same hooks your production :func:`serve` call uses so in-process tests see the same validation surface. :param response_enhancer: Forwarded to :func:`build_asgi_app`. Wire @@ -612,6 +629,7 @@ async def build_test_client( mcp_result_text=mcp_result_text, on_startup=on_startup, on_shutdown=on_shutdown, + version_aliases=version_aliases, **factory_kwargs, ) async with LifespanManager(app): diff --git a/src/adcp/validation/envelope.py b/src/adcp/validation/envelope.py index 8f79f3a6d..aad844315 100644 --- a/src/adcp/validation/envelope.py +++ b/src/adcp/validation/envelope.py @@ -21,6 +21,7 @@ from __future__ import annotations +from collections.abc import Mapping, Sequence from typing import Any from adcp._version import ( @@ -55,6 +56,17 @@ DEFAULT_UNNEGOTIATED_ADCP_VERSION = "3.0" +def served_version_aliases(supported: Sequence[str] | None) -> Mapping[str, str]: + """The per-server wire aliases a served-version selection carries. + + :class:`adcp.server.version_policy.ServedVersions` (what ``serve()`` + builds from ``version_aliases=``) exposes its alias map as ``aliases``; + a plain sequence carries none, so only the SDK's built-in aliases apply. + """ + aliases = getattr(supported, "aliases", None) + return aliases if isinstance(aliases, Mapping) else {} + + class UnsupportedVersionError(ValueError): """The wire version the buyer claims isn't supported by this server. @@ -83,7 +95,9 @@ def detect_wire_version( 1. ``payload['adcp_version']`` — string, normalized to release precision (``"3.0.7"`` → ``"3.0"``). Must be in ``supported`` or raises :class:`UnsupportedVersionError`. The explicit ``3.2-rc.7`` - compatibility alias resolves to ``3.2``. + and ``3.3-rc.3`` compatibility aliases resolve to ``3.2`` and + ``3.3``, as do the server's own ``version_aliases`` when + ``supported`` carries them. 2. ``payload['adcp_major_version']`` — int. Prefer ``MAJOR.0`` when supported because this legacy field predates release-precision negotiation and the 3.1 response envelope split. If ``MAJOR.0`` is @@ -108,7 +122,7 @@ def detect_wire_version( raise UnsupportedVersionError(explicit, supported) from exc if normalized not in supported: raise UnsupportedVersionError(explicit, supported) - return resolve_adcp_version_alias(normalized) + return resolve_adcp_version_alias(normalized, served_version_aliases(supported)) # Empty-string ``adcp_version`` falls through to ``adcp_major_version`` # intentionally — pre-3.1 buyers may set both fields, and an empty # string from a half-migrated client shouldn't override the int field. @@ -138,7 +152,8 @@ def detect_wire_version( return base_minor # Otherwise fall back to the highest supported minor for this major. return resolve_adcp_version_alias( - max(candidates, key=lambda v: int(v.split(".")[1].split("-")[0])) + max(candidates, key=lambda v: int(v.split(".")[1].split("-")[0])), + served_version_aliases(supported), ) return None @@ -182,4 +197,4 @@ def resolve_requested_adcp_version( return resolved if default not in supported: raise UnsupportedVersionError(default, supported) - return resolve_adcp_version_alias(default) + return resolve_adcp_version_alias(default, served_version_aliases(supported)) diff --git a/src/adcp/validation/schema_validator.py b/src/adcp/validation/schema_validator.py index bf10cd0e0..077ec1751 100644 --- a/src/adcp/validation/schema_validator.py +++ b/src/adcp/validation/schema_validator.py @@ -18,6 +18,7 @@ import re from dataclasses import dataclass, field +from functools import lru_cache from itertools import islice from typing import Any, Literal @@ -540,6 +541,102 @@ def validate_response( ) +def response_admits_property( + tool_name: str, + payload: Any, + name: str, + *, + version: str | None = None, +) -> bool: + """Whether ``version``'s response schema lets ``payload`` carry ``name``. + + The response variant is selected from ``payload`` as + :func:`validate_response` selects it. The answer is structural and + conservative: ``False`` when any object schema the root composes + (``$ref``, ``allOf``, ``anyOf``, ``oneOf``, ``then``, ``else``) is closed + (``additionalProperties: false`` or ``unevaluatedProperties: false``) + without declaring ``name``, declares ``name`` as ``false``, or forbids it + through ``not: {required: [name]}``. A tool with no shipped schema admits + any property. The server uses this before echoing ``adcp_version`` into a + response, so it never stamps a field the served release forbids. + """ + variant: Direction = _select_response_variant(_as_wire_payload(payload)) + return _schema_admits_top_level_property(tool_name, variant, version, name) + + +@lru_cache(maxsize=1024) +def _schema_admits_top_level_property( + tool_name: str, variant: Direction, version: str | None, name: str +) -> bool: + from adcp.validation.schema_loader import get_portable_schema + + schema = get_portable_schema(tool_name, variant, version=version) + if schema is None and variant != "sync": + schema = get_portable_schema(tool_name, "sync", version=version) + if schema is None: + return True + return _object_schema_admits(schema, schema, name, frozenset(), 0) + + +def _object_schema_admits( + node: Any, root: dict[str, Any], name: str, seen: frozenset[str], depth: int +) -> bool: + if not isinstance(node, dict): + # A boolean subschema accepts or refuses the whole payload; it says + # nothing about one property. + return True + if depth > 32: + return False + ref = node.get("$ref") + if isinstance(ref, str): + if ref in seen: + return True + target = _resolve_local_ref(root, ref) + if target is None or not _object_schema_admits(target, root, name, seen | {ref}, depth + 1): + # A reference the portable schema cannot resolve is treated as + # forbidding: the caller only adds an optional field. + return False + properties = node.get("properties") + declared = isinstance(properties, dict) and name in properties + if isinstance(properties, dict) and properties.get(name) is False: + return False + if not declared and not node.get("patternProperties"): + if node.get("additionalProperties") is False or node.get("unevaluatedProperties") is False: + return False + negated = node.get("not") + if isinstance(negated, dict): + required = negated.get("required") + if isinstance(required, list) and required == [name]: + return False + for keyword in ("allOf", "anyOf", "oneOf"): + branches = node.get(keyword) + if isinstance(branches, list): + for branch in branches: + if not _object_schema_admits(branch, root, name, seen, depth + 1): + return False + for keyword in ("then", "else"): + if keyword in node and not _object_schema_admits( + node[keyword], root, name, seen, depth + 1 + ): + return False + return True + + +def _resolve_local_ref(root: dict[str, Any], ref: str) -> Any: + if not ref.startswith("#"): + return None + node: Any = root + for token in ref[1:].split("/")[1:] if ref != "#" else []: + token = token.replace("~1", "/").replace("~0", "~") + if isinstance(node, dict) and token in node: + node = node[token] + elif isinstance(node, list) and token.isdigit() and int(token) < len(node): + node = node[int(token)] + else: + return None + return node + + def format_issues(issues: list[ValidationIssue], limit: int = 3) -> str: """Render a compact one-line summary of failures — useful for logs. diff --git a/tests/test_adcp_3_3_0_adoption.py b/tests/test_adcp_3_3_0_adoption.py index 0940ee968..e30380a99 100644 --- a/tests/test_adcp_3_3_0_adoption.py +++ b/tests/test_adcp_3_3_0_adoption.py @@ -66,6 +66,8 @@ def test_current_pin_and_historical_roots(): "3.2", WIRE_VERSION, "3.2-rc.7", + # Built-in bridge for 3.3 release-candidate peers (adcp#9223); removed in 11.0. + "3.3-rc.3", } assert resolve_adcp_version("3.3.0") == WIRE_VERSION assert schema_loader._resolve_schema_root(BUNDLE_KEY) is not None @@ -91,11 +93,11 @@ def test_current_pin_and_historical_roots(): "3.3.0-beta.6", "3.3-rc.0", "3.3.0-rc.0", - "3.3-rc.3", - "3.3.0-rc.3", ): with pytest.raises(ConfigurationError): resolve_adcp_version(previous) + # rc.3 is served as the stable 3.3 contract; its archival root stays exact. + assert resolve_adcp_version("3.3-rc.3") == resolve_adcp_version("3.3.0-rc.3") == WIRE_VERSION for previous in ( "3.3-beta.0", "3.3-beta.1", @@ -105,7 +107,6 @@ def test_current_pin_and_historical_roots(): "3.3-beta.5", "3.3-beta.6", "3.3-rc.0", - "3.3-rc.3", ): assert previous not in get_supported_adcp_versions() assert schema_loader._resolve_schema_root("3.3.0-beta.1") is not None @@ -279,11 +280,13 @@ def test_postal_area_arms_keep_their_names(): assert postal_area.PostalArea2 is not None -def test_a_peer_on_the_3_3_release_candidate_negotiates_down_to_3_2(): +def test_a_peer_on_the_3_3_release_candidate_negotiates_its_rc3_alias(): + """An rc.3 seller is spoken to as 3.3 under its own advertised alias (adcp#9223).""" from adcp.compat.versions import negotiate_version - assert negotiate_version(["3.3-rc.3", "3.2"], maximum=WIRE_VERSION) == "3.2" - assert negotiate_version(["3.3", "3.2"], maximum=WIRE_VERSION) == WIRE_VERSION + assert negotiate_version(["3.3-rc.3", "3.2"], maximum=WIRE_VERSION) == "3.3-rc.3" + assert negotiate_version(["3.3-rc.0", "3.2"], maximum=WIRE_VERSION) == "3.2" + assert negotiate_version(["3.3", "3.3-rc.3", "3.2"], maximum=WIRE_VERSION) == WIRE_VERSION def test_ga_bounds_new_and_experimental_fields(): diff --git a/tests/test_reporting_subscription_coverage.py b/tests/test_reporting_subscription_coverage.py index a46d74f38..e5ac0f27e 100644 --- a/tests/test_reporting_subscription_coverage.py +++ b/tests/test_reporting_subscription_coverage.py @@ -1759,15 +1759,17 @@ def test_utc_alignment_is_unchanged(self) -> None: def test_a_bare_3_3_version_is_served_once_the_ga_bundle_is_pinned() -> None: # The gate serves 3.3 the adcp#8585 fields. A bare "3.3" was refused while a - # 3.3 prerelease bundle was pinned; the 3.3.0 GA pin serves it, and refuses - # the release candidate it replaced. + # 3.3 prerelease bundle was pinned; the 3.3.0 GA pin serves it, serves the + # last release candidate as its deprecated alias (adcp#9223), and refuses + # the earlier release candidates. from adcp._version import get_supported_adcp_versions, resolve_adcp_version from adcp.exceptions import ConfigurationError assert resolve_adcp_version("3.3") == "3.3" assert "3.3" in get_supported_adcp_versions() + assert resolve_adcp_version("3.3-rc.3") == "3.3" with pytest.raises(ConfigurationError): - resolve_adcp_version("3.3-rc.3") + resolve_adcp_version("3.3-rc.0") # -- the budget ---------------------------------------------------------------- diff --git a/tests/test_response_version_echo.py b/tests/test_response_version_echo.py new file mode 100644 index 000000000..392859e32 --- /dev/null +++ b/tests/test_response_version_echo.py @@ -0,0 +1,113 @@ +"""The response ``adcp_version`` echo never stamps a field the served schema forbids (#2007).""" + +from __future__ import annotations + +from typing import Any + +import pytest + +from adcp.server import ADCPHandler, ToolContext +from adcp.server.mcp_tools import create_tool_caller +from adcp.validation import ValidationHookConfig +from adcp.validation.schema_validator import response_admits_property + +STRICT = ValidationHookConfig(requests="strict", responses="strict") +RESPONSES_ONLY = ValidationHookConfig(requests="off", responses="strict") +REQUEST = {"buying_mode": "brief", "brief": "sports"} + + +class CompactSeller(ADCPHandler[ToolContext]): + advertised_tools = {"get_products", "list_products", "buy_products", "control_media_buy"} + + def __init__(self) -> None: + self.versions: list[tuple[str, str | None]] = [] + + def _record(self, tool: str, context: ToolContext | None) -> None: + assert context is not None + self.versions.append((tool, context.resolved_adcp_version)) + + async def get_products(self, params: Any, context: ToolContext | None = None) -> Any: + self._record("get_products", context) + return {"products": [], "cache_scope": "public"} + + async def list_products(self, params: Any, context: ToolContext | None = None) -> Any: + self._record("list_products", context) + return { + "outcome": "listed", + "products": [], + "feed_version": "feed-1", + "cache_scope": "public", + } + + async def buy_products(self, params: Any, context: ToolContext | None = None) -> Any: + self._record("buy_products", context) + return { + "status": "failed", + "errors": [{"code": "PRODUCT_UNAVAILABLE", "message": "sold out"}], + } + + async def control_media_buy(self, params: Any, context: ToolContext | None = None) -> Any: + self._record("control_media_buy", context) + return {"status": "completed", "media_buy_id": "mb-1", "revision": 1} + + +@pytest.mark.parametrize("tool", ["list_products", "buy_products", "control_media_buy"]) +async def test_rc7_echo_never_stamps_a_closed_3_2_response(tool: str) -> None: + """Compact 3.2 roots are closed and declare no ``adcp_version``.""" + seller = CompactSeller() + caller = create_tool_caller(seller, tool, validation=RESPONSES_ONLY) + response = await caller({"adcp_version": "3.2-rc.7"}) + assert "adcp_version" not in response + assert seller.versions == [(tool, "3.2")] + + +async def test_rc7_echo_is_kept_where_the_3_2_schema_admits_it() -> None: + seller = CompactSeller() + caller = create_tool_caller(seller, "get_products", validation=STRICT) + response = await caller({**REQUEST, "adcp_version": "3.2-rc.7"}) + assert response["adcp_version"] == "3.2-rc.7" + + +async def test_alias_echo_uses_the_callers_claim_not_a_hook_rewrite() -> None: + caller = create_tool_caller( + CompactSeller(), + "get_products", + validation=STRICT, + pre_validation_hook=lambda tool, args: {**args, "adcp_version": "3.2"}, + ) + response = await caller({**REQUEST, "adcp_version": "3.2-rc.7"}) + assert response["adcp_version"] == "3.2-rc.7" + + +async def test_native_claims_get_no_alias_echo() -> None: + caller = create_tool_caller(CompactSeller(), "get_products", validation=STRICT) + assert "adcp_version" not in await caller({**REQUEST, "adcp_version": "3.3"}) + # A converted response carries the release it was served as. + assert (await caller({**REQUEST, "adcp_version": "3.2"}))["adcp_version"] == "3.2" + + +@pytest.mark.parametrize( + "tool,payload", + [ + ("list_products", {"outcome": "listed", "products": [], "feed_version": "f"}), + ("buy_products", {"status": "failed", "errors": []}), + ("control_media_buy", {"status": "completed", "media_buy_id": "m", "revision": 1}), + ("accept_proposal", {"status": "completed"}), + ("decline_proposals", {"results": []}), + ], +) +def test_response_admits_property_follows_the_served_schema( + tool: str, payload: dict[str, Any] +) -> None: + assert not response_admits_property(tool, payload, "adcp_version", version="3.2") + assert response_admits_property(tool, payload, "adcp_version", version="3.3") + + +def test_response_admits_property_defaults() -> None: + assert response_admits_property("get_products", {"products": []}, "adcp_version", version="3.2") + # A submitted response is checked against its own variant's schema. + assert response_admits_property( + "create_media_buy", {"status": "submitted", "task_id": "t"}, "adcp_version", version="3.2" + ) + # A tool with no shipped schema admits any property. + assert response_admits_property("not_an_adcp_tool", {}, "adcp_version", version="3.2") diff --git a/tests/test_server_supported_versions.py b/tests/test_server_supported_versions.py index 656616a3a..78851e4fb 100644 --- a/tests/test_server_supported_versions.py +++ b/tests/test_server_supported_versions.py @@ -45,7 +45,7 @@ async def get_adcp_capabilities( @pytest.mark.parametrize( - "selection", [[], "3.2", ["3.3-rc.3"], ["3.2.1"], ["3.2-rc.8"], [None], [{}]] + "selection", [[], "3.2", ["3.3-rc.2"], ["3.2.1"], ["3.2-rc.8"], [None], [{}]] ) @pytest.mark.parametrize("factory", [ServeConfig, create_mcp_server, create_a2a_server, MCPToolSet]) def test_invalid_selections_fail_at_construction(factory: Any, selection: Any) -> None: @@ -282,7 +282,7 @@ def test_decisioning_selection_validates_before_allocating_executor_and_reaches_ serve_module = importlib.import_module("adcp.decisioning.serve") with patch.object(serve_module, "ThreadPoolExecutor") as executor: with pytest.raises(ConfigurationError, match="supported_versions"): - create_adcp_server_from_platform(_BarePlatform(), supported_versions=["3.3-rc.3"]) + create_adcp_server_from_platform(_BarePlatform(), supported_versions=["3.3-rc.2"]) executor.assert_not_called() handler, executor, _ = create_adcp_server_from_platform( _BarePlatform(), supported_versions=["3.2"] diff --git a/tests/test_version_aliases.py b/tests/test_version_aliases.py new file mode 100644 index 000000000..b79dd8b31 --- /dev/null +++ b/tests/test_version_aliases.py @@ -0,0 +1,648 @@ +"""Per-server wire version aliases, the built-in 3.3-rc.3 alias, and the echo rule. + +Covers ``serve(version_aliases=...)`` and the built-in ``3.3-rc.3`` alias +(#2009), ``VERSION_UNSUPPORTED`` details and the pre-validation hook contract +(#2008): the ``"*"`` hook and middleware ordering. The echo rule itself is +pinned in ``test_response_version_echo.py`` (#2007). +""" + +from __future__ import annotations + +import importlib +import json +from typing import Any +from unittest.mock import patch + +import pytest +from starlette.testclient import TestClient + +from adcp._version import get_supported_adcp_versions +from adcp.exceptions import ADCPTaskError, ConfigurationError +from adcp.server import ( + GLOBAL_PRE_VALIDATION_HOOK_KEY, + ADCPHandler, + ServeConfig, + ToolContext, + compose_pre_validation_hooks, + create_a2a_server, + create_mcp_server, +) +from adcp.server.a2a_server import ADCPAgentExecutor +from adcp.server.mcp_tools import MCPToolSet, create_mcp_tools, create_tool_caller +from adcp.server.responses import capabilities_response +from adcp.server.version_policy import ServedVersions, resolve_supported_versions +from adcp.validation import ValidationHookConfig, get_validator +from adcp.validation.envelope import detect_wire_version + +STRICT = ValidationHookConfig(requests="strict", responses="strict") +RESPONSES_ONLY = ValidationHookConfig(requests="off", responses="strict") +REQUEST = {"buying_mode": "brief", "brief": "sports"} +NO_IDEMPOTENCY = {"supported": False} + + +class AliasSeller(ADCPHandler[ToolContext]): + advertised_tools = { + "get_products", + "get_adcp_capabilities", + "get_task_status", + "list_products", + "buy_products", + "control_media_buy", + } + + def __init__(self) -> None: + self.versions: list[tuple[str, str | None, str | None]] = [] + self.capabilities = capabilities_response(["media_buy"], idempotency=NO_IDEMPOTENCY) + + def _record(self, tool: str, context: ToolContext | None) -> None: + assert context is not None + self.versions.append( + (tool, context.resolved_adcp_version, context.application_adcp_version) + ) + + async def get_products(self, params: Any, context: ToolContext | None = None) -> Any: + self._record("get_products", context) + return {"products": [], "cache_scope": "public"} + + async def get_adcp_capabilities(self, params: Any, context: ToolContext | None = None) -> Any: + return self.capabilities + + async def get_task_status(self, params: Any, context: ToolContext | None = None) -> Any: + self._record("get_task_status", context) + return { + "task_id": "task_1", + "task_type": "get_products", + "protocol": "media-buy", + "status": "completed", + "created_at": "2026-01-01T00:00:00Z", + "updated_at": "2026-01-01T00:00:00Z", + } + + async def list_products(self, params: Any, context: ToolContext | None = None) -> Any: + self._record("list_products", context) + return { + "outcome": "listed", + "products": [], + "feed_version": "feed-1", + "cache_scope": "public", + } + + async def buy_products(self, params: Any, context: ToolContext | None = None) -> Any: + self._record("buy_products", context) + return { + "status": "failed", + "errors": [{"code": "PRODUCT_UNAVAILABLE", "message": "sold out"}], + } + + async def control_media_buy(self, params: Any, context: ToolContext | None = None) -> Any: + self._record("control_media_buy", context) + return {"status": "completed", "media_buy_id": "mb-1", "revision": 1} + + +# --------------------------------------------------------------------------- +# Built-in 3.3-rc.3 alias (adcontextprotocol/adcp#9223) +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("claim", ["3.3-rc.3", "3.3.0-rc.3"]) +def test_builtin_rc3_alias_resolves_to_stable_and_is_advertised(claim: str) -> None: + assert detect_wire_version({"adcp_version": claim}) == "3.3" + assert "3.3-rc.3" in get_supported_adcp_versions() + assert "3.3-rc.3" in capabilities_response(["media_buy"])["adcp"]["supported_versions"] + aliased = get_validator("get_products", "sync", version="3.3-rc.3") + stable = get_validator("get_products", "sync", version="3.3") + assert aliased is not None and stable is not None + assert aliased.schema == stable.schema + + +async def test_builtin_rc3_request_is_served_and_validated_as_3_3() -> None: + seller = AliasSeller() + caller = create_tool_caller(seller, "get_products", validation=STRICT) + response = await caller({**REQUEST, "adcp_version": "3.3-rc.3"}) + assert seller.versions == [("get_products", "3.3", "3.3")] + assert response["adcp_version"] == "3.3-rc.3" + + +# --------------------------------------------------------------------------- +# serve(version_aliases=...) configuration +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "aliases,match", + [ + ({"3.3": "3.2"}, "serves natively"), + ({"2.5": "3.3"}, "another major"), + ({"3.1-rc.2": "3.1-beta"}, "does not serve natively"), + ({"3.2-rc.9": "3.2-rc.7"}, "does not serve natively"), + ({"3.3-rc.2": "3.3-rc.3"}, "does not serve natively"), + # A key must be a prerelease of its target's own release line. + ({"3.4": "3.3"}, "prerelease of its target's release line"), + ({"3.3-beta.1": "3.2"}, "prerelease of its target's release line"), + ({"3.2-rc.8": "3.3"}, "prerelease of its target's release line"), + ({"3.3-rc.2": "2.5"}, "prerelease of its target's release line"), + ({"4.0-rc.1": "3.3"}, "another major"), + ({"3.3.0-rc.2": "3.3"}, "release precision"), + ({"3.2-rc.7": "3.3"}, "built-in alias"), + ({"not-a-version": "3.3"}, "not a valid AdCP version"), + ({"3.3-rc.2": 3}, "strings"), + (["3.3-rc.2"], "mapping"), + ], +) +@pytest.mark.parametrize( + "factory", + [ + ServeConfig, + create_mcp_server, + create_a2a_server, + MCPToolSet, + create_mcp_tools, + create_tool_caller, + ], +) +def test_invalid_aliases_fail_at_construction(factory: Any, aliases: Any, match: str) -> None: + with pytest.raises(ConfigurationError, match=match): + if factory is ServeConfig: + factory(version_aliases=aliases) + elif factory is create_tool_caller: + factory(AliasSeller(), "get_products", version_aliases=aliases) + else: + factory(AliasSeller(), version_aliases=aliases) + + +def test_alias_target_must_be_in_the_explicit_selection() -> None: + with pytest.raises(ConfigurationError, match=r"choose a target from \['3.2'\]"): + resolve_supported_versions(["3.2"], version_aliases={"3.3-rc.2": "3.3"}) + + +def test_served_set_lists_aliases_after_the_native_selection() -> None: + default = resolve_supported_versions(None, version_aliases={"3.3-rc.2": "3.3"}) + assert isinstance(default, ServedVersions) + assert default.explicit is False + assert default.aliases == {"3.3-rc.2": "3.3"} + assert default[-1] == "3.3-rc.2" and "3.3" in default + explicit = resolve_supported_versions(["3.3"], version_aliases={"3.3-rc.2": "3.3"}) + assert explicit == ("3.3", "3.3-rc.2") + assert isinstance(explicit, ServedVersions) and explicit.explicit + # A served set passes through unchanged and merges further aliases. + assert resolve_supported_versions(explicit) is explicit + merged = resolve_supported_versions(explicit, version_aliases={"3.3-rc.1": "3.3"}) + assert merged == ("3.3", "3.3-rc.2", "3.3-rc.1") + # Restating a built-in alias selects it natively; nothing else changes. + assert resolve_supported_versions(None, version_aliases={"3.3-rc.3": "3.3"}) is None + assert resolve_supported_versions(["3.3"], version_aliases={"3.3-rc.3": "3.3"}) == ( + "3.3", + "3.3-rc.3", + ) + + +def test_serve_and_config_fold_aliases_into_the_served_set() -> None: + serve_module = importlib.import_module("adcp.server.serve") + aliases = {"3.3-rc.2": "3.3"} + config = ServeConfig(supported_versions=["3.3"], version_aliases=aliases) + aliases["3.3-rc.1"] = "3.3" + assert config.version_aliases == {"3.3-rc.2": "3.3"} + for kwargs in ( + {"config": config}, + {"supported_versions": ["3.3"], "version_aliases": {"3.3-rc.2": "3.3"}}, + ): + with patch.object(serve_module, "_serve_mcp") as run: + serve_module.serve(AliasSeller(), **kwargs) + served = run.call_args.kwargs["supported_versions"] + assert served == ("3.3", "3.3-rc.2") + assert served.aliases == {"3.3-rc.2": "3.3"} + + +def test_decisioning_serve_forwards_aliases() -> None: + from adcp.decisioning import serve as decisioning_serve + from tests.test_decisioning_serve import _BarePlatform + + # ``adcp.server.serve`` is also the name of the re-exported function, so + # resolve the submodule explicitly; a dotted patch target picks the + # function on Python 3.10. + serve_module = importlib.import_module("adcp.server.serve") + with patch.object(serve_module, "serve") as run: + decisioning_serve( + _BarePlatform(), version_aliases={"3.3-rc.2": "3.3"}, validate_at_init=False + ) + assert run.call_args.kwargs["version_aliases"] == {"3.3-rc.2": "3.3"} + + +# --------------------------------------------------------------------------- +# Dispatch: routing, validation, echo, VERSION_UNSUPPORTED +# --------------------------------------------------------------------------- + + +async def test_alias_is_routed_validated_and_echoed_as_its_target() -> None: + seller = AliasSeller() + caller = create_tool_caller( + seller, "get_products", validation=STRICT, version_aliases={"3.3-rc.2": "3.3"} + ) + response = await caller({**REQUEST, "adcp_version": "3.3-rc.2"}) + assert seller.versions == [("get_products", "3.3", "3.3")] + assert response["adcp_version"] == "3.3-rc.2" + + +async def test_alias_of_an_older_release_is_converted_and_validated_there() -> None: + seller = AliasSeller() + caller = create_tool_caller( + seller, "get_products", validation=STRICT, version_aliases={"3.2-rc.8": "3.2"} + ) + response = await caller({**REQUEST, "adcp_version": "3.2-rc.8"}) + # The buyer is served 3.2; the handler runs on the SDK's 3.3. + assert seller.versions == [("get_products", "3.2", "3.3")] + assert response["adcp_version"] == "3.2-rc.8" + + +async def test_version_unsupported_reports_the_effective_served_list() -> None: + caller = create_tool_caller(AliasSeller(), "get_products", version_aliases={"3.3-rc.2": "3.3"}) + with pytest.raises(ADCPTaskError) as caught: + await caller({**REQUEST, "adcp_version": "3.3-rc.1"}) + error = caught.value.errors[0] + assert error.code == "VERSION_UNSUPPORTED" + assert error.details["claimed_version"] == "3.3-rc.1" + assert {"3.3", "3.3-rc.3", "3.3-rc.2"} <= set(error.details["supported_versions"]) + + explicit = create_tool_caller( + AliasSeller(), + "get_products", + supported_versions=["3.3"], + version_aliases={"3.3-rc.2": "3.3"}, + ) + for claim in ("3.2", "3.3-rc.1"): + with pytest.raises(ADCPTaskError) as caught: + await explicit({**REQUEST, "adcp_version": claim}) + assert caught.value.errors[0].details == { + "claimed_version": claim, + "supported_versions": ["3.3", "3.3-rc.2"], + } + # An omitted envelope that falls outside the explicit selection reports + # the same served list. + with pytest.raises(ADCPTaskError) as caught: + await explicit(REQUEST) + assert caught.value.errors[0].details["supported_versions"] == ["3.3", "3.3-rc.2"] + + +async def test_alias_echo_uses_the_callers_claim_not_a_hook_rewrite() -> None: + caller = create_tool_caller( + AliasSeller(), + "get_products", + validation=STRICT, + pre_validation_hook=lambda tool, args: {**args, "adcp_version": "3.3"}, + ) + response = await caller({**REQUEST, "adcp_version": "3.3-rc.3"}) + assert response["adcp_version"] == "3.3-rc.3" + + +@pytest.mark.parametrize("tool", ["list_products", "buy_products", "control_media_buy"]) +async def test_rc3_alias_is_echoed_where_the_3_3_schema_admits_it(tool: str) -> None: + """The compact roots closed in 3.2 declare ``adcp_version`` in 3.3.""" + seller = AliasSeller() + response = await create_tool_caller(seller, tool, validation=RESPONSES_ONLY)( + {"adcp_version": "3.3-rc.3"} + ) + assert response["adcp_version"] == "3.3-rc.3" + assert seller.versions == [(tool, "3.3", "3.3")] + + +async def test_task_polling_accepts_the_alias() -> None: + seller = AliasSeller() + tools = MCPToolSet(seller, validation=STRICT, version_aliases={"3.3-rc.2": "3.3"}) + response = await tools.call_tool( + "get_task_status", {"task_id": "task_1", "adcp_version": "3.3-rc.2"} + ) + assert response["status"] == "completed" + assert response["adcp_version"] == "3.3-rc.2" + assert seller.versions == [("get_task_status", "3.3", "3.3")] + + +@pytest.mark.parametrize("leg", ["mcp", "a2a"]) +async def test_test_controller_accepts_the_alias(leg: str) -> None: + from adcp.server.test_controller import TestControllerStore, register_test_controller + + store = TestControllerStore() + aliases = {"3.3-rc.2": "3.3"} + if leg == "mcp": + mcp = create_mcp_server(AliasSeller(), supported_versions=["3.3"], version_aliases=aliases) + register_test_controller(mcp, store) + caller = mcp._tool_manager._tools["comply_test_controller"].fn + else: + executor = ADCPAgentExecutor( + AliasSeller(), + test_controller=store, + supported_versions=["3.3"], + version_aliases=aliases, + ) + caller = executor._tool_callers["comply_test_controller"] + + async def call(params: dict[str, Any]) -> Any: + return await caller(**params) if leg == "mcp" else await caller(params) + + with pytest.raises(ADCPTaskError) as caught: + await call({"scenario": "list_scenarios", "adcp_version": "3.2"}) + assert caught.value.errors[0].details["supported_versions"] == ["3.3", "3.3-rc.2"] + response = await call( + {"scenario": "list_scenarios", "adcp_version": "3.3-rc.2", "account": {"sandbox": True}} + ) + assert response["success"] is True + + +# --------------------------------------------------------------------------- +# Capabilities advertisement +# --------------------------------------------------------------------------- + + +async def test_capabilities_advertise_aliases_on_the_default_set() -> None: + def drop_alias(response: dict[str, Any]) -> None: + versions = response["adcp"]["supported_versions"] + response["adcp"]["supported_versions"] = [v for v in versions if v != "3.3-rc.2"] + + seller = AliasSeller() + original = list(seller.capabilities["adcp"]["supported_versions"]) + caller = create_tool_caller( + seller, + "get_adcp_capabilities", + validation=STRICT, + version_aliases={"3.3-rc.2": "3.3", "3.2-rc.8": "3.2"}, + # The SDK re-applies its projection after the seller's enhancer. + response_enhancer=drop_alias, + ) + response = await caller({"adcp_version": "3.3"}) + # The enhancer dropped 3.3-rc.2 after the first projection; the second + # projection appends it again. + assert response["adcp"]["supported_versions"] == [*original, "3.2-rc.8", "3.3-rc.2"] + assert seller.capabilities["adcp"]["supported_versions"] == original + + # An alias is advertised only while the handler advertises its target. + seller.capabilities = capabilities_response( + ["media_buy"], supported_versions=["3.3"], idempotency=NO_IDEMPOTENCY + ) + response = await caller({"adcp_version": "3.3"}) + assert response["adcp"]["supported_versions"] == ["3.3", "3.3-rc.2"] + + +async def test_capabilities_advertise_aliases_in_an_explicit_selection() -> None: + tools = MCPToolSet( + AliasSeller(), + validation=STRICT, + supported_versions=["3.2", "3.3"], + version_aliases={"3.3-rc.2": "3.3"}, + ) + response = await tools.call_tool("get_adcp_capabilities", {"adcp_version": "3.3-rc.2"}) + assert response["adcp"]["supported_versions"] == ["3.2", "3.3", "3.3-rc.2"] + assert response["adcp"]["major_versions"] == [3] + assert response["adcp_version"] == "3.3-rc.2" + + +# --------------------------------------------------------------------------- +# Public transports, MCP and A2A +# --------------------------------------------------------------------------- + + +def _call(client: TestClient, leg: str, tool: str, params: dict[str, Any]) -> Any: + if leg == "mcp": + body: dict[str, Any] = { + "jsonrpc": "2.0", + "id": 1, + "method": "tools/call", + "params": {"name": tool, "arguments": params}, + } + else: + body = { + "jsonrpc": "2.0", + "id": 1, + "method": "message/send", + "params": { + "message": { + "messageId": "m1", + "role": "user", + "parts": [{"kind": "data", "data": {"skill": tool, "parameters": params}}], + } + }, + } + response = client.post( + "/mcp" if leg == "mcp" else "/", + json=body, + headers={"accept": "application/json, text/event-stream"}, + ) + assert response.status_code == 200 + return response.json() + + +@pytest.mark.parametrize("leg", ["mcp", "a2a"]) +def test_public_transports_serve_the_alias_on_every_tool(leg: str) -> None: + seller = AliasSeller() + kwargs: dict[str, Any] = {"version_aliases": {"3.3-rc.2": "3.3"}, "validation": STRICT} + if leg == "mcp": + app = create_mcp_server(seller, stateless_http=True, **kwargs).streamable_http_app() + else: + app = create_a2a_server(seller, **kwargs) + with TestClient(app, base_url="http://localhost:3001") as client: + products = json.dumps( + _call(client, leg, "get_products", {**REQUEST, "adcp_version": "3.3-rc.2"}) + ) + assert '"products": []' in products + assert '"adcp_version": "3.3-rc.2"' in products + polled = json.dumps( + _call(client, leg, "get_task_status", {"task_id": "task_1", "adcp_version": "3.3-rc.2"}) + ) + assert '"task_id": "task_1"' in polled + assert '"adcp_version": "3.3-rc.2"' in polled + capabilities = json.dumps( + _call(client, leg, "get_adcp_capabilities", {"adcp_version": "3.3-rc.2"}) + ) + assert '"3.3-rc.3", "3.3-rc.2"]' in capabilities + refused = json.dumps( + _call(client, leg, "get_products", {**REQUEST, "adcp_version": "3.3-rc.1"}) + ) + assert "VERSION_UNSUPPORTED" in refused + assert "3.3-rc.2" in refused + assert seller.versions == [("get_products", "3.3", "3.3"), ("get_task_status", "3.3", "3.3")] + + +async def test_testing_client_serves_aliases_for_decisioning_platforms() -> None: + from adcp.testing import build_test_client + from tests.test_decisioning_serve import _BarePlatform + + async with build_test_client( + _BarePlatform(), + transport="mcp", + stateless_http=True, + supported_versions=["3.3"], + version_aliases={"3.3-rc.2": "3.3"}, + validation=None, + validate_at_init=False, + ) as client: + response = await client.post( + "/mcp", + json={ + "jsonrpc": "2.0", + "id": 1, + "method": "tools/call", + "params": { + "name": "get_adcp_capabilities", + "arguments": {"adcp_version": "3.3-rc.2"}, + }, + }, + headers={"accept": "application/json, text/event-stream"}, + ) + assert response.status_code == 200 + assert '"supported_versions":["3.3","3.3-rc.2"]' in response.text.replace(" ", "") + + +# --------------------------------------------------------------------------- +# #2008: global hook and middleware ordering +# --------------------------------------------------------------------------- + + +async def test_global_hook_runs_for_every_tool_before_the_tools_own() -> None: + calls: list[tuple[str, str]] = [] + + def global_hook(tool: str, args: dict[str, Any]) -> dict[str, Any]: + calls.append(("*", tool)) + return args + + def products_hook(tool: str, args: dict[str, Any]) -> dict[str, Any]: + calls.append(("get_products", tool)) + return args + + hooks = {GLOBAL_PRE_VALIDATION_HOOK_KEY: global_hook, "get_products": products_hook} + assert GLOBAL_PRE_VALIDATION_HOOK_KEY == "*" + toolset = MCPToolSet(AliasSeller(), pre_validation_hooks=hooks) + executor = ADCPAgentExecutor(AliasSeller(), pre_validation_hooks=hooks, validation=None) + for call in ( + toolset.call_tool, + lambda tool, params: executor._tool_callers[tool](params, ToolContext()), + ): + calls.clear() + await call("get_products", {**REQUEST, "adcp_version": "3.3"}) + await call("get_adcp_capabilities", {"adcp_version": "3.3"}) + assert calls == [ + ("*", "get_products"), + ("get_products", "get_products"), + ("*", "get_adcp_capabilities"), + ] + + +def test_compose_appends_global_hooks() -> None: + def first(tool: str, args: dict[str, Any]) -> dict[str, Any]: + return args + + def second(tool: str, args: dict[str, Any]) -> dict[str, Any]: + return args + + assert compose_pre_validation_hooks({"*": first}, {"*": [second]}) == {"*": (first, second)} + + +async def test_global_hook_can_bridge_versions_on_every_tool() -> None: + def bridge(tool: str, args: dict[str, Any]) -> dict[str, Any]: + if args.get("adcp_version") == "3.3-rc.1": + args["adcp_version"] = "3.3" + return args + + tools = MCPToolSet(AliasSeller(), validation=STRICT, pre_validation_hooks={"*": bridge}) + response = await tools.call_tool( + "get_task_status", {"task_id": "task_1", "adcp_version": "3.3-rc.1"} + ) + # The hook served an unadvertised version; only aliases are echoed. + assert response["status"] == "completed" and "adcp_version" not in response + + +@pytest.mark.parametrize("leg", ["mcp", "a2a"]) +def test_middleware_receives_the_raw_request_and_hooks_receive_a_copy(leg: str) -> None: + """Pins the documented SkillMiddleware / pre-validation hook ordering.""" + seen: list[tuple[str, dict[str, Any]]] = [] + + async def audit( + skill: str, params: dict[str, Any], context: ToolContext, call_next: Any + ) -> Any: + seen.append(("before", dict(params))) + result = await call_next() + seen.append(("after", dict(params))) + return result + + hook_args: list[dict[str, Any]] = [] + + def rewrite(tool: str, args: dict[str, Any]) -> dict[str, Any]: + hook_args.append(dict(args)) + args["adcp_version"] = "3.3" + args["brief"] = "rewritten" + return args + + seller = AliasSeller() + kwargs: dict[str, Any] = { + "middleware": [audit], + "pre_validation_hooks": {"*": rewrite}, + "validation": STRICT, + } + if leg == "mcp": + app = create_mcp_server(seller, stateless_http=True, **kwargs).streamable_http_app() + else: + app = create_a2a_server(seller, **kwargs) + request = {**REQUEST, "adcp_version": "3.3-rc.3"} + with TestClient(app, base_url="http://localhost:3001") as client: + response = json.dumps(_call(client, leg, "get_products", request)) + assert '"adcp_version": "3.3-rc.3"' in response + assert hook_args == [request] + assert [phase for phase, _ in seen] == ["before", "after"] + for _, params in seen: + assert params["adcp_version"] == "3.3-rc.3" + assert params["brief"] == "sports" + + +def test_testing_helper_checks_the_handler_pin_like_serve( + monkeypatch: pytest.MonkeyPatch, +) -> None: + from adcp.server import version_policy + from adcp.testing import build_asgi_app + from tests.test_decisioning_serve import _BarePlatform + + calls: list[dict[str, Any]] = [] + resolve = version_policy.resolve_supported_versions + + def spy(*args: Any, **kwargs: Any) -> Any: + if kwargs.get("version_aliases"): + calls.append(kwargs) + return resolve(*args, **kwargs) + + monkeypatch.setattr(version_policy, "resolve_supported_versions", spy) + build_asgi_app( + _BarePlatform(), + supported_versions=["3.3"], + version_aliases={"3.3-rc.2": "3.3"}, + validation=None, + validate_at_init=False, + ) + assert calls and calls[0]["adcp_version"] == "3.3" + # The pin is checked against the served set, as in serve(). + with pytest.raises(ConfigurationError, match="outside supported_versions"): + resolve(["3.2"], adcp_version="3.3", version_aliases={"3.2-rc.8": "3.2"}) + + +async def test_comply_test_controller_never_runs_global_hooks() -> None: + from adcp.server._hooks import pre_validation_hooks_for_tool + from adcp.server.test_controller import TestControllerStore + + calls: list[str] = [] + + def global_hook(tool: str, args: dict[str, Any]) -> dict[str, Any]: + calls.append(tool) + return args + + def own_hook(tool: str, args: dict[str, Any]) -> dict[str, Any]: + return args + + hooks = {GLOBAL_PRE_VALIDATION_HOOK_KEY: global_hook} + assert pre_validation_hooks_for_tool(hooks, "comply_test_controller") == () + assert pre_validation_hooks_for_tool( + {**hooks, "comply_test_controller": own_hook}, "comply_test_controller" + ) == (own_hook,) + executor = ADCPAgentExecutor( + AliasSeller(), test_controller=TestControllerStore(), pre_validation_hooks=hooks + ) + response = await executor._tool_callers["comply_test_controller"]( + {"scenario": "list_scenarios", "adcp_version": "3.3", "account": {"sandbox": True}}, + ToolContext(), + ) + assert response["success"] is True + assert calls == [] diff --git a/tests/type_checks/server_version_aliases.py b/tests/type_checks/server_version_aliases.py new file mode 100644 index 000000000..e0ca1858e --- /dev/null +++ b/tests/type_checks/server_version_aliases.py @@ -0,0 +1,51 @@ +"""Typed version aliases and the global pre-validation hook on the server APIs.""" + +from collections.abc import Mapping +from typing import Any + +from adcp.decisioning import DecisioningPlatform +from adcp.decisioning import serve as serve_platform +from adcp.server import ( + GLOBAL_PRE_VALIDATION_HOOK_KEY, + ADCPHandler, + PreValidationHooks, + ServeConfig, + ToolContext, + create_a2a_server, + create_mcp_server, + serve, +) +from adcp.server.a2a_server import ADCPAgentExecutor +from adcp.server.mcp_tools import MCPToolSet, create_mcp_tools, create_tool_caller +from adcp.server.version_policy import ServedVersions, resolve_supported_versions +from adcp.testing import build_asgi_app, build_test_client + + +def bridge(tool_name: str, args: dict[str, Any]) -> dict[str, Any]: + return args + + +def compose(handler: ADCPHandler[ToolContext], platform: DecisioningPlatform) -> None: + aliases: Mapping[str, str] = {"3.3-rc.2": "3.3"} + hooks: PreValidationHooks = {GLOBAL_PRE_VALIDATION_HOOK_KEY: bridge} + config = ServeConfig(version_aliases=aliases, pre_validation_hooks=hooks) + create_mcp_server(handler, version_aliases=aliases) + create_a2a_server(handler, version_aliases=aliases) + create_tool_caller(handler, "get_products", version_aliases=aliases) + create_mcp_tools(handler, version_aliases=aliases) + MCPToolSet(handler, version_aliases=aliases, pre_validation_hooks=hooks) + ADCPAgentExecutor(handler, version_aliases=aliases) + serve(handler, config=config) + serve(handler, supported_versions=["3.3"], version_aliases=aliases) + serve_platform(platform, version_aliases=aliases) + build_asgi_app(platform, version_aliases=aliases) + served = resolve_supported_versions(None, version_aliases=aliases) + if isinstance(served, ServedVersions): + target: str = served.aliases["3.3-rc.2"] + explicit: bool = served.explicit + del target, explicit + + +async def connect(platform: DecisioningPlatform) -> None: + async with build_test_client(platform, version_aliases={"3.3-rc.2": "3.3"}) as client: + await client.get("/.well-known/agent-card.json")