Package adcp
Sub-modules
adcp.acceptance-
Advisory buyer resolution for seller acceptance-policy catalogs …
adcp.account_identity-
Canonical account keys shared by buyer tracking and seller resolution.
adcp.accounts-
Buyer-side provisioning registry, scoped to a seller and buyer identity.
adcp.adagentsadcp.audit_sink-
Audit-event observability seam paralleling :class:
~adcp.webhook_supervisor.DeliveryLogSink… adcp.canonical_formats-
Pythonic v1↔v2 canonical-formats projection layer …
adcp.capabilities-
Feature capability resolution for AdCP …
adcp.clientadcp.compat-
AdCP compatibility surfaces for buyers on older spec versions …
adcp.configadcp.decisioning-
Decisioning Platform v6.0 — Protocol-driven adopter framework …
adcp.error_sanitization-
Sanitizers for public error/account authorization metadata.
adcp.exceptions-
Exception hierarchy for AdCP client.
adcp.feed_mirror-
In-memory mirror of an AdCP agent's wholesale product and signal feeds …
adcp.governance-
Cross-role campaign-governance helpers for AdCP 3.2 …
adcp.identifiers-
Public, local identifier validation and canonicalization (no network I/O).
adcp.media_buy_actions-
Buyer and seller helpers for proposal-bound MediaBuy change rights …
adcp.migrate-
Migration tooling for the AdCP SDK …
adcp.negotiation-
Buyer-side verification helpers for AdCP proposal negotiation …
adcp.notification_outbox_pg-
Atomic PostgreSQL publication of immutable, non-task notifications …
adcp.oauth-
Security-focused OAuth 2.0 authorization-code helpers for buyer clients …
adcp.observability-
Optional OpenTelemetry tracing for AdCP client calls …
adcp.principal-
Buyer-side orchestration for the AdCP 3.2 principal layer …
adcp.property_lists-
MCP property-list resolution and opt-in buyer product checks.
adcp.property_registry-
PropertyRegistry — local authorization cache backed by the AAO registry …
adcp.protocolsadcp.registry-
Client for the AdCP registry API (brand, property, member, and policy lookups).
adcp.registry_sync-
Registry change feed synchronization.
adcp.reporting-
Reliable Reporting: buyer-side reconciliation and seller-side production …
adcp.reporting_inspection-
Built-in inspection for immutable reporting file manifests.
adcp.schemas-
Access bundled AdCP JSON schemas by name …
adcp.server-
ADCP Server Framework …
adcp.signing-
AdCP RFC 9421 request-signing profile …
adcp.simple-
Simplified API accessor for ADCPClient …
adcp.substitution-
Producer-side translation of AdCP universal macros in pixel URLs …
adcp.task_options-
Per-call execution options and deadline recovery metadata.
adcp.testing-
Test helpers for AdCP client library …
adcp.types-
AdCP Type System …
adcp.utilsadcp.validation-
AdCP validation helpers …
adcp.webhook_auth-
Auth-mode strategies for :class:
WebhookSender… adcp.webhook_receiver-
One-call webhook receiver: verify signature, dedupe, parse …
adcp.webhook_sender-
One-call outbound webhook delivery for AdCP senders …
adcp.webhook_supervisor-
Webhook delivery supervisor — retry, circuit breaker, attempt audit …
adcp.webhook_supervisor_pg-
PostgreSQL-backed :class:
WebhookDeliverySupervisorfor a durable retry queue … adcp.webhook_transport_hooks-
Pre-SSRF URL rewrite hooks for :class:
WebhookSender… adcp.webhooks-
Webhook creation, signing, and reception for AdCP agents …
Functions
def assess_media_buy_action(action: str,
*,
product: Any | None = None,
proposal: Any | None = None,
media_buy: Any | None = None,
intent: ActionIntent | Mapping[str, Any] | None = None,
now: datetime | None = None) ‑> MediaBuyActionAssessment-
Expand source code
def assess_media_buy_action( action: str, *, product: Any | None = None, proposal: Any | None = None, media_buy: Any | None = None, intent: ActionIntent | Mapping[str, Any] | None = None, now: datetime | None = None, ) -> MediaBuyActionAssessment: """Join product, accepted proposal, and live-buy action surfaces. Inputs may be generated Pydantic models or wire mappings. Unknown future enum values and legacy coarse actions are retained as unknown evidence but are never treated as authority. """ if _ACTION_RE.fullmatch(action) is None: raise MediaBuyActionError("invalid_action", "action") diagnostics: list[ActionDiagnostic] = [] possible = _assess_product_support(action, product, diagnostics) change_terms_present, change_terms = _extract_change_terms(proposal, media_buy) term, term_diagnostics = _find_change_term(action, change_terms) diagnostics.extend(term_diagnostics) if not change_terms_present: promised = ActionKnowledge.unknown diagnostics.append(ActionDiagnostic(code=ActionDiagnosticCode.legacy_terms_unknown)) elif term is None: promised = ActionKnowledge.no else: promised = ActionKnowledge.yes status_value = _string_field(media_buy, "status") wrong_status = False if term is not None and status_value is not None: allowed_statuses = _string_sequence(term.get("allowed_statuses")) wrong_status = status_value in _TERMINAL_STATUSES or ( bool(allowed_statuses) and status_value not in allowed_statuses ) live_state, live_action = _assess_live_action(action, media_buy, diagnostics) task: ActionTask | None = None mode: str | None = None change_term_id: str | None = None constraints: tuple[ConstraintCheck, ...] = () if live_action is not None: task = _task_field(live_action) if "task" in live_action else route_media_buy_action(action) mode = _string_value(live_action.get("mode")) change_term_id = _string_value(live_action.get("change_term_id")) if term is not None and not _projection_matches_term( action, live_action, term, task, diagnostics ): live_state = ActionKnowledge.no elif term is not None: task = route_media_buy_action(action) mode = _string_value(term.get("service_mode")) change_term_id = _string_value(term.get("term_id")) if term is not None and intent is not None: parsed_intent = ( intent if isinstance(intent, ActionIntent) else ActionIntent.model_validate(intent) ) constraints = evaluate_action_constraints( action, term.get("constraints"), parsed_intent, now=now, ) if any(check.outcome is ConstraintOutcome.violated for check in constraints): diagnostics.append(ActionDiagnostic(code=ActionDiagnosticCode.constraint_violated)) live_state = ActionKnowledge.no integrity_failure = any( diagnostic.code in { ActionDiagnosticCode.alias_mismatch, ActionDiagnosticCode.duplicate_action, ActionDiagnosticCode.duplicate_term_id, ActionDiagnosticCode.invalid_projection, ActionDiagnosticCode.missing_change_term_link, ActionDiagnosticCode.mode_mismatch, ActionDiagnosticCode.route_mismatch, ActionDiagnosticCode.sla_mismatch, } for diagnostic in diagnostics ) if action not in _CANONICAL_ACTIONS: diagnostics.append(ActionDiagnostic(code=ActionDiagnosticCode.unknown_action)) final_status = ActionAvailabilityStatus.currently_unavailable live_state = ActionKnowledge.unknown elif integrity_failure: final_status = ActionAvailabilityStatus.currently_unavailable live_state = ActionKnowledge.no elif possible is ActionKnowledge.no: final_status = ActionAvailabilityStatus.unsupported_by_product elif promised is ActionKnowledge.no: final_status = ActionAvailabilityStatus.not_negotiated elif promised is ActionKnowledge.unknown: final_status = ActionAvailabilityStatus.legacy_unknown elif wrong_status: final_status = ActionAvailabilityStatus.wrong_status live_state = ActionKnowledge.no elif live_state is ActionKnowledge.yes: final_status = ActionAvailabilityStatus.available_now elif live_state is ActionKnowledge.unknown: final_status = ActionAvailabilityStatus.legacy_unknown else: final_status = ActionAvailabilityStatus.currently_unavailable return MediaBuyActionAssessment( action=action, status=final_status, possible=possible, promised=promised, available=live_state, task=task, mode=mode, change_term_id=change_term_id, async_processing=mode in {"seller_managed", "requires_approval"}, constraints=constraints, diagnostics=tuple(_dedupe_diagnostics(diagnostics)), )Join product, accepted proposal, and live-buy action surfaces.
Inputs may be generated Pydantic models or wire mappings. Unknown future enum values and legacy coarse actions are retained as unknown evidence but are never treated as authority.
def assess_update_media_buy_actions(patch: Any,
current_media_buy: Any,
*,
product: Any | None = None,
proposal: Any | None = None,
now: datetime | None = None) ‑> tuple[MediaBuyActionAssessment, ...]-
Expand source code
def assess_update_media_buy_actions( patch: Any, current_media_buy: Any, *, product: Any | None = None, proposal: Any | None = None, now: datetime | None = None, ) -> tuple[MediaBuyActionAssessment, ...]: """Assess every logical action represented by an update compatibility patch.""" assessments: list[MediaBuyActionAssessment] = [] for mutation in decompose_update_media_buy(patch, current_media_buy): if mutation.action == UNKNOWN_UPDATE_ACTION: continue intent = _intent_from_mutation(mutation, current_media_buy, now=now) assessments.append( assess_media_buy_action( mutation.action, product=product, proposal=proposal, media_buy=current_media_buy, intent=intent, now=now, ) ) return tuple(assessments)Assess every logical action represented by an update compatibility patch.
async def challenge_webhook_destination(*,
url: str | AnyUrl,
account_id: str,
subscriber_id: str,
seller_agent_url: str = <object object>,
event_types: Sequence[str] = <object object>,
sender: WebhookSender | None = None,
authentication: AdCPBaseModel | Mapping[str, Any] | None = None,
challenge: str | None = None,
timeout_seconds: float | None = None,
policy: WebhookDestinationPolicy | None = None,
field: str | None = None,
extra_headers: Mapping[str, str] | None = None) ‑> WebhookChallengeResult-
Expand source code
async def challenge_webhook_destination( *, url: str | AnyUrl, account_id: str, subscriber_id: str, seller_agent_url: str = _UNSET, event_types: Sequence[str] = _UNSET, sender: WebhookSender | None = None, authentication: AdCPBaseModel | Mapping[str, Any] | None = None, challenge: str | None = None, timeout_seconds: float | None = None, policy: WebhookDestinationPolicy | None = None, field: str | None = None, extra_headers: Mapping[str, str] | None = None, ) -> WebhookChallengeResult: """Validate and prove control of a durable webhook destination. Use before activating a new or changed active ``sync_accounts.accounts[].notification_configs[]`` entry. Inactive configs can be persisted without calling this helper. Pass ``seller_agent_url``, ``event_types`` and an RFC 9421 ``sender`` to send the AdCP 3.2 challenge. ``authentication`` then describes the durable config's deprecated Bearer or HMAC-SHA256 delivery mode; the challenge itself is always signed by the RFC 9421 ``sender`` and uses the SDK-managed pinned transport. Omitting ``seller_agent_url`` and ``event_types`` is deprecated and keeps the adcp 9.6 behaviour with a :class:`DeprecationWarning`: the four-field challenge is signed by ``sender``, or, when only ``authentication`` is passed, sent with legacy Bearer or HMAC-SHA256 delivery authentication (a second :class:`DeprecationWarning`). adcp 10.0 requires ``seller_agent_url``, ``event_types`` and an RFC 9421 ``sender``. """ _check_challenge_fields_passed_together( "challenge_webhook_destination", seller_agent_url=seller_agent_url, event_types=event_types, ) if seller_agent_url is _UNSET: return await _challenge_webhook_destination_v9_6( url=url, account_id=account_id, subscriber_id=subscriber_id, sender=sender, authentication=authentication, challenge=challenge, timeout_seconds=timeout_seconds, policy=policy, field=field, extra_headers=extra_headers, ) error_url = str(url) if isinstance(url, (str, AnyUrl)) else None sender_owns_client = bool(getattr(cast(Any, sender), "_owns_client", False)) sender_transport_hooks = tuple(getattr(cast(Any, sender), "_transport_hooks", ())) if sender is not None and not sender_owns_client: raise WebhookChallengeError( "proof-of-control requires a WebhookSender constructed without client=", reason="unsafe_sender_client", field=field, url=error_url, ) if sender is not None and sender_transport_hooks: raise WebhookChallengeError( "proof-of-control does not support sender transport_hooks", reason="unsupported_sender_hooks", field=field, url=error_url, ) if sender is not None and not sender.signs_with_rfc9421: raise WebhookChallengeError( "proof-of-control requires an RFC 9421 WebhookSender", reason="sender_auth_mode_mismatch", field=field, url=error_url, suggestion="Use WebhookSender.from_jwk(...) to sign the challenge.", ) if sender is None: raise WebhookChallengeError( "webhook challenge requires an RFC 9421 sender", reason="sender_required", field=field, url=error_url, suggestion="Pass the seller's RFC 9421 WebhookSender.", ) try: destination = validate_webhook_destination_url(url, policy=policy, field=field) payload = _build_webhook_challenge_payload( account_id=account_id, subscriber_id=subscriber_id, seller_agent_url=seller_agent_url, event_types=event_types, authentication=authentication, challenge=challenge, ) except WebhookDestinationValidationError as exc: raise WebhookChallengeError( str(exc), reason=exc.reason, field=exc.field, url=exc.url, suggestion=exc.suggestion, ) from exc except ValueError as exc: raise WebhookChallengeError( f"webhook challenge configuration is invalid: {exc}", reason="invalid_configuration", field=field, url=error_url, ) from exc challenge_value = payload["challenge"] try: effective_timeout = ( timeout_seconds if timeout_seconds is not None else float(getattr(cast(Any, sender), "_timeout", _DEFAULT_TIMEOUT_SECONDS)) ) response = await _send_sender_webhook_challenge( url=destination.effective_url, sender=sender, payload=payload, timeout_seconds=effective_timeout, policy=destination.policy, extra_headers=extra_headers, ) status_code = response.status_code response_headers = dict(response.headers) response_body = response.content except httpx.TimeoutException as exc: raise WebhookChallengeError( "webhook challenge timed out", reason="timeout", field=field, url=destination.original_url, ) from exc except httpx.HTTPError as exc: raise WebhookChallengeError( f"webhook challenge request failed: {exc}", reason="request_failed", field=field, url=destination.original_url, ) from exc except ValueError as exc: raise WebhookChallengeError( f"webhook challenge configuration is invalid: {exc}", reason="invalid_configuration", field=field, url=destination.original_url, ) from exc if not 200 <= status_code < 300: raise WebhookChallengeError( f"webhook challenge failed with HTTP {status_code}", reason="http_status", field=field, url=destination.original_url, status_code=status_code, ) echoed_field = validate_webhook_challenge_response( response_body, challenge=challenge_value, field=field, url=destination.original_url, ) return WebhookChallengeResult( challenge=challenge_value, echoed_field=echoed_field, destination=destination, status_code=status_code, response_headers=response_headers, response_body=response_body, )Validate and prove control of a durable webhook destination.
Use before activating a new or changed active
sync_accounts.accounts[].notification_configs[]entry. Inactive configs can be persisted without calling this helper.Pass
seller_agent_url,event_typesand an RFC 9421senderto send the AdCP 3.2 challenge.authenticationthen describes the durable config's deprecated Bearer or HMAC-SHA256 delivery mode; the challenge itself is always signed by the RFC 9421senderand uses the SDK-managed pinned transport.Omitting
seller_agent_urlandevent_typesis deprecated and keeps the adcp 9.6 behaviour with a :class:DeprecationWarning: the four-field challenge is signed bysender, or, when onlyauthenticationis passed, sent with legacy Bearer or HMAC-SHA256 delivery authentication (a second :class:DeprecationWarning). adcp 10.0 requiresseller_agent_url,event_typesand an RFC 9421sender. async def check_property_list_reference(ref: Any,
*,
fetcher: MCPPropertyListFetcher | None = None) ‑> ResolvedPropertyList-
Expand source code
async def check_property_list_reference( ref: Any, *, fetcher: MCPPropertyListFetcher | None = None ) -> ResolvedPropertyList: """Compliance probe: resolve a reference over MCP and exhaust its pages. Disable caching so every probe exercises the issuing agent. The returned ``pages`` and identifiers let a caller assert its expected list contents. """ resolver = fetcher if fetcher is not None else MCPPropertyListFetcher(max_cache_entries=0) resolver.clear_cache() return await resolver.resolve(ref)Compliance probe: resolve a reference over MCP and exhaust its pages.
Disable caching so every probe exercises the issuing agent. The returned
pagesand identifiers let a caller assert its expected list contents. -
Expand source code
async def complete_oauth_authorization( *, code: str | None, callback_state: str, expected_state: str, store: PendingOAuthFlowStore, callback_issuer: str | None = None, callback_error: str | None = None, timeout: float = 10.0, clock: Callable[[], datetime] | None = None, ) -> OAuthTokenSet: """Consume one callback and exchange its code for public-client tokens. ``expected_state`` must come from a separate browser-session binding, not from the callback query itself. Once the two states match, the pending flow is consumed before any issuer/error/code handling or network I/O. Any failure therefore requires starting a new authorization flow. """ if isinstance(timeout, bool) or not math.isfinite(timeout) or timeout <= 0 or timeout > 60: raise ValueError("timeout must be greater than 0 and at most 60 seconds") if not ( 43 <= len(callback_state) <= _MAX_STATE_LENGTH and 43 <= len(expected_state) <= _MAX_STATE_LENGTH and callback_state.isascii() and expected_state.isascii() and re.fullmatch(r"[A-Za-z0-9_-]+", callback_state) and re.fullmatch(r"[A-Za-z0-9_-]+", expected_state) ) or not hmac.compare_digest(callback_state, expected_state): raise OAuthAuthorizationError("state_mismatch", phase="callback") pending = await store.consume(callback_state) if pending is None: raise OAuthAuthorizationError("flow_not_found", phase="callback") if not hmac.compare_digest(pending.state, callback_state): raise OAuthAuthorizationError("state_mismatch", phase="callback") now = (clock or (lambda: datetime.now(timezone.utc)))() if now.tzinfo is None: raise ValueError("clock must return a timezone-aware datetime") if pending.expires_at <= now: raise OAuthAuthorizationError("flow_expired", phase="callback") if callback_issuer is not None and ( len(callback_issuer) > _MAX_URL_LENGTH or callback_issuer != pending.issuer ): raise OAuthAuthorizationError("issuer_mismatch", phase="callback") if ( pending.issuer_binding is OAuthIssuerBinding.AUTHORIZATION_RESPONSE_ISS and callback_issuer is None ): raise OAuthAuthorizationError("issuer_mismatch", phase="callback") if callback_error is not None: raise OAuthAuthorizationError( "authorization_failed", phase="callback", oauth_error=_safe_oauth_error(callback_error), ) if code is None or not 1 <= len(code) <= _MAX_CODE_LENGTH or not _VSCHAR_RE.fullmatch(code): raise OAuthAuthorizationError("invalid_code", phase="callback") return await _exchange_code( pending, code=code, timeout=timeout, )Consume one callback and exchange its code for public-client tokens.
expected_statemust come from a separate browser-session binding, not from the callback query itself. Once the two states match, the pending flow is consumed before any issuer/error/code handling or network I/O. Any failure therefore requires starting a new authorization flow. def create_a2a_webhook_payload(task_id: str,
status: TaskStatus,
context_id: str,
result: PydanticBaseModel | dict[str, Any],
timestamp: datetime | None = None) ‑> a2a_pb2.Task | a2a_pb2.TaskStatusUpdateEvent-
Expand source code
def create_a2a_webhook_payload( task_id: str, status: GeneratedTaskStatus, context_id: str, result: PydanticBaseModel | dict[str, Any], timestamp: datetime | None = None, ) -> Task | TaskStatusUpdateEvent: """ Create A2A webhook payload (Task or TaskStatusUpdateEvent). Per A2A specification: - Terminated statuses (completed, failed, canceled, rejected): Returns Task with artifacts[].parts[] - Intermediate statuses (working, input-required, submitted, auth-required): Returns TaskStatusUpdateEvent with status.message.parts[] This function helps agent implementations construct properly formatted A2A webhook payloads for sending to clients. Args: task_id: Unique identifier for the task status: Current task status context_id: Session/conversation identifier (required by A2A protocol) timestamp: When the webhook was generated (defaults to current UTC time) result: Task-specific payload — any Pydantic model or plain dict Returns: Task object for terminated statuses, TaskStatusUpdateEvent for intermediate statuses Examples: Create a completed Task webhook: >>> from adcp.webhooks import create_a2a_webhook_payload >>> from adcp.types import GeneratedTaskStatus >>> >>> task = create_a2a_webhook_payload( ... task_id="task_123", ... context_id="ctx_123", ... status=GeneratedTaskStatus.completed, ... result={"products": [...]}, ... ) >>> # task is a Task object with artifacts containing the result Create a working status update: >>> event = create_a2a_webhook_payload( ... task_id="task_456", ... context_id="ctx_456", ... status=GeneratedTaskStatus.working, ... result={"current_step": "processing", "percentage": 30}, ... ) >>> # event is a TaskStatusUpdateEvent with status.message Send A2A webhook via HTTP POST: >>> import httpx >>> from a2a.types import Task >>> >>> payload = create_a2a_webhook_payload(...) >>> # Serialize to dict for JSON >>> if isinstance(payload, Task): ... payload_dict = payload.model_dump(mode='json') ... else: ... payload_dict = payload.model_dump(mode='json') >>> >>> response = await httpx.post(webhook_url, json=payload_dict) """ if timestamp is None: timestamp = datetime.now(timezone.utc) # Convert datetime to ISO string for A2A protocol timestamp_str = timestamp.isoformat() if isinstance(timestamp, datetime) else timestamp timestamp_proto = _isoformat_to_proto_timestamp(timestamp_str) if timestamp_str else None # Map GeneratedTaskStatus to A2A TaskState enum value. # GeneratedTaskStatus is always an Enum so .value is guaranteed. status_value = status.value adcp_to_task_state: dict[str, int] = { "completed": pb.TaskState.TASK_STATE_COMPLETED, "failed": pb.TaskState.TASK_STATE_FAILED, "canceled": pb.TaskState.TASK_STATE_CANCELED, "rejected": pb.TaskState.TASK_STATE_REJECTED, "working": pb.TaskState.TASK_STATE_WORKING, "submitted": pb.TaskState.TASK_STATE_SUBMITTED, # GeneratedTaskStatus enum values are hyphenated ("input-required", # "auth-required"). The underscore forms are accepted as a convenience # for callers passing raw strings rather than enum members. "input_required": pb.TaskState.TASK_STATE_INPUT_REQUIRED, "input-required": pb.TaskState.TASK_STATE_INPUT_REQUIRED, "auth_required": pb.TaskState.TASK_STATE_AUTH_REQUIRED, "auth-required": pb.TaskState.TASK_STATE_AUTH_REQUIRED, } task_state_enum = adcp_to_task_state.get(status_value) if task_state_enum is None: # Falling back to TASK_STATE_UNSPECIFIED (proto3 zero) would be # silently omitted by MessageToDict, producing an invalid wire # shape ``{"status": {}}`` that A2A v0.3 receivers reject as # missing the required ``state`` field. Fail loud at the builder # boundary so callers can't ship a broken envelope. known = [ "submitted", "working", "input-required", "completed", "canceled", "failed", "rejected", "auth-required", ] raise ValueError( f"create_a2a_webhook_payload: unknown status {status_value!r}. " f"Known AdCP→A2A states: {known}. " "Note: 'unknown' has no a2a-sdk 1.0 protobuf constant; build a " "Task manually and pass it through to_wire_dict if you need to " "emit that state." ) # Build parts for the message/artifact. parts: list[pb.Part] = [] # Convert Pydantic model to dict if needed if hasattr(result, "model_dump"): result_dict: dict[str, Any] = result.model_dump(mode="json") else: result_dict = result value = Value() ParseDict(result_dict, value) parts.append(pb.Part(data=value)) # Determine if this is a terminated status (Task) or intermediate (TaskStatusUpdateEvent). # canceled and rejected are terminal: the task will not continue. is_terminated = status in ( GeneratedTaskStatus.completed, GeneratedTaskStatus.failed, GeneratedTaskStatus.canceled, GeneratedTaskStatus.rejected, ) if is_terminated: status_kwargs: dict[str, Any] = {"state": task_state_enum} if timestamp_proto is not None: status_kwargs["timestamp"] = timestamp_proto task_status = pb.TaskStatus(**status_kwargs) artifacts = ( [ pb.Artifact( artifact_id=f"{task_id}_result", parts=parts, ) ] if parts else [] ) return pb.Task( id=task_id, status=task_status, artifacts=artifacts, context_id=context_id, ) # Intermediate status: build a Message carrying the parts and nest it # inside TaskStatus.message so the event mirrors the spec shape. message_obj = None if parts: message_obj = pb.Message( message_id=f"{task_id}_msg", role=pb.Role.ROLE_AGENT, parts=parts, ) status_kwargs = {"state": task_state_enum} if timestamp_proto is not None: status_kwargs["timestamp"] = timestamp_proto if message_obj is not None: status_kwargs["message"] = message_obj task_status = pb.TaskStatus(**status_kwargs) return pb.TaskStatusUpdateEvent( task_id=task_id, status=task_status, context_id=context_id, )Create A2A webhook payload (Task or TaskStatusUpdateEvent).
Per A2A specification: - Terminated statuses (completed, failed, canceled, rejected): Returns Task with artifacts[].parts[] - Intermediate statuses (working, input-required, submitted, auth-required): Returns TaskStatusUpdateEvent with status.message.parts[]
This function helps agent implementations construct properly formatted A2A webhook payloads for sending to clients.
- Args
- -----=
task_id- Unique identifier for the task
status- Current task status
context_id- Session/conversation identifier (required by A2A protocol)
timestamp- When the webhook was generated (defaults to current UTC time)
result- Task-specific payload — any Pydantic model or plain dict
Returns -----= Task object for terminated statuses, TaskStatusUpdateEvent for intermediate statuses
Examples -----= Create a completed Task webhook:
>>> from adcp.webhooks import create_a2a_webhook_payload >>> from adcp.types import GeneratedTaskStatus >>> >>> task = create_a2a_webhook_payload( ... task_id="task_123", ... context_id="ctx_123", ... status=GeneratedTaskStatus.completed, ... result={"products": [...]}, ... ) >>> # task is a Task object with artifacts containing the resultCreate a working status update:
>>> event = create_a2a_webhook_payload( ... task_id="task_456", ... context_id="ctx_456", ... status=GeneratedTaskStatus.working, ... result={"current_step": "processing", "percentage": 30}, ... ) >>> # event is a TaskStatusUpdateEvent with status.messageSend A2A webhook via HTTP POST:
>>> import httpx >>> from a2a.types import Task >>> >>> payload = create_a2a_webhook_payload(...) >>> # Serialize to dict for JSON >>> if isinstance(payload, Task): ... payload_dict = payload.model_dump(mode='json') ... else: ... payload_dict = payload.model_dump(mode='json') >>> >>> response = await httpx.post(webhook_url, json=payload_dict) def create_mcp_webhook_payload(task_id: str,
status: TaskStatus | str,
task_type: TaskType | str,
*,
result: PydanticBaseModel | dict[str, Any] | None = None,
timestamp: datetime | None = None,
operation_id: str,
notification_id: str | None = None,
message: str | None = None,
context_id: str | None = None,
protocol: AdcpProtocol | str | None = None,
idempotency_key: str | None = None,
token: str | None = None) ‑> McpWebhookPayload-
Expand source code
def create_mcp_webhook_payload( task_id: str, status: GeneratedTaskStatus | str, task_type: TaskType | str, *, result: PydanticBaseModel | dict[str, Any] | None = None, timestamp: datetime | None = None, operation_id: str, notification_id: str | None = None, message: str | None = None, context_id: str | None = None, protocol: AdcpProtocol | str | None = None, idempotency_key: str | None = None, token: str | None = None, ) -> McpWebhookPayload: """ Build an :class:`McpWebhookPayload` for a tracked async task. Pair with :func:`to_wire_dict` for HTTP transport — Pydantic-typed at construction so the publisher catches schema drift before it leaves the process. ``task_type`` is restricted to the closed :class:`TaskType` enum (the spec's complete set of async/tracked operations). Passing a value not present in the enum produces a validation error before an invalid webhook payload can leave the process. Args: task_id: Unique identifier for the task. status: Current task status. task_type: Type of AdCP async operation (see :class:`TaskType`). result: Task-specific payload — any Pydantic model or plain dict. Plain dicts are validated against :class:`AdcpAsyncResponseData`'s discriminated union. timestamp: When the webhook was generated. Defaults to current UTC. operation_id: Client-generated identifier supplied through the registration's ``push_notification_config.operation_id``. Required for every task webhook; publishers echo it verbatim and MUST NOT derive it from the receiver URL. notification_id: Stable identity for one logical notification. Terminal task webhooks default to ``"{task_id}.terminal"`` so re-emissions under different delivery keys still converge. ``media_buy_delivery`` reports get no default: they are point-in-time events deduped by ``idempotency_key``. message: Human-readable summary of task state. context_id: Session/conversation identifier. protocol: AdCP protocol this task belongs to (see :class:`AdcpProtocol`). Auto-derived from ``task_type`` when omitted, matching the JS SDK's ``protocolForTool`` so cross-SDK bodies classify operations identically. Pass an explicit value to override. idempotency_key: Sender-generated key stable across retries of the same event. Defaults to a freshly-generated UUID v4 — callers retrying delivery of the same event MUST pass the key from their first attempt; passing None twice mints two keys and defeats dedup. token: Buyer-supplied token from ``push_notification_config.token``, echoed back per spec for authenticity validation. Returns: :class:`McpWebhookPayload` instance. Use :func:`to_wire_dict` (or ``payload.model_dump(mode="json", exclude_none=True)``) to get the JSON-ready dict for HTTP transport. Examples: Create a completed webhook with results: >>> from adcp.webhooks import create_mcp_webhook_payload, to_wire_dict >>> from adcp.types import GeneratedTaskStatus >>> >>> payload = create_mcp_webhook_payload( ... task_id="task_123", ... operation_id="op_123", ... status=GeneratedTaskStatus.completed, ... task_type="create_media_buy", ... result={"media_buy_id": "mb_1", "buyer_ref": "ref_1"}, ... message="Created campaign" ... ) >>> wire = to_wire_dict(payload) Create a failed webhook with error: >>> payload = create_mcp_webhook_payload( ... task_id="task_456", ... operation_id="op_456", ... status=GeneratedTaskStatus.failed, ... task_type="create_media_buy", ... result={"errors": [{"code": "INVALID_INPUT", "message": "..."}]}, ... message="Validation failed" ... ) Create a working status update: >>> payload = create_mcp_webhook_payload( ... task_id="task_789", ... operation_id="op_789", ... status=GeneratedTaskStatus.working, ... task_type="sync_creatives", ... message="Processing 3 of 10 creatives" ... ) """ if timestamp is None: timestamp = datetime.now(timezone.utc) if idempotency_key is None: idempotency_key = generate_webhook_idempotency_key() if not operation_id: raise ValueError( "operation_id is required for AdCP task webhooks; copy the buyer-supplied " "push_notification_config.operation_id verbatim" ) status_value = status.value if hasattr(status, "value") else str(status) task_type_value = task_type.value if hasattr(task_type, "value") else str(task_type) # Delivery reports are point-in-time events, not terminal task outcomes: # the spec omits notification_id and dedupes them by idempotency_key. if ( notification_id is None and task_type_value != "media_buy_delivery" and status_value in {"completed", "failed", "canceled", "rejected"} ): notification_id = f"{task_id}.terminal" # Auto-derive `protocol` from `task_type` when caller doesn't override. # Matches `protocolForTool` in the JS reference SDK so cross-SDK bodies # classify operations identically. if protocol is None: try: task_type_enum = task_type if isinstance(task_type, TaskType) else TaskType(task_type) except ValueError: # Unknown string — let `model_validate` raise the canonical # task_type error below rather than swallow it here. task_type_enum = None if task_type_enum is not None: protocol = _TASK_TYPE_TO_PROTOCOL.get(task_type_enum) # Foreign BaseModel subclasses (anything outside AdcpAsyncResponseData) # don't match the discriminated-union variants by identity — dump to a # dict so the union picks by shape, matching the dict path. result_value: PydanticBaseModel | dict[str, Any] | None if isinstance(result, PydanticBaseModel): result_value = result.model_dump(mode="json") else: result_value = result payload = McpWebhookPayload.model_validate( { "idempotency_key": idempotency_key, "notification_id": notification_id, "task_id": task_id, "task_type": task_type, "protocol": protocol, "status": status_value, "timestamp": timestamp, "operation_id": operation_id, "message": message, "context_id": context_id, "token": token, } ) # Preserve task result payloads byte-for-byte. Validating through the # generated AdcpAsyncResponseData union can coerce arbitrary dicts into # typed response models and inject response defaults, changing webhook # bodies before signing. payload.result = result_value # type: ignore[assignment] return payloadBuild an :class:
McpWebhookPayloadfor a tracked async task.Pair with :func:
to_wire_dict()for HTTP transport — Pydantic-typed at construction so the publisher catches schema drift before it leaves the process.task_typeis restricted to the closed :class:TaskTypeenum (the spec's complete set of async/tracked operations). Passing a value not present in the enum produces a validation error before an invalid webhook payload can leave the process.- Args
- -----=
task_id- Unique identifier for the task.
status- Current task status.
task_type- Type of AdCP async operation (see :class:
TaskType). result- Task-specific payload — any Pydantic model or plain dict.
Plain dicts are validated against
:class:
AdcpAsyncResponseData's discriminated union. timestamp- When the webhook was generated. Defaults to current UTC.
operation_id- Client-generated identifier supplied through the
registration's
push_notification_config.operation_id. Required for every task webhook; publishers echo it verbatim and MUST NOT derive it from the receiver URL. notification_id- Stable identity for one logical notification.
Terminal task webhooks default to
"{task_id}.terminal"so re-emissions under different delivery keys still converge.media_buy_deliveryreports get no default: they are point-in-time events deduped byidempotency_key. message- Human-readable summary of task state.
context_id- Session/conversation identifier.
protocol- AdCP protocol this task belongs to (see :class:
AdcpProtocol). Auto-derived fromtask_typewhen omitted, matching the JS SDK'sprotocolForToolso cross-SDK bodies classify operations identically. Pass an explicit value to override. idempotency_key- Sender-generated key stable across retries of the same event. Defaults to a freshly-generated UUID v4 — callers retrying delivery of the same event MUST pass the key from their first attempt; passing None twice mints two keys and defeats dedup.
token- Buyer-supplied token from
push_notification_config.token, echoed back per spec for authenticity validation.
Returns -----= :class:
McpWebhookPayloadinstance. Use :func:to_wire_dict()(orpayload.model_dump(mode="json", exclude_none=True)) to get the JSON-ready dict for HTTP transport.Examples -----= Create a completed webhook with results:
>>> from adcp.webhooks import create_mcp_webhook_payload, to_wire_dict >>> from adcp.types import GeneratedTaskStatus >>> >>> payload = create_mcp_webhook_payload( ... task_id="task_123", ... operation_id="op_123", ... status=GeneratedTaskStatus.completed, ... task_type="create_media_buy", ... result={"media_buy_id": "mb_1", "buyer_ref": "ref_1"}, ... message="Created campaign" ... ) >>> wire = to_wire_dict(payload)Create a failed webhook with error:
>>> payload = create_mcp_webhook_payload( ... task_id="task_456", ... operation_id="op_456", ... status=GeneratedTaskStatus.failed, ... task_type="create_media_buy", ... result={"errors": [{"code": "INVALID_INPUT", "message": "..."}]}, ... message="Validation failed" ... )Create a working status update:
>>> payload = create_mcp_webhook_payload( ... task_id="task_789", ... operation_id="op_789", ... status=GeneratedTaskStatus.working, ... task_type="sync_creatives", ... message="Processing 3 of 10 creatives" ... ) def create_test_agent(**overrides: Any) ‑> AgentConfig-
Expand source code
def create_test_agent(**overrides: Any) -> AgentConfig: """Create a custom test agent configuration. Useful when you need to modify the default test agent setup. Args: **overrides: Keyword arguments to override default config values Returns: Complete agent configuration Example: ```python from adcp.testing import create_test_agent from adcp.client import ADCPClient # Use default test agent with custom ID config = create_test_agent(id="my-test-agent") client = ADCPClient(config) ``` Example: ```python # Use A2A protocol instead of MCP from adcp.types.core import Protocol config = create_test_agent( protocol=Protocol.A2A, agent_uri="https://test-agent.adcontextprotocol.org" ) ``` """ base_config = TEST_AGENT_MCP_CONFIG.model_dump() base_config.update(overrides) return AgentConfig(**base_config)Create a custom test agent configuration.
Useful when you need to modify the default test agent setup.
- Args
- -----=
**overrides- Keyword arguments to override default config values
Returns -----= Complete agent configuration
Example -----=
from adcp.testing import create_test_agent from adcp.client import ADCPClient # Use default test agent with custom ID config = create_test_agent(id="my-test-agent") client = ADCPClient(config)Example -----=
# Use A2A protocol instead of MCP from adcp.types.core import Protocol config = create_test_agent( protocol=Protocol.A2A, agent_uri="https://test-agent.adcontextprotocol.org" ) def create_webhook_challenge_payload(*,
account_id: str,
subscriber_id: str,
seller_agent_url: str = <object object>,
event_types: Sequence[str] = <object object>,
authentication: AdCPBaseModel | Mapping[str, Any] | None = None,
challenge: str | None = None) ‑> dict[str, typing.Any]-
Expand source code
def create_webhook_challenge_payload( *, account_id: str, subscriber_id: str, seller_agent_url: str = _UNSET, event_types: Sequence[str] = _UNSET, authentication: AdCPBaseModel | Mapping[str, Any] | None = None, challenge: str | None = None, ) -> dict[str, Any]: """Build the durable ``notification_configs[]`` challenge payload. Pass ``seller_agent_url`` and ``event_types`` to build the AdCP 3.2 challenge, which is validated against the bundled schema and binds ``delivery_auth`` (``authentication`` for deprecated Bearer/HMAC configs). Omitting both is deprecated: it emits a :class:`DeprecationWarning` and returns the four-field challenge adcp 9.6 built. Both arguments become required in adcp 10.0. """ _check_challenge_fields_passed_together( "create_webhook_challenge_payload", seller_agent_url=seller_agent_url, event_types=event_types, ) if seller_agent_url is _UNSET: if authentication is not None: raise TypeError( "create_webhook_challenge_payload() binds authentication only into " "the AdCP 3.2 challenge; pass seller_agent_url and event_types too" ) _warn_missing_challenge_fields("create_webhook_challenge_payload", stacklevel=3) return _legacy_webhook_challenge_payload( account_id=account_id, subscriber_id=subscriber_id, challenge=challenge, ) return _build_webhook_challenge_payload( account_id=account_id, subscriber_id=subscriber_id, seller_agent_url=seller_agent_url, event_types=event_types, authentication=authentication, challenge=challenge, )Build the durable
notification_configs[]challenge payload.Pass
seller_agent_urlandevent_typesto build the AdCP 3.2 challenge, which is validated against the bundled schema and bindsdelivery_auth(authenticationfor deprecated Bearer/HMAC configs). Omitting both is deprecated: it emits a :class:DeprecationWarningand returns the four-field challenge adcp 9.6 built. Both arguments become required in adcp 10.0. async def detect_publisher_properties_divergence(agent_url: str,
*,
directory_url: str,
sample_size: int | None = 200,
max_concurrency: int = 20,
timeout: float = 30.0,
client: httpx.AsyncClient | None = None) ‑> list[PublisherDivergence]-
Expand source code
async def detect_publisher_properties_divergence( agent_url: str, *, directory_url: str, sample_size: int | None = 200, max_concurrency: int = 20, timeout: float = 30.0, client: httpx.AsyncClient | None = None, ) -> DivergenceReport: """Compare directory's inline resolution against per-publisher federated fetches. For each publisher the directory lists under ``agent_url``, fetches that publisher's own ``adagents.json`` and compares the property set against the directory's claim. Returns only publishers where the two paths disagree (or where the child fetch failed). Always requests ``include=["properties"]`` from the directory so the full ``(publisher_domain, property_id)`` set-diff lights up on directories that support adcp#4894. Against older directories that return only ``properties_authorized`` counts, falls back to count- comparison; ``missing_in_inline`` / ``missing_in_federated`` are None in that fallback path. Per adcp#4827 §Resolution-paths, the federated result is authoritative when the two paths disagree. Args: agent_url: agent to check. directory_url: AAO directory base URL (HTTPS only — same SSRF gate as :func:`fetch_agent_authorizations_from_directory`). sample_size: cap the sweep at N publishers (drawn from the first page of directory results). None opts into a full sweep across all pages — only do this for small networks. Default 200 keeps the divergence sweep bounded by default. max_concurrency: semaphore-capped concurrent federated fetches. Default 20 — caps the burst against publisher origins. timeout: per-request timeout (directory + child fetches). client: optional shared ``httpx.AsyncClient``. Returns: :data:`DivergenceReport` (``list[PublisherDivergence]``). Empty list = no divergence detected. Note in count-only fallback mode, an empty list means counts agree but set-equality is not guaranteed. """ http = client collected: list[DirectoryPublisherEntry] = [] cursor: str | None = None seen_cursors: set[str] = set() page_count = 0 while True: page = await fetch_agent_authorizations_from_directory( agent_url, directory_url=directory_url, cursor=cursor, include=["properties"], timeout=timeout, client=http, ) page_count += 1 collected.extend(page.publishers) if sample_size is not None and len(collected) >= sample_size: collected = collected[:sample_size] break cursor = page.next_cursor if not cursor: break if cursor in seen_cursors: raise AdagentsValidationError( f"Directory page cursor {cursor!r} repeated — refusing to loop forever." ) seen_cursors.add(cursor) if page_count >= MAX_DIRECTORY_PAGES: raise AdagentsValidationError( f"Directory pagination exceeded {MAX_DIRECTORY_PAGES} pages — aborting sweep." ) # Dedupe by publisher_domain before fan-out: a hostile directory # returning N rows for the same publisher would otherwise amplify # into N concurrent fetches against a single victim host. First # occurrence wins (deterministic) — conflicting property_ids / # properties_authorized across duplicates are dropped here; the # directory's behavior is itself a divergence signal for ops. seen_domains: set[str] = set() deduped: list[DirectoryPublisherEntry] = [] for entry in collected: if entry.publisher_domain in seen_domains: continue seen_domains.add(entry.publisher_domain) deduped.append(entry) collected = deduped # Emit a one-shot warning when the entire sample comes back without # property_ids[]. In count-only mode, same-count substitutions are # undetectable — adopters should pin include=["properties"] support # on directories that offer it. if collected and all(e.property_ids is None for e in collected): logger.warning( "AAO directory %s did not return property_ids[] on any publisher " "entry — falling back to count-only divergence detection. Same-count " "substitutions are undetectable in this mode. Upgrade the directory " "or pin include=['properties'] support.", directory_url, ) sem = asyncio.Semaphore(max_concurrency) async def _probe(entry: DirectoryPublisherEntry) -> PublisherDivergence | None: async with sem: try: data = await fetch_adagents(entry.publisher_domain, timeout=timeout, client=http) federated_props = get_properties_by_agent(data, agent_url) # Falsy/empty property_id is silently dropped: upstream # schema requires a non-empty string, so an empty value # is a structural violation that belongs in # validate_adagents, not a divergence signal. Federated # properties with valid IDs only. federated_ids = { str(p.get("property_id")) for p in federated_props if p.get("property_id") } except ( AdagentsNotFoundError, AdagentsValidationError, AdagentsTimeoutError, httpx.HTTPError, OSError, ValueError, ) as exc: return PublisherDivergence( publisher_domain=entry.publisher_domain, directory_properties_authorized=entry.properties_authorized, federated_properties_found=0, missing_in_inline=None, missing_in_federated=None, child_fetch_error=str(exc), ) if entry.property_ids is not None: # Full set-diff path (adcp#4894). dir_ids = set(entry.property_ids) missing_in_inline = sorted(federated_ids - dir_ids) missing_in_federated = sorted(dir_ids - federated_ids) if not missing_in_inline and not missing_in_federated: return None return PublisherDivergence( publisher_domain=entry.publisher_domain, directory_properties_authorized=entry.properties_authorized, federated_properties_found=len(federated_ids), missing_in_inline=missing_in_inline, missing_in_federated=missing_in_federated, ) # Count-only fallback (older directories). if len(federated_ids) == entry.properties_authorized: return None return PublisherDivergence( publisher_domain=entry.publisher_domain, directory_properties_authorized=entry.properties_authorized, federated_properties_found=len(federated_ids), missing_in_inline=None, missing_in_federated=None, ) probes = await asyncio.gather(*[_probe(e) for e in collected]) return [p for p in probes if p is not None]Compare directory's inline resolution against per-publisher federated fetches.
For each publisher the directory lists under
agent_url, fetches that publisher's ownadagents.jsonand compares the property set against the directory's claim. Returns only publishers where the two paths disagree (or where the child fetch failed).Always requests
include=["properties"]from the directory so the full(publisher_domain, property_id)set-diff lights up on directories that support adcp#4894. Against older directories that return onlyproperties_authorizedcounts, falls back to count- comparison;missing_in_inline/missing_in_federatedare None in that fallback path.Per adcp#4827 §Resolution-paths, the federated result is authoritative when the two paths disagree.
- Args
- -----=
agent_url- agent to check.
directory_url- AAO directory base URL (HTTPS only — same SSRF
gate as :func:
fetch_agent_authorizations_from_directory()). sample_size- cap the sweep at N publishers (drawn from the first page of directory results). None opts into a full sweep across all pages — only do this for small networks. Default 200 keeps the divergence sweep bounded by default.
max_concurrency- semaphore-capped concurrent federated fetches. Default 20 — caps the burst against publisher origins.
timeout- per-request timeout (directory + child fetches).
client- optional shared
httpx.AsyncClient.
Returns -----= :data:
DivergenceReport(list[PublisherDivergence]). Empty list = no divergence detected. Note in count-only fallback mode, an empty list means counts agree but set-equality is not guaranteed. async def discover_oauth_metadata(issuer_url: str, *, timeout: float = 5.0, allow_loopback_http: bool = False) ‑> OAuthAuthorizationServerMetadata-
Expand source code
async def discover_oauth_metadata( issuer_url: str, *, timeout: float = 5.0, allow_loopback_http: bool = False, ) -> OAuthAuthorizationServerMetadata: """Discover and validate RFC 8414 metadata for an exact issuer URL. ``issuer_url`` is an authorization-server issuer, not an MCP/HTTP resource URL. The returned ``issuer`` must match it exactly. Plain HTTP is available only for literal loopback IPs when ``allow_loopback_http=True``. """ if isinstance(timeout, bool) or not math.isfinite(timeout) or timeout <= 0 or timeout > 60: raise ValueError("timeout must be greater than 0 and at most 60 seconds") discovery_url = _metadata_url(issuer_url, allow_loopback_http=allow_loopback_http) async def fetch() -> Mapping[str, Any]: transport = await _transport_for( discovery_url, allow_loopback_http=allow_loopback_http, ) async with httpx.AsyncClient( transport=transport, timeout=timeout, follow_redirects=False, trust_env=False, ) as client: async with client.stream( "GET", discovery_url, headers={"accept": "application/json", "accept-encoding": "identity"}, ) as response: if response.status_code != 200: raise OAuthDiscoveryError( "http_error", phase="discovery", status_code=response.status_code ) return await _read_json_response(response, phase="discovery") try: raw = await _run_with_deadline(fetch, timeout) except _OAuthDeadlineExpired: raise OAuthDiscoveryError("timeout", phase="discovery") from None except OAuthDiscoveryError: raise except OAuthClientError as exc: raise OAuthDiscoveryError( exc.code, phase="discovery", status_code=exc.status_code ) from None except (httpx.HTTPError, OSError, SSRFValidationError, ValueError): raise OAuthDiscoveryError("network_error", phase="discovery") from None try: metadata = OAuthAuthorizationServerMetadata.model_validate(raw) except ValidationError: raise OAuthDiscoveryError("invalid_metadata", phase="discovery") from None if metadata.issuer != issuer_url: raise OAuthDiscoveryError("issuer_mismatch", phase="discovery") _validate_public_client_metadata(metadata, allow_loopback_http=allow_loopback_http) return metadataDiscover and validate RFC 8414 metadata for an exact issuer URL.
issuer_urlis an authorization-server issuer, not an MCP/HTTP resource URL. The returnedissuermust match it exactly. Plain HTTP is available only for literal loopback IPs whenallow_loopback_http=True. async def dispatch_media_buy_action(client: ActionDispatchClient,
assessment: MediaBuyActionAssessment,
request: BaseModel,
*,
options: Any | None = None) ‑> Any-
Expand source code
async def dispatch_media_buy_action( client: ActionDispatchClient, assessment: MediaBuyActionAssessment, request: BaseModel, *, options: Any | None = None, ) -> Any: """Dispatch an already-assessed action through its canonical task. The caller still supplies the task-specific generated request model. This helper owns only the action-to-task decision and refuses unavailable or unknown actions. ``seller_managed`` uses the same ordinary async task lifecycle as every other mode; no internal approval workflow is inferred. """ if assessment.status is not ActionAvailabilityStatus.available_now: raise MediaBuyActionError("action_not_available", "status") if assessment.task is None: raise MediaBuyActionError("unknown_action_route", "task") return await client.execute_task(assessment.task.value, request, options=options)Dispatch an already-assessed action through its canonical task.
The caller still supplies the task-specific generated request model. This helper owns only the action-to-task decision and refuses unavailable or unknown actions.
seller_manageduses the same ordinary async task lifecycle as every other mode; no internal approval workflow is inferred. def domain_matches(property_domain: str, agent_domain_pattern: str) ‑> bool-
Expand source code
def domain_matches(property_domain: str, agent_domain_pattern: str) -> bool: """Check if domains match per AdCP rules. Rules: - Exact match always succeeds - 'example.com' matches www.example.com, m.example.com (common subdomains) - 'subdomain.example.com' matches that specific subdomain only - '*.example.com' matches all subdomains Args: property_domain: Domain from property agent_domain_pattern: Domain pattern from adagents.json Returns: True if domains match per AdCP rules """ # Normalize both domains for comparison try: property_domain = _normalize_domain(property_domain) agent_domain_pattern = _normalize_domain(agent_domain_pattern) except AdagentsValidationError: # Invalid domain format - no match return False # Exact match if property_domain == agent_domain_pattern: return True # Wildcard pattern (*.example.com) if agent_domain_pattern.startswith("*."): base_domain = agent_domain_pattern[2:] return property_domain.endswith(f".{base_domain}") # Bare domain matches common subdomains (www, m) # If agent pattern is a bare domain (no subdomain), match www/m subdomains if "." in agent_domain_pattern and not agent_domain_pattern.startswith("www."): # Check if this looks like a bare domain (e.g., example.com) parts = agent_domain_pattern.split(".") if len(parts) == 2: # Looks like bare domain common_subdomains = ["www", "m"] for subdomain in common_subdomains: if property_domain == f"{subdomain}.{agent_domain_pattern}": return True return FalseCheck if domains match per AdCP rules.
Rules: - Exact match always succeeds - 'example.com' matches www.example.com, m.example.com (common subdomains) - 'subdomain.example.com' matches that specific subdomain only - '*.example.com' matches all subdomains
- Args
- -----=
property_domain- Domain from property
agent_domain_pattern- Domain pattern from adagents.json
Returns -----= True if domains match per AdCP rules
def encode_unreserved(raw: str) ‑> str-
Expand source code
def encode_unreserved(raw: str) -> str: """UTF-8 encode ``raw``, escaping every byte outside RFC 3986 unreserved. Percent escapes use uppercase hexadecimal. Unlike :func:`urllib.parse.quote`, this helper does not preserve ``/``. """ return "".join( chr(byte) if byte in _UNRESERVED_BYTES else f"%{byte:02X}" for byte in raw.encode("utf-8") )UTF-8 encode
raw, escaping every byte outside RFC 3986 unreserved.Percent escapes use uppercase hexadecimal. Unlike :func:
urllib.parse.quote, this helper does not preserve/. def evaluate_action_constraints(action: str,
constraints: Any | None,
intent: ActionIntent,
*,
now: datetime | None = None) ‑> tuple[ConstraintCheck, ...]-
Expand source code
def evaluate_action_constraints( action: str, constraints: Any | None, intent: ActionIntent, *, now: datetime | None = None, ) -> tuple[ConstraintCheck, ...]: """Evaluate portable constraints without interpreting opaque conditions.""" constraint = _as_mapping(constraints) if not constraint: return () kind = _string_value(constraint.get("kind")) if kind is None or action not in _CONSTRAINT_ACTIONS.get(kind, frozenset()): return ( ConstraintCheck( kind=kind or "unknown", constraint="kind", outcome=ConstraintOutcome.unknown, field=intent.field, ), ) if kind == "budget": return _evaluate_budget_constraints(constraint, intent) if kind == "flight": return _evaluate_flight_constraints(constraint, intent, now=now) if kind == "package_count": return _evaluate_package_constraints(constraint, intent) if kind == "effective_timing": return _evaluate_effective_timing_constraints(constraint, intent, now=now) return ()Evaluate portable constraints without interpreting opaque conditions.
def extract_adcp_error_info(err: Any) ‑> AdcpErrorInfo-
Expand source code
def extract_adcp_error_info(err: Any) -> AdcpErrorInfo: """Normalize a single ADCP error entry into a typed `AdcpErrorInfo`. Accepts pydantic `Error` models, plain dicts (raw JSON), and duck-typed objects with the same attribute names. Missing fields become `None`; an unknown `recovery` string normalizes to `None`. """ raw_buyer_reason = _access(err, "buyer_reason") buyer_reason: BuyerReasonInfo | None = None if raw_buyer_reason is not None: code = _access(raw_buyer_reason, "code") message = _access(raw_buyer_reason, "message") if isinstance(code, str) and isinstance(message, str) and code and message: buyer_reason = BuyerReasonInfo(code=code, message=message) retry_after_raw = _access(err, "retry_after") retry_after: float | None = None # Reject `bool` (a subclass of `int` in Python — `retry_after: true` from a # non-conforming producer would otherwise become `1.0` and schedule a real # retry), any non-finite float (NaN/inf), and any value outside the AdCP # spec's [1, 3600] range at `core/error.json`. The generated pydantic # `Error` model enforces the range; this extractor also serves raw-dict # and duck-typed inputs that bypass that validation, so we enforce here # too — a negative value would schedule an immediate retry, and a very # large value would stall the loop for hours. if ( isinstance(retry_after_raw, (int, float)) and not isinstance(retry_after_raw, bool) and math.isfinite(retry_after_raw) and 1 <= retry_after_raw <= 3600 ): retry_after = float(retry_after_raw) details_raw = _access(err, "details") details: dict[str, Any] | None = details_raw if isinstance(details_raw, dict) else None return AdcpErrorInfo( code=_access(err, "code"), message=_access(err, "message"), recovery=_normalize_recovery(_access(err, "recovery")), buyer_reason=buyer_reason, field=_access(err, "field"), suggestion=_access(err, "suggestion"), retry_after=retry_after, details=details, )Normalize a single ADCP error entry into a typed
AdcpErrorInfo.Accepts pydantic
Errormodels, plain dicts (raw JSON), and duck-typed objects with the same attribute names. Missing fields becomeNone; an unknownrecoverystring normalizes toNone. def extract_webhook_result_data(webhook_payload: dict[str, Any]) ‑> dict[str, typing.Any] | None-
Expand source code
def extract_webhook_result_data(webhook_payload: dict[str, Any]) -> dict[str, Any] | None: """ Extract result data from webhook payload (MCP or A2A format). This utility function handles webhook payloads from both MCP and A2A protocols, extracting the result data regardless of the webhook format. Useful for quick inspection, logging, or custom webhook routing logic without requiring full client initialization. Protocol Detection: - A2A Task: Has "artifacts" field (terminated statuses: completed, failed, canceled, rejected) - A2A TaskStatusUpdateEvent: Has nested "status.message" structure (intermediate statuses) - MCP: Has "result" field directly Args: webhook_payload: Raw webhook dictionary from HTTP request (JSON-deserialized) Returns: dict[str, Any] containing the extracted AdCP response data, or None if no result is present. For A2A webhooks, unwraps data from artifacts/message parts structure. For MCP webhooks, returns the result field directly. Examples: Extract from MCP webhook: >>> mcp_payload = { ... "task_id": "task_123", ... "task_type": "create_media_buy", ... "status": "completed", ... "timestamp": "2025-01-15T10:00:00Z", ... "result": {"media_buy_id": "mb_123", "buyer_ref": "ref_123", "packages": []} ... } >>> result = extract_webhook_result_data(mcp_payload) >>> print(result["media_buy_id"]) mb_123 Extract from A2A Task webhook: >>> a2a_task_payload = { ... "id": "task_456", ... "context_id": "ctx_456", ... "status": {"state": "completed", "timestamp": "2025-01-15T10:00:00Z"}, ... "artifacts": [ ... { ... "artifact_id": "artifact_456", ... "parts": [ ... { ... "data": { ... "media_buy_id": "mb_456", ... "buyer_ref": "ref_456", ... "packages": [] ... } ... } ... ] ... } ... ] ... } >>> result = extract_webhook_result_data(a2a_task_payload) >>> print(result["media_buy_id"]) mb_456 Extract from A2A TaskStatusUpdateEvent webhook: >>> a2a_event_payload = { ... "task_id": "task_789", ... "context_id": "ctx_789", ... "status": { ... "state": "working", ... "timestamp": "2025-01-15T10:00:00Z", ... "message": { ... "message_id": "msg_789", ... "role": "agent", ... "parts": [ ... {"data": {"current_step": "processing", "percentage": 50}} ... ] ... } ... }, ... "final": False ... } >>> result = extract_webhook_result_data(a2a_event_payload) >>> print(result["percentage"]) 50 Handle webhook with no result: >>> empty_payload = {"task_id": "task_000", "status": "working", "timestamp": "..."} >>> result = extract_webhook_result_data(empty_payload) >>> print(result) None """ # Detect A2A Task format (has "artifacts" field) if "artifacts" in webhook_payload: # Extract from task.artifacts[].parts[] artifacts = webhook_payload.get("artifacts", []) if not artifacts: return None # Use last artifact (most recent) target_artifact = artifacts[-1] parts = target_artifact.get("parts", []) if not parts: return None # Find DataPart (skip TextPart) for part in parts: # Check if this part has "data" field (DataPart) if "data" in part: data = part["data"] # Unwrap {"response": {...}} wrapper if present (A2A convention) if isinstance(data, dict) and "response" in data and len(data) == 1: return cast(dict[str, Any], data["response"]) return cast(dict[str, Any], data) return None # Detect A2A TaskStatusUpdateEvent format (has nested "status.message") status = webhook_payload.get("status") if isinstance(status, dict): message = status.get("message") if isinstance(message, dict): # Extract from status.message.parts[] parts = message.get("parts", []) if not parts: return None # Find DataPart for part in parts: if "data" in part: data = part["data"] # Unwrap {"response": {...}} wrapper if present if isinstance(data, dict) and "response" in data and len(data) == 1: return cast(dict[str, Any], data["response"]) return cast(dict[str, Any], data) return None # MCP format: result field directly return cast(dict[str, Any] | None, webhook_payload.get("result"))Extract result data from webhook payload (MCP or A2A format).
This utility function handles webhook payloads from both MCP and A2A protocols, extracting the result data regardless of the webhook format. Useful for quick inspection, logging, or custom webhook routing logic without requiring full client initialization.
Protocol Detection: - A2A Task: Has "artifacts" field (terminated statuses: completed, failed, canceled, rejected) - A2A TaskStatusUpdateEvent: Has nested "status.message" structure (intermediate statuses) - MCP: Has "result" field directly
- Args
- -----=
webhook_payload- Raw webhook dictionary from HTTP request (JSON-deserialized)
Returns -----= dict[str, Any] containing the extracted AdCP response data, or None if no result is present. For A2A webhooks, unwraps data from artifacts/message parts structure. For MCP webhooks, returns the result field directly.
Examples -----= Extract from MCP webhook:
>>> mcp_payload = { ... "task_id": "task_123", ... "task_type": "create_media_buy", ... "status": "completed", ... "timestamp": "2025-01-15T10:00:00Z", ... "result": {"media_buy_id": "mb_123", "buyer_ref": "ref_123", "packages": []} ... } >>> result = extract_webhook_result_data(mcp_payload) >>> print(result["media_buy_id"]) mb_123Extract from A2A Task webhook:
>>> a2a_task_payload = { ... "id": "task_456", ... "context_id": "ctx_456", ... "status": {"state": "completed", "timestamp": "2025-01-15T10:00:00Z"}, ... "artifacts": [ ... { ... "artifact_id": "artifact_456", ... "parts": [ ... { ... "data": { ... "media_buy_id": "mb_456", ... "buyer_ref": "ref_456", ... "packages": [] ... } ... } ... ] ... } ... ] ... } >>> result = extract_webhook_result_data(a2a_task_payload) >>> print(result["media_buy_id"]) mb_456Extract from A2A TaskStatusUpdateEvent webhook:
>>> a2a_event_payload = { ... "task_id": "task_789", ... "context_id": "ctx_789", ... "status": { ... "state": "working", ... "timestamp": "2025-01-15T10:00:00Z", ... "message": { ... "message_id": "msg_789", ... "role": "agent", ... "parts": [ ... {"data": {"current_step": "processing", "percentage": 50}} ... ] ... } ... }, ... "final": False ... } >>> result = extract_webhook_result_data(a2a_event_payload) >>> print(result["percentage"]) 50Handle webhook with no result:
>>> empty_payload = {"task_id": "task_000", "status": "working", "timestamp": "..."} >>> result = extract_webhook_result_data(empty_payload) >>> print(result) None async def fetch_adagents(publisher_domain: str,
timeout: float = 10.0,
user_agent: str = 'AdCP-Client/1.0',
client: httpx.AsyncClient | None = None,
*,
validate_structure: bool = True,
transport_factory: AdagentsTransportFactory | None = None) ‑> dict[str, typing.Any]-
Expand source code
async def fetch_adagents( publisher_domain: str, timeout: float = 10.0, user_agent: str = "AdCP-Client/1.0", client: httpx.AsyncClient | None = None, *, validate_structure: bool = True, transport_factory: AdagentsTransportFactory | None = None, ) -> dict[str, Any]: """Fetch and parse adagents.json from publisher domain. Discovery order: 1. ``https://{publisher}/.well-known/adagents.json`` (direct). 2. ``authoritative_location`` redirect, if the direct response is a URL reference. 3. IAB ads.txt MANAGERDOMAIN fallback, on direct 404 only: fetches ``https://{publisher}/ads.txt`` for a ``MANAGERDOMAIN=`` directive and, if present, tries ``https://{manager}/.well-known/adagents.json``. The ads.txt fetch follows up to five HTTPS redirects within a single timeout, permitting same-root redirects followed by one terminal off-root hop. Manager delegation remains one-hop only. If the manager domain also 404s, this raises :class:`AdagentsNotFoundError` for the original publisher — not a silent pass. Args: publisher_domain: Domain hosting the adagents.json file. timeout: Request timeout in seconds. user_agent: User-Agent header for HTTP request. client: Optional caller-owned client for the initial publisher request. The caller controls its transport and lifecycle. Redirect targets and manager manifests use fresh SDK-owned client contexts. validate_structure: Validate authorization entry structure (default True). False permits bare entries without relaxing fetch security checks. transport_factory: Optional factory for SDK-owned hops, receiving the URL and timeout. Defaults to an IP-pinned, proxy-disabled client. Custom factories must supply their own transport-level rebinding protection. Returns: Parsed adagents.json data (resolved via authoritative_location or ads.txt MANAGERDOMAIN if applicable). Raises: AdagentsNotFoundError: If adagents.json was not found via any discovery path. AdagentsAccessBlockedError: If the publisher's CDN returns HTTP 403 with ``cf-mitigated: challenge`` (Cloudflare bot-management block). Subclass of ``AdagentsValidationError``. AdagentsHTTPError: On other unsuccessful HTTP statuses; carries ``status_code`` and ``url`` and subclasses AdagentsValidationError. AdagentsValidationError: If JSON is invalid, malformed, or redirects exceed maximum depth or form a loop. AdagentsTimeoutError: If request times out. Notes: For production use with multiple requests, pass a shared httpx.AsyncClient to enable connection pooling. Callers who need to know which discovery path produced the data (direct, authoritative_location, or ads_txt_managerdomain) should call :func:`validate_adagents_domain` instead. Strict authorization structure validation is enabled by default. Pass ``validate_structure=False`` to fetch bare-entry documents, then inspect :func:`validate_adagents_structure` and explicitly choose a :func:`resolve_properties_for_agent` mode. This opt-out preserves JSON, endpoint, renderer-origin, SSRF and body-size checks. """ publisher_domain = _validate_publisher_domain(publisher_domain) try: data, *_ = await _resolve_direct( publisher_domain, timeout, user_agent, client, validate_structure=validate_structure, transport_factory=transport_factory, ) return data except AdagentsNotFoundError: manager_data = await _try_managerdomain_fallback( publisher_domain, timeout, user_agent, client, validate_structure=validate_structure, transport_factory=transport_factory, ) if manager_data is not None: return manager_data raiseFetch and parse adagents.json from publisher domain.
Discovery order:
https://{publisher}/.well-known/adagents.json(direct).authoritative_locationredirect, if the direct response is a URL reference.- IAB ads.txt MANAGERDOMAIN fallback, on direct 404 only:
fetches
https://{publisher}/ads.txtfor aMANAGERDOMAIN=directive and, if present, trieshttps://{manager}/.well-known/adagents.json.
The ads.txt fetch follows up to five HTTPS redirects within a single timeout, permitting same-root redirects followed by one terminal off-root hop. Manager delegation remains one-hop only. If the manager domain also 404s, this raises :class:
AdagentsNotFoundErrorfor the original publisher — not a silent pass.- Args
- -----=
publisher_domain- Domain hosting the adagents.json file.
timeout- Request timeout in seconds.
user_agent- User-Agent header for HTTP request.
client- Optional caller-owned client for the initial publisher request. The caller controls its transport and lifecycle. Redirect targets and manager manifests use fresh SDK-owned client contexts.
validate_structure- Validate authorization entry structure (default True). False permits bare entries without relaxing fetch security checks.
transport_factory- Optional factory for SDK-owned hops, receiving the URL and timeout. Defaults to an IP-pinned, proxy-disabled client. Custom factories must supply their own transport-level rebinding protection.
Returns -----= Parsed adagents.json data (resolved via authoritative_location or ads.txt MANAGERDOMAIN if applicable).
- Raises
- -----=
AdagentsNotFoundError- If adagents.json was not found via any discovery path.
AdagentsAccessBlockedError- If the publisher's CDN returns HTTP
403 with
cf-mitigated: challenge(Cloudflare bot-management block). Subclass ofAdagentsValidationError. AdagentsHTTPError- On other unsuccessful HTTP statuses; carries
status_codeandurland subclasses AdagentsValidationError. AdagentsValidationError- If JSON is invalid, malformed, or redirects exceed maximum depth or form a loop.
AdagentsTimeoutError- If request times out.
Notes -----= For production use with multiple requests, pass a shared httpx.AsyncClient to enable connection pooling.
Callers who need to know which discovery path produced the data (direct, authoritative_location, or ads_txt_managerdomain) should call :func:
validate_adagents_domain()instead.Strict authorization structure validation is enabled by default. Pass
validate_structure=Falseto fetch bare-entry documents, then inspect :func:validate_adagents_structure()and explicitly choose a :func:resolve_properties_for_agent()mode. This opt-out preserves JSON, endpoint, renderer-origin, SSRF and body-size checks. async def fetch_adagents_with_cache(publisher_domain: str,
cache_entry: AdagentsCacheEntry | None = None,
timeout: float = 10.0,
user_agent: str = 'AdCP-Client/1.0',
client: httpx.AsyncClient | None = None,
*,
validate_structure: bool = True,
transport_factory: AdagentsTransportFactory | None = None) ‑> AdagentsFetchResult-
Expand source code
async def fetch_adagents_with_cache( publisher_domain: str, cache_entry: AdagentsCacheEntry | None = None, timeout: float = 10.0, user_agent: str = "AdCP-Client/1.0", client: httpx.AsyncClient | None = None, *, validate_structure: bool = True, transport_factory: AdagentsTransportFactory | None = None, ) -> AdagentsFetchResult: """Fetch with conditional refresh — returns body plus refreshed validators. Pass the previous fetch's :class:`AdagentsCacheEntry` to send ``If-None-Match`` / ``If-Modified-Since`` on the next fetch. A 304 from the publisher is treated as a successful refresh: the cached ``body`` is returned with ``not_modified=True``, satisfying the 7-day cache window described in adcp#4504. Cached bodies undergo the same document and renderer checks as a fresh response, including the current ``validate_structure`` policy. Switching from an opt-out fetch to a strict refresh therefore validates the cached document before returning it; a successful refresh preserves body identity. The first hop (``/.well-known/adagents.json``) is capped at 5 MiB; a dereferenced ``authoritative_location`` file is capped at 20 MiB. Both caps fail closed — oversized responses raise :class:`AdagentsValidationError` rather than truncate. Does NOT perform the ads.txt ``managerdomain`` fallback; the fallback is best-effort discovery, not cache-aware refresh, and bypassing it on 304 keeps the path simple. Callers that need both behaviors should compose this helper with :func:`validate_adagents_domain`. """ publisher_domain = _validate_publisher_domain(publisher_domain) data, discovery, etag, last_modified, not_modified = await _resolve_direct( publisher_domain, timeout, user_agent, client, cache_entry=cache_entry, validate_structure=validate_structure, transport_factory=transport_factory, ) return AdagentsFetchResult( data=data, discovery_method=discovery, etag=etag, last_modified=last_modified, not_modified=not_modified, )Fetch with conditional refresh — returns body plus refreshed validators.
Pass the previous fetch's :class:
AdagentsCacheEntryto sendIf-None-Match/If-Modified-Sinceon the next fetch. A 304 from the publisher is treated as a successful refresh: the cachedbodyis returned withnot_modified=True, satisfying the 7-day cache window described in adcp#4504.Cached bodies undergo the same document and renderer checks as a fresh response, including the current
validate_structurepolicy. Switching from an opt-out fetch to a strict refresh therefore validates the cached document before returning it; a successful refresh preserves body identity.The first hop (
/.well-known/adagents.json) is capped at 5 MiB; a dereferencedauthoritative_locationfile is capped at 20 MiB. Both caps fail closed — oversized responses raise :class:AdagentsValidationErrorrather than truncate.Does NOT perform the ads.txt
managerdomainfallback; the fallback is best-effort discovery, not cache-aware refresh, and bypassing it on 304 keeps the path simple. Callers that need both behaviors should compose this helper with :func:validate_adagents_domain(). -
Expand source code
async def fetch_agent_authorizations( agent_url: str, publisher_domains: list[str], timeout: float = 10.0, client: httpx.AsyncClient | None = None, ) -> dict[str, AuthorizationContext]: """Fetch authorization contexts by checking publisher adagents.json files. This function discovers what publishers have authorized your agent by fetching their adagents.json files from the .well-known directory and extracting the properties your agent can access. This is the "pull" approach - you query publishers to see if they've authorized you. Args: agent_url: URL of your sales agent publisher_domains: List of publisher domains to check (e.g., ["nytimes.com", "wsj.com"]) timeout: Request timeout in seconds for each fetch client: Optional httpx.AsyncClient for connection pooling Returns: Dictionary mapping publisher domain to AuthorizationContext. Only includes domains where the agent is authorized. Example: >>> # "Pull" approach - check what publishers have authorized you >>> contexts = await fetch_agent_authorizations( ... "https://our-sales-agent.com", ... ["nytimes.com", "wsj.com", "cnn.com"] ... ) >>> for domain, ctx in contexts.items(): ... print(f"{domain}:") ... print(f" Property IDs: {ctx.property_ids}") ... print(f" Tags: {ctx.property_tags}") Notes: - Silently skips domains where adagents.json is not found or invalid - Only returns domains where the agent is explicitly authorized - For production use with many domains, pass a shared httpx.AsyncClient to enable connection pooling """ import asyncio # Create tasks to fetch all adagents.json files in parallel async def fetch_authorization_for_domain( domain: str, ) -> tuple[str, AuthorizationContext | None]: """Fetch authorization context for a single domain.""" try: adagents_data = await fetch_adagents(domain, timeout=timeout, client=client) # Check if agent is authorized if not verify_agent_authorization(adagents_data, agent_url): return (domain, None) # Get properties for this agent properties = get_properties_by_agent(adagents_data, agent_url) # Create authorization context return (domain, AuthorizationContext(properties)) except (AdagentsNotFoundError, AdagentsValidationError, AdagentsTimeoutError): # Silently skip domains with missing or invalid adagents.json. # AdagentsAccessBlockedError (AdagentsValidationError subclass) is # intentionally swallowed: a bot-blocked domain is treated as # authorization-unavailable, same as a missing file. return (domain, None) # Fetch all domains in parallel tasks = [fetch_authorization_for_domain(domain) for domain in publisher_domains] results = await asyncio.gather(*tasks) # Build result dictionary, filtering out None values return {domain: ctx for domain, ctx in results if ctx is not None}Fetch authorization contexts by checking publisher adagents.json files.
This function discovers what publishers have authorized your agent by fetching their adagents.json files from the .well-known directory and extracting the properties your agent can access.
This is the "pull" approach - you query publishers to see if they've authorized you.
- Args
- -----=
agent_url- URL of your sales agent
publisher_domains- List of publisher domains to check (e.g., ["nytimes.com", "wsj.com"])
timeout- Request timeout in seconds for each fetch
client- Optional httpx.AsyncClient for connection pooling
Returns -----= Dictionary mapping publisher domain to AuthorizationContext. Only includes domains where the agent is authorized.
Example -----=
>>> # "Pull" approach - check what publishers have authorized you >>> contexts = await fetch_agent_authorizations( ... "https://our-sales-agent.com", ... ["nytimes.com", "wsj.com", "cnn.com"] ... ) >>> for domain, ctx in contexts.items(): ... print(f"{domain}:") ... print(f" Property IDs: {ctx.property_ids}") ... print(f" Tags: {ctx.property_tags}")Notes -----= - Silently skips domains where adagents.json is not found or invalid - Only returns domains where the agent is explicitly authorized - For production use with many domains, pass a shared httpx.AsyncClient to enable connection pooling
-
Expand source code
async def fetch_agent_authorizations_from_directory( agent_url: str, *, directory_url: str, since: str | None = None, cursor: str | None = None, include: list[str] | None = None, timeout: float = 10.0, client: httpx.AsyncClient | None = None, ) -> AgentAuthorizationsDirectoryResult: """Query an AAO directory for publishers that authorize ``agent_url``. Calls ``GET {directory_url}/v1/agents/{agent_url}/publishers`` per the AAO inverse-lookup contract (adcp#4823 / #4828) and returns the parsed response. The directory's answer is *discovery*, not authorization: callers should still verify each returned ``publisher_domain`` via :func:`fetch_adagents` before treating an edge as trusted. Args: agent_url: The agent whose publisher authorizations are being queried. Passed verbatim in the path; the directory echoes back a canonicalized form on the response. directory_url: HTTPS base URL of the AAO directory (e.g. ``"https://aao.example.com"``). The ``/v1/agents/...`` path is appended; pass the directory's root, not a request-specific path. since: Optional RFC 3339 timestamp from a prior ``directory_indexed_at`` — passed through as ``?since=...`` to limit the result to edges that changed since that point. cursor: Optional opaque pagination cursor from a prior response's ``next_cursor`` — passed through as ``?cursor=...`` to fetch the next page. include: Optional list of expansion keys per the AAO directory API spec (adcp#4894). Each value is emitted as a separate ``?include=<value>`` query parameter (repeated-key form, not comma-joined). Pass ``["properties"]`` against directories that support it to receive per-publisher ``property_ids[]`` on each row, enabling full set-diff against the publisher's own adagents.json. Directories that don't support a given expansion key simply omit the corresponding fields from the response; callers should treat absence as count-only mode. timeout: Request timeout in seconds. client: Optional shared ``httpx.AsyncClient`` for connection pooling. Caller owns the client lifecycle. Returns: :class:`AgentAuthorizationsDirectoryResult`. On 404 from the directory the function returns a result with ``publishers=[]`` and ``directory_indexed_at=None`` — directories MUST be allowed to answer "I do not index this agent" without callers needing to branch on exception type. Raises: AdagentsValidationError: If ``directory_url`` is malformed, the response status is non-200/non-404, the body is not valid JSON, or the body does not match the directory result schema. AdagentsTimeoutError: If the request times out. Notes: - ``directory_url`` is gated through the same SSRF protection (HTTPS only, DNS pre-check, private/reserved address ban) as publisher-side fetches. - Response bodies are capped at 5 MiB. Bulk responses paginate via ``next_cursor``; pass that value as ``cursor`` on the next call. """ if not isinstance(agent_url, str) or not agent_url: raise AdagentsValidationError("agent_url must be a non-empty string") if not isinstance(directory_url, str) or not directory_url: raise AdagentsValidationError("directory_url must be a non-empty string") base = directory_url.rstrip("/") if not base.startswith("https://"): raise AdagentsValidationError(f"directory_url must be an HTTPS URL, got: {directory_url!r}") _validate_redirect_url(f"{base}/v1/agents/_/publishers") request_url = f"{base}/v1/agents/{quote(agent_url, safe='')}/publishers" query_pairs: list[tuple[str, str]] = [] if since is not None: query_pairs.append(("since", since)) if cursor is not None: query_pairs.append(("cursor", cursor)) if include: # Repeated-key form per docs/aao/directory-api.mdx (style: form, # explode: true). Comma-joined NOT accepted by spec-conformant # directories. for value in include: query_pairs.append(("include", value)) if query_pairs: query_string = "&".join(f"{quote(k, safe='')}={quote(v, safe='')}" for k, v in query_pairs) request_url = f"{request_url}?{query_string}" parsed = urlparse(request_url) await _dns_validate_host( parsed.hostname or "", parsed.port or (443 if parsed.scheme == "https" else 80) ) headers = {"User-Agent": "AdCP-Client/1.0", "Accept": "application/json"} # SDK-owned client is pinned to the validated IP (see _fetch_adagents_url). # A failed resolve/SSRF check raises AdagentsValidationError, which # propagates past the httpx handlers below — the correct fail-closed # outcome (we do not convert it into an empty result). try: if client is not None: body, status_code, _ = await _stream_capped( client, request_url, headers, timeout, MAX_DIRECTORY_PAGE_BYTES ) else: async with _owned_pinned_client(request_url, timeout) as new_client: body, status_code, _ = await _stream_capped( new_client, request_url, headers, timeout, MAX_DIRECTORY_PAGE_BYTES ) except httpx.TimeoutException as e: raise AdagentsTimeoutError(parsed.netloc, timeout) from e except httpx.RequestError as e: raise AdagentsValidationError(f"Failed to fetch agent-publishers directory: {e}") from e if status_code == 404: # Per adcp#4828, a directory that has not indexed this agent # answers 404. Surface as an empty result so callers don't need # to special-case the exception path for "no edges" — the # protocol is intentionally permissive here. return AgentAuthorizationsDirectoryResult( agent_url=agent_url, directory_indexed_at=None, publishers=[], next_cursor=None, ) if status_code != 200: raise AdagentsValidationError(f"Agent-publishers directory returned HTTP {status_code}") try: data = json.loads(body) except json.JSONDecodeError as e: raise AdagentsValidationError( f"Invalid JSON in agent-publishers directory response: {str(e)[:200]}" ) from e try: return AgentAuthorizationsDirectoryResult.model_validate(data) except Exception as e: # pydantic.ValidationError + any coercion failure raise AdagentsValidationError( f"Agent-publishers directory response failed schema validation: {e}" ) from eQuery an AAO directory for publishers that authorize
agent_url.Calls
GET {directory_url}/v1/agents/{agent_url}/publishersper the AAO inverse-lookup contract (adcp#4823 / #4828) and returns the parsed response. The directory's answer is discovery, not authorization: callers should still verify each returnedpublisher_domainvia :func:fetch_adagents()before treating an edge as trusted.- Args
- -----=
agent_url- The agent whose publisher authorizations are being queried. Passed verbatim in the path; the directory echoes back a canonicalized form on the response.
directory_url- HTTPS base URL of the AAO directory
(e.g.
"https://aao.example.com"). The/v1/agents/...path is appended; pass the directory's root, not a request-specific path. since- Optional RFC 3339 timestamp from a prior
directory_indexed_at— passed through as?since=...to limit the result to edges that changed since that point. cursor- Optional opaque pagination cursor from a prior response's
next_cursor— passed through as?cursor=...to fetch the next page. include- Optional list of expansion keys per the AAO directory
API spec (adcp#4894). Each value is emitted as a separate
?include=<value>query parameter (repeated-key form, not comma-joined). Pass["properties"]against directories that support it to receive per-publisherproperty_ids[]on each row, enabling full set-diff against the publisher's own adagents.json. Directories that don't support a given expansion key simply omit the corresponding fields from the response; callers should treat absence as count-only mode. timeout- Request timeout in seconds.
client- Optional shared
httpx.AsyncClientfor connection pooling. Caller owns the client lifecycle.
Returns -----= :class:
AgentAuthorizationsDirectoryResult. On 404 from the directory the function returns a result withpublishers=[]anddirectory_indexed_at=None— directories MUST be allowed to answer "I do not index this agent" without callers needing to branch on exception type.- Raises
- -----=
AdagentsValidationError- If
directory_urlis malformed, the response status is non-200/non-404, the body is not valid JSON, or the body does not match the directory result schema. AdagentsTimeoutError- If the request times out.
Notes -----= -
directory_urlis gated through the same SSRF protection (HTTPS only, DNS pre-check, private/reserved address ban) as publisher-side fetches. - Response bodies are capped at 5 MiB. Bulk responses paginate vianext_cursor; pass that value ascursoron the next call. def filter_revoked_selectors(selectors: list[dict[str, Any]], revoked_domains: set[str]) ‑> list[dict[str, typing.Any]]-
Expand source code
def filter_revoked_selectors( selectors: list[dict[str, Any]], revoked_domains: set[str], ) -> list[dict[str, Any]]: """Strip selectors whose ``publisher_domain`` is revoked. Apply this AFTER the compact-form fan-out so each remaining selector addresses exactly one publisher, then drop any whose domain is in ``revoked_domains``. Revocation takes precedence over every other listing of that domain in the file (selectors, top-level properties, etc.) per adcp#4504. """ if not revoked_domains: return selectors return [s for s in selectors if s.get("publisher_domain") not in revoked_domains]Strip selectors whose
publisher_domainis revoked.Apply this AFTER the compact-form fan-out so each remaining selector addresses exactly one publisher, then drop any whose domain is in
revoked_domains. Revocation takes precedence over every other listing of that domain in the file (selectors, top-level properties, etc.) per adcp#4504. -
Expand source code
def find_authorized_agent_entries( adagents_data: dict[str, Any], agent_url: str ) -> list[dict[str, Any]]: """Return all entries listing an agent, independently of property binding. A non-empty result distinguishes a listed agent whose selectors resolve to no properties from an unlisted agent. Entries are returned in document order without copying or modifying them. Malformed sibling entries and URL values are skipped. Matching preserves HTTP/HTTPS equivalence and path semantics. Raises AdagentsValidationError if the document is not an object with an ``authorized_agents`` array. """ if not isinstance(adagents_data, dict): raise AdagentsValidationError("adagents_data must be a dictionary") authorized_agents = adagents_data.get("authorized_agents") if not isinstance(authorized_agents, list): raise AdagentsValidationError("adagents.json must have 'authorized_agents' array") normalized_agent_url = normalize_url(agent_url) matches: list[dict[str, Any]] = [] for agent in authorized_agents: if not isinstance(agent, dict): continue entry_url = agent.get("url") if not isinstance(entry_url, str) or not entry_url.strip(): continue try: normalized_entry_url = normalize_url(entry_url) except ValueError: continue if normalized_entry_url == normalized_agent_url: matches.append(agent) return matchesReturn all entries listing an agent, independently of property binding.
A non-empty result distinguishes a listed agent whose selectors resolve to no properties from an unlisted agent. Entries are returned in document order without copying or modifying them. Malformed sibling entries and URL values are skipped. Matching preserves HTTP/HTTPS equivalence and path semantics.
Raises AdagentsValidationError if the document is not an object with an
authorized_agentsarray. def format_is_supported(requested: FormatIdInput,
supported: FormatIdInput,
*,
default_agent_url: str = 'https://creative.adcontextprotocol.org') ‑> bool-
Expand source code
def format_is_supported( requested: FormatIdInput, supported: FormatIdInput, *, default_agent_url: str = CANONICAL_CREATIVE_AGENT_URL, ) -> bool: """Return true when ``requested`` is acceptable for ``supported``. This is intentionally stricter than :func:`formats_are_equivalent`. A broad supported format such as ``display_image`` accepts a specific request such as ``display_image`` 300x250, but a fixed supported product format requires the request to provide and match every parameter the supported side fixes — every parameter ``core/format-id.json`` declares, not a chosen few. ``pixel_ratio`` is the one parameter whose absence carries a value rather than meaning "unspecified": the schema describes omitting it as selecting the backward-compatible 1x variant. That reading applies to both sides of a dimensioned reference: a product fixed at 2x refuses a request that omits the field, a product that omits it (so is 1x) refuses a 2x request, and a product fixed at 1x accepts a request that omits it. """ req = _upgrade_legacy_format_id( requested, default_agent_url=default_agent_url, param="requested" ) sup = _upgrade_legacy_format_id( supported, default_agent_url=default_agent_url, param="supported" ) if not formats_are_equivalent(req, sup, default_agent_url=default_agent_url): return False for field in _PARAMETER_FIELDS: supported_value = _parameter_value(sup, field) if supported_value is None: continue if _parameter_value(req, field) != supported_value: return False return TrueReturn true when
requestedis acceptable forsupported.This is intentionally stricter than :func:
formats_are_equivalent(). A broad supported format such asdisplay_imageaccepts a specific request such asdisplay_image300x250, but a fixed supported product format requires the request to provide and match every parameter the supported side fixes — every parametercore/format-id.jsondeclares, not a chosen few.pixel_ratiois the one parameter whose absence carries a value rather than meaning "unspecified": the schema describes omitting it as selecting the backward-compatible 1x variant. That reading applies to both sides of a dimensioned reference: a product fixed at 2x refuses a request that omits the field, a product that omits it (so is 1x) refuses a 2x request, and a product fixed at 1x accepts a request that omits it. def formats_are_equivalent(a: FormatIdInput,
b: FormatIdInput,
*,
default_agent_url: str = 'https://creative.adcontextprotocol.org') ‑> bool-
Expand source code
def formats_are_equivalent( a: FormatIdInput, b: FormatIdInput, *, default_agent_url: str = CANONICAL_CREATIVE_AGENT_URL, ) -> bool: """Return true when two format IDs identify the same canonical family. Both inputs are first passed through :func:`upgrade_legacy_format_id`. Declared parameters must not conflict, but an omitted width, height or duration on either side is treated as unspecified rather than a mismatch: omitting them names the template, which covers every variant. An omitted ``pixel_ratio`` on a sized reference is not unspecified — it names the 1x variant — so 300x250 and 300x250 at 2x are different formats here too. Use :func:`format_is_supported` for product/capability gating, where a supported fixed size, duration or pixel density requires the request to state that value. """ left = _upgrade_legacy_format_id(a, default_agent_url=default_agent_url, param="a") right = _upgrade_legacy_format_id(b, default_agent_url=default_agent_url, param="b") if canonicalize_agent_url(left.agent_url) != canonicalize_agent_url(right.agent_url): return False if left.id != right.id: return False for field in _PARAMETER_FIELDS: left_value = _parameter_value(left, field) right_value = _parameter_value(right, field) if left_value is not None and right_value is not None and left_value != right_value: return False return TrueReturn true when two format IDs identify the same canonical family.
Both inputs are first passed through :func:
upgrade_legacy_format_id(). Declared parameters must not conflict, but an omitted width, height or duration on either side is treated as unspecified rather than a mismatch: omitting them names the template, which covers every variant. An omittedpixel_ratioon a sized reference is not unspecified — it names the 1x variant — so 300x250 and 300x250 at 2x are different formats here too. Use :func:format_is_supported()for product/capability gating, where a supported fixed size, duration or pixel density requires the request to state that value. def generate_webhook_challenge_value() ‑> str-
Expand source code
def generate_webhook_challenge_value() -> str: """Generate an opaque random value for a proof-of-control challenge.""" return f"wch_{secrets.token_urlsafe(32)}"Generate an opaque random value for a proof-of-control challenge.
def generate_webhook_idempotency_key() ‑> str-
Expand source code
def generate_webhook_idempotency_key() -> str: """Generate a cryptographically random idempotency_key for a webhook event. Returns a UUID v4 prefixed with ``whk_`` — matches the example format in ``webhooks.mdx`` and stays within the spec's length + charset bounds (``^[A-Za-z0-9_.:-]{16,255}$``). Publishers generate this once per delivery and reuse it for exact retries. A re-emission of the same logical event uses a new delivery key while retaining its stable ``notification_id``. """ return f"whk_{uuid.uuid4()}"Generate a cryptographically random idempotency_key for a webhook event.
Returns a UUID v4 prefixed with
whk_— matches the example format inwebhooks.mdxand stays within the spec's length + charset bounds (^[A-Za-z0-9_.:-]{16,255}$).Publishers generate this once per delivery and reuse it for exact retries. A re-emission of the same logical event uses a new delivery key while retaining its stable
notification_id. def get_adcp_signed_headers_for_webhook(headers: dict[str, Any],
secret: str,
timestamp: str | int | None,
payload: dict[str, Any] | AdCPBaseModel) ‑> dict[str, typing.Any]-
Expand source code
def get_adcp_signed_headers_for_webhook( headers: dict[str, Any], secret: str, timestamp: str | int | None, payload: dict[str, Any] | AdCPBaseModel, ) -> dict[str, Any]: """ Generate AdCP-compliant signed headers for webhook delivery. This function creates a cryptographic signature that proves the webhook came from an authorized agent and protects against replay attacks by including a timestamp in the signed message. The function adds two headers to the provided headers dict: - X-AdCP-Signature: HMAC-SHA256 signature in format "sha256=<hex_digest>" - X-AdCP-Timestamp: Unix timestamp in seconds The signing algorithm: 1. Constructs message as "{timestamp}.{json_payload}" 2. JSON-serializes payload with default separators (matches wire format from json= kwarg) 3. UTF-8 encodes the message 4. HMAC-SHA256 signs with the shared secret 5. Hex-encodes and prefixes with "sha256=" Args: headers: Existing headers dictionary to add signature headers to secret: Shared secret key for HMAC signing timestamp: Unix timestamp in seconds (str or int). If None, uses current time. payload: Webhook payload (dict or Pydantic model - will be JSON-serialized) Returns: The modified headers dictionary with signature headers added Examples: Sign and send an MCP webhook: >>> import time >>> from adcp.webhooks import create_mcp_webhook_payload >>> from adcp.webhooks import get_adcp_signed_headers_for_webhook >>> >>> payload = create_mcp_webhook_payload( ... task_id="task_123", ... operation_id="op_123", ... status="completed", ... task_type="create_media_buy", ... result={"media_buy_id": "mb_1"}, ... ) >>> headers = {"Content-Type": "application/json"} >>> signed_headers = get_adcp_signed_headers_for_webhook( ... headers, secret="my-webhook-secret", timestamp=str(int(time.time())), ... payload=payload, ... ) >>> >>> # Send webhook with signed headers >>> import httpx >>> response = await httpx.post( ... webhook_url, ... json=payload, ... headers=signed_headers ... ) Headers will contain: >>> print(signed_headers) { "Content-Type": "application/json", "X-AdCP-Signature": "sha256=a1b2c3...", "X-AdCP-Timestamp": "1773185740" } """ signature_headers, _body_bytes = _compute_legacy_signature( secret=secret, timestamp=timestamp, payload=payload ) headers.update(signature_headers) return headersGenerate AdCP-compliant signed headers for webhook delivery.
This function creates a cryptographic signature that proves the webhook came from an authorized agent and protects against replay attacks by including a timestamp in the signed message.
The function adds two headers to the provided headers dict: - X-AdCP-Signature: HMAC-SHA256 signature in format "sha256=
" - X-AdCP-Timestamp: Unix timestamp in seconds The signing algorithm: 1. Constructs message as "{timestamp}.{json_payload}" 2. JSON-serializes payload with default separators (matches wire format from json= kwarg) 3. UTF-8 encodes the message 4. HMAC-SHA256 signs with the shared secret 5. Hex-encodes and prefixes with "sha256="
- Args
- -----=
headers- Existing headers dictionary to add signature headers to
secret- Shared secret key for HMAC signing
timestamp- Unix timestamp in seconds (str or int). If None, uses current time.
payload- Webhook payload (dict or Pydantic model - will be JSON-serialized)
Returns -----= The modified headers dictionary with signature headers added
Examples -----= Sign and send an MCP webhook:
>>> import time >>> from adcp.webhooks import create_mcp_webhook_payload >>> from adcp.webhooks import get_adcp_signed_headers_for_webhook >>> >>> payload = create_mcp_webhook_payload( ... task_id="task_123", ... operation_id="op_123", ... status="completed", ... task_type="create_media_buy", ... result={"media_buy_id": "mb_1"}, ... ) >>> headers = {"Content-Type": "application/json"} >>> signed_headers = get_adcp_signed_headers_for_webhook( ... headers, secret="my-webhook-secret", timestamp=str(int(time.time())), ... payload=payload, ... ) >>> >>> # Send webhook with signed headers >>> import httpx >>> response = await httpx.post( ... webhook_url, ... json=payload, ... headers=signed_headers ... )Headers will contain:
>>> print(signed_headers) { "Content-Type": "application/json", "X-AdCP-Signature": "sha256=a1b2c3...", "X-AdCP-Timestamp": "1773185740" } def get_adcp_version() ‑> str-
Expand source code
def get_adcp_version() -> str: """Return the AdCP *spec* version (legacy name). .. deprecated:: 4.1 Kept for backwards compatibility with pre-4.1 callers. Prefer :func:`get_adcp_spec_version` (spec version) or :func:`get_adcp_sdk_version` / :attr:`adcp.__version__` (SDK package version) — the split disambiguates what the caller actually wants at the call site. """ import warnings warnings.warn( "get_adcp_version() is deprecated; use get_adcp_spec_version() " "for the AdCP spec version or get_adcp_sdk_version() / " "adcp.__version__ for the SDK package version.", DeprecationWarning, stacklevel=2, ) return get_adcp_spec_version()Return the AdCP spec version (legacy name).
Deprecated since version: 4.1
Kept for backwards compatibility with pre-4.1 callers. Prefer :func:
get_adcp_spec_version(spec version) or :func:get_adcp_sdk_version/ :attr:adcp.__version__(SDK package version) — the split disambiguates what the caller actually wants at the call site. def get_all_properties(adagents_data: dict[str, Any]) ‑> list[dict[str, typing.Any]]-
Expand source code
def get_all_properties(adagents_data: dict[str, Any]) -> list[dict[str, Any]]: """Extract all properties from adagents.json data. Handles all authorization types: inline_properties, property_ids, property_tags, and publisher_properties. For ``publisher_properties`` selectors whose target ``publisher_domain`` is NOT present inline in this file's top-level ``properties[]`` array, this function returns no properties for that selector. Federated fallback (fetching the child publisher's own adagents.json to resolve the selector remotely) is out of scope here and lives in :func:`fetch_agent_authorizations_from_directory` and :func:`detect_publisher_properties_divergence` from companion PR #752. Wire-only authorization checks that assume federated resolution will under-authorize against managed-network parent files that only inline a subset of their child domains. Args: adagents_data: Parsed adagents.json data Returns: List of all properties across all authorized agents, with agent_url added Raises: AdagentsValidationError: If adagents_data is malformed """ if not isinstance(adagents_data, dict): raise AdagentsValidationError("adagents_data must be a dictionary") authorized_agents = adagents_data.get("authorized_agents") if not isinstance(authorized_agents, list): raise AdagentsValidationError("adagents.json must have 'authorized_agents' array") top_level_properties = adagents_data.get("properties", []) if not isinstance(top_level_properties, list): top_level_properties = [] revoked = _get_revoked_publisher_domains(adagents_data) revoked_top_level = [ p for p in top_level_properties if not ( isinstance(p, dict) and isinstance(p.get("publisher_domain"), str) and p["publisher_domain"] in revoked ) ] # Build the domain index once per file — _resolve_agent_properties is # called per-agent, and at cafemedia scale (thousands of properties × # multiple agents) rebuilding it inside each call is O(agents × N). domain_index = _build_domain_index(revoked_top_level) properties = [] for agent in authorized_agents: if not isinstance(agent, dict): continue agent_url = agent.get("url", "") if not agent_url: continue # revoked_top_level pre-filters revoked domains from the per-domain # index, so inline resolution honors revocation transparently. agent_properties = _resolve_agent_properties(agent, revoked_top_level, domain_index) for prop in agent_properties: prop_with_agent = {**prop, "agent_url": agent_url} properties.append(prop_with_agent) return propertiesExtract all properties from adagents.json data.
Handles all authorization types: inline_properties, property_ids, property_tags, and publisher_properties.
For
publisher_propertiesselectors whose targetpublisher_domainis NOT present inline in this file's top-levelproperties[]array, this function returns no properties for that selector. Federated fallback (fetching the child publisher's own adagents.json to resolve the selector remotely) is out of scope here and lives in :func:fetch_agent_authorizations_from_directory()and :func:detect_publisher_properties_divergence()from companion PR #752. Wire-only authorization checks that assume federated resolution will under-authorize against managed-network parent files that only inline a subset of their child domains.- Args
- -----=
adagents_data- Parsed adagents.json data
Returns -----= List of all properties across all authorized agents, with agent_url added
- Raises
- -----=
AdagentsValidationError- If adagents_data is malformed
-
Expand source code
def get_all_tags(adagents_data: dict[str, Any]) -> set[str]: """Extract all unique tags from properties in adagents.json data. Args: adagents_data: Parsed adagents.json data Returns: Set of all unique tags across all properties Raises: AdagentsValidationError: If adagents_data is malformed """ properties = get_all_properties(adagents_data) tags = set() for prop in properties: prop_tags = prop.get("tags", []) if isinstance(prop_tags, list): for tag in prop_tags: if isinstance(tag, str): tags.add(tag) return tagsExtract all unique tags from properties in adagents.json data.
- Args
- -----=
adagents_data- Parsed adagents.json data
Returns -----= Set of all unique tags across all properties
- Raises
- -----=
AdagentsValidationError- If adagents_data is malformed
def get_asset_count(format: FormatAssetsInput | Mapping[str, Any]) ‑> int-
Expand source code
def get_asset_count(format: FormatAssetsInput | Mapping[str, Any]) -> int: """Get the count of assets in a format (for display purposes). Args: format: The Format object Returns: Number of assets, or 0 if none defined """ return len(get_format_assets(format))Get the count of assets in a format (for display purposes).
- Args
- -----=
format- The Format object
Returns -----= Number of assets, or 0 if none defined
def get_format_assets(format: FormatAssetsInput | Mapping[str, Any]) ‑> list[typing.Any]-
Expand source code
def get_format_assets(format: FormatAssetsInput | Mapping[str, Any]) -> list[FormatAsset]: """Get assets from a Format. Returns the list of assets from the format's `assets` field. Returns empty list if no assets are defined (flexible format with no assets). Args: format: Any canonical declaration or raw catalog object exposing ``assets`` Returns: List of assets Example: ```python for declaration in product.format_options: assets = get_format_assets(declaration) print(f"{declaration.format_kind} has {len(assets)} assets") ``` """ if isinstance(format, Mapping): assets = format.get("assets") if assets is None and isinstance(format.get("params"), Mapping): assets = format["params"].get("slots") else: assets = getattr(format, "assets", None) if assets is None: params = getattr(format, "params", None) assets = params.get("slots") if isinstance(params, Mapping) else None if assets: return list(assets) return []Get assets from a Format.
Returns the list of assets from the format's
assetsfield. Returns empty list if no assets are defined (flexible format with no assets).- Args
- -----=
format- Any canonical declaration or raw catalog object exposing
assets
Returns -----= List of assets
Example -----=
for declaration in product.format_options: assets = get_format_assets(declaration) print(f"{declaration.format_kind} has {len(assets)} assets") def get_individual_assets(format: FormatAssetsInput | Mapping[str, Any]) ‑> list[typing.Any]-
Expand source code
def get_individual_assets(format: FormatAssetsInput | Mapping[str, Any]) -> list[FormatAsset]: """Get individual assets (not repeatable groups) from a Format. Args: format: The Format object Returns: List of individual assets (item_type='individual') """ return [asset for asset in get_format_assets(format) if _get_item_type(asset) == "individual"]Get individual assets (not repeatable groups) from a Format.
- Args
- -----=
format- The Format object
Returns -----= List of individual assets (item_type='individual')
def get_optional_assets(format: FormatAssetsInput | Mapping[str, Any]) ‑> list[typing.Any]-
Expand source code
def get_optional_assets(format: FormatAssetsInput | Mapping[str, Any]) -> list[FormatAsset]: """Get only optional assets from a Format. Note: When using deprecated `assets_required`, this will always return empty since assets_required only contained required assets. Args: format: The Format object Returns: List of optional assets only Example: ```python optional_assets = get_optional_assets(format) print(f"Can optionally provide {len(optional_assets)} additional assets") ``` """ return [asset for asset in get_format_assets(format) if not _is_required(asset)]Get only optional assets from a Format.
Note: When using deprecated
assets_required, this will always return empty since assets_required only contained required assets.- Args
- -----=
format- The Format object
Returns -----= List of optional assets only
Example -----=
optional_assets = get_optional_assets(format) print(f"Can optionally provide {len(optional_assets)} additional assets") def get_properties_by_agent(adagents_data: dict[str, Any], agent_url: str) ‑> list[dict[str, typing.Any]]-
Expand source code
def get_properties_by_agent(adagents_data: dict[str, Any], agent_url: str) -> list[dict[str, Any]]: """Get all properties authorized for a specific agent. Handles all authorization types per the AdCP specification: - inline_properties: Properties defined directly in the agent's properties array - property_ids: Filter top-level properties by property_id - property_tags: Filter top-level properties by tags - publisher_properties: Inline-resolved properties from cross-publisher selectors (resolved from the parent file's top-level properties[] array per adcp#4827) For ``publisher_properties`` selectors whose target ``publisher_domain`` is NOT present inline in this file's top-level ``properties[]`` array, this function returns no properties for that selector. Federated fallback (fetching the child publisher's own adagents.json to resolve the selector remotely) is out of scope here and lives in :func:`fetch_agent_authorizations_from_directory` and :func:`detect_publisher_properties_divergence` from companion PR #752. Wire-only authorization checks that assume federated resolution will under-authorize against managed-network parent files that only inline a subset of their child domains. Args: adagents_data: Parsed adagents.json data agent_url: URL of the agent to filter by Returns: List of properties for the specified agent (empty if agent not found) Raises: AdagentsValidationError: If adagents_data is malformed """ return _resolve_properties_for_agent(adagents_data, agent_url, permissive_bare_top_level=False)Get all properties authorized for a specific agent.
Handles all authorization types per the AdCP specification: - inline_properties: Properties defined directly in the agent's properties array - property_ids: Filter top-level properties by property_id - property_tags: Filter top-level properties by tags - publisher_properties: Inline-resolved properties from cross-publisher selectors (resolved from the parent file's top-level properties[] array per adcp#4827)
For
publisher_propertiesselectors whose targetpublisher_domainis NOT present inline in this file's top-levelproperties[]array, this function returns no properties for that selector. Federated fallback (fetching the child publisher's own adagents.json to resolve the selector remotely) is out of scope here and lives in :func:fetch_agent_authorizations_from_directory()and :func:detect_publisher_properties_divergence()from companion PR #752. Wire-only authorization checks that assume federated resolution will under-authorize against managed-network parent files that only inline a subset of their child domains.- Args
- -----=
adagents_data- Parsed adagents.json data
agent_url- URL of the agent to filter by
Returns -----= List of properties for the specified agent (empty if agent not found)
- Raises
- -----=
AdagentsValidationError- If adagents_data is malformed
def get_repeatable_groups(format: FormatAssetsInput | Mapping[str, Any]) ‑> list[typing.Any]-
Expand source code
def get_repeatable_groups(format: FormatAssetsInput | Mapping[str, Any]) -> list[FormatAsset]: """Get repeatable asset groups from a Format. Args: format: The Format object Returns: List of repeatable asset groups (item_type='repeatable_group') """ return [ asset for asset in get_format_assets(format) if _get_item_type(asset) == "repeatable_group" ]Get repeatable asset groups from a Format.
- Args
- -----=
format- The Format object
Returns -----= List of repeatable asset groups (item_type='repeatable_group')
def get_required_assets(format: FormatAssetsInput | Mapping[str, Any]) ‑> list[typing.Any]-
Expand source code
def get_required_assets(format: FormatAssetsInput | Mapping[str, Any]) -> list[FormatAsset]: """Get only required assets from a Format. Args: format: The Format object Returns: List of required assets only Example: ```python required_assets = get_required_assets(format) print(f"Must provide {len(required_assets)} assets") ``` """ return [asset for asset in get_format_assets(format) if _is_required(asset)]Get only required assets from a Format.
- Args
- -----=
format- The Format object
Returns -----= List of required assets only
Example -----=
required_assets = get_required_assets(format) print(f"Must provide {len(required_assets)} assets") def get_tracer() ‑> typing.Any | None-
Expand source code
def get_tracer() -> Any | None: """Return the AdCP tracer, or ``None`` without OpenTelemetry installed.""" bindings = _load_bindings() if bindings is None: return None return bindings.trace.get_tracer(_INSTRUMENTATION_NAME)Return the AdCP tracer, or
Nonewithout OpenTelemetry installed. def has_assets(format: FormatAssetsInput | Mapping[str, Any]) ‑> bool-
Expand source code
def has_assets(format: FormatAssetsInput | Mapping[str, Any]) -> bool: """Check if a format has any assets defined. Args: format: The Format object Returns: True if format has assets, False otherwise """ return get_asset_count(format) > 0Check if a format has any assets defined.
- Args
- -----=
format- The Format object
Returns -----= True if format has assets, False otherwise
def identifiers_match(property_identifiers: list[dict[str, str]],
agent_identifiers: list[dict[str, str]]) ‑> bool-
Expand source code
def identifiers_match( property_identifiers: list[dict[str, str]], agent_identifiers: list[dict[str, str]], ) -> bool: """Check if any property identifier matches agent's authorized identifiers. Args: property_identifiers: Identifiers from property (e.g., [{"type": "domain", "value": "cnn.com"}]) agent_identifiers: Identifiers from adagents.json Returns: True if any identifier matches Notes: - Domain identifiers use AdCP domain matching rules - Other identifiers (bundle_id, roku_store_id, etc.) require exact match """ for prop_id in property_identifiers: prop_type = prop_id.get("type", "") prop_value = prop_id.get("value", "") for agent_id in agent_identifiers: agent_type = agent_id.get("type", "") agent_value = agent_id.get("value", "") # Type must match if prop_type != agent_type: continue # Domain identifiers use special matching rules if prop_type == "domain": if domain_matches(prop_value, agent_value): return True else: # Other identifier types require exact match if prop_value == agent_value: return True return FalseCheck if any property identifier matches agent's authorized identifiers.
- Args
- -----=
property_identifiers- Identifiers from property (e.g., [{"type": "domain", "value": "cnn.com"}])
agent_identifiers- Identifiers from adagents.json
Returns -----= True if any identifier matches
Notes -----= - Domain identifiers use AdCP domain matching rules - Other identifiers (bundle_id, roku_store_id, etc.) require exact match
def inject_trace_headers(carrier: MutableMapping[str, str] | None = None) ‑> dict[str, str]-
Expand source code
def inject_trace_headers( carrier: MutableMapping[str, str] | None = None, ) -> dict[str, str]: """Inject the active W3C trace context into a string header mapping. The returned dictionary contains the full resulting carrier. Existing ``traceparent`` and ``tracestate`` values are replaced only when an active, valid OpenTelemetry span produces new values. W3C baggage is never propagated by this helper. """ result = {name: value for name, value in (carrier or {}).items() if name.lower() != "baggage"} bindings = _load_bindings() if bindings is None: return result injected: dict[str, str] = {} bindings.trace_context_propagator().inject(injected) if not injected: return result for existing_name in tuple(result): if existing_name.lower() in {"traceparent", "tracestate"}: result.pop(existing_name) for name in ("traceparent", "tracestate"): value = injected.get(name) if value is not None: result[name] = value return resultInject the active W3C trace context into a string header mapping.
The returned dictionary contains the full resulting carrier. Existing
traceparentandtracestatevalues are replaced only when an active, valid OpenTelemetry span produces new values. W3C baggage is never propagated by this helper. def is_tracing_available() ‑> bool-
Expand source code
def is_tracing_available() -> bool: """Return whether the optional OpenTelemetry API is installed. Availability does not imply that spans are exported. Applications remain responsible for installing/configuring an OpenTelemetry SDK and exporter. """ return _load_bindings() is not NoneReturn whether the optional OpenTelemetry API is installed.
Availability does not imply that spans are exported. Applications remain responsible for installing/configuring an OpenTelemetry SDK and exporter.
def materialize_change_terms(product_actions: Iterable[Any],
selections: Iterable[ChangeTermSelection | Mapping[str, Any]]) ‑> tuple[MediaBuyChangeTerm, ...]-
Expand source code
def materialize_change_terms( product_actions: Iterable[Any], selections: Iterable[ChangeTermSelection | Mapping[str, Any]], ) -> tuple[MediaBuyChangeTerm, ...]: """Materialize explicitly selected product templates as binding terms. Product declarations are never copied wholesale. Every returned term requires a :class:`ChangeTermSelection`, and all portable bounds, SLA, and status scope are copied from (or narrowed relative to) that template. """ product_index = _unique_action_index(product_actions, field="product_actions") parsed = [ ( value if isinstance(value, ChangeTermSelection) else ChangeTermSelection.model_validate(value) ) for value in selections ] if len({selection.action for selection in parsed}) != len(parsed): raise MediaBuyActionError("duplicate_action", "selections") if len({selection.term_id for selection in parsed}) != len(parsed): raise MediaBuyActionError("duplicate_term_id", "selections") terms: list[MediaBuyChangeTerm] = [] for index, selection in enumerate(parsed): product_action = product_index.get(selection.action) if product_action is None: raise MediaBuyActionError("action_not_advertised", f"selections[{index}].action") if selection.action not in _CANONICAL_ACTIONS: raise MediaBuyActionError("unknown_action", f"selections[{index}].action") modes = _string_sequence(product_action.get("modes")) mode = selection.service_mode if mode is None: if len(modes) != 1: raise MediaBuyActionError( "service_mode_required", f"selections[{index}].service_mode" ) mode = modes[0] if mode not in modes: raise MediaBuyActionError( "service_mode_not_advertised", f"selections[{index}].service_mode" ) product_statuses = _string_sequence(product_action.get("allowed_statuses")) selected_statuses = selection.allowed_statuses if ( selected_statuses is not None and product_statuses and not set(selected_statuses) <= set(product_statuses) ): raise MediaBuyActionError( "status_scope_expanded", f"selections[{index}].allowed_statuses" ) statuses = selected_statuses or (tuple(product_statuses) if product_statuses else None) constraint = _as_mapping(product_action.get("constraints")) or None if constraint is not None: kind = _string_value(constraint.get("kind")) if selection.action not in _CONSTRAINT_ACTIONS.get(kind or "", frozenset()): raise MediaBuyActionError( "constraint_action_mismatch", f"product_actions[{index}].constraints", ) term_payload: dict[str, Any] = { "term_id": selection.term_id, "action": selection.action, "service_mode": mode, } if statuses is not None: term_payload["allowed_statuses"] = list(statuses) sla = _as_mapping(product_action.get("sla")) if sla: term_payload["processing_sla"] = sla if constraint is not None: term_payload["constraints"] = constraint if selection.conditions is not None: term_payload["conditions"] = list(selection.conditions) terms_ref = selection.terms_ref or _string_value(product_action.get("terms_ref")) if terms_ref is not None: term_payload["terms_ref"] = terms_ref if selection.description is not None: term_payload["description"] = selection.description terms.append(MediaBuyChangeTerm.model_validate(term_payload)) return tuple(terms)Materialize explicitly selected product templates as binding terms.
Product declarations are never copied wholesale. Every returned term requires a :class:
ChangeTermSelection, and all portable bounds, SLA, and status scope are copied from (or narrowed relative to) that template. def normalize_assets_required(assets_required: list[Any]) ‑> list[typing.Any]-
Expand source code
def normalize_assets_required(assets_required: list[Any]) -> list[FormatAsset]: """Convert deprecated assets_required to new assets format. .. deprecated:: 3.2.0 The ``assets_required`` field was removed in ADCP 3.0.0-beta.2. This function will be removed in a future version. All assets in assets_required are required by definition (that's why they were in that array). The new `assets` field has an explicit `required: boolean` to allow both required AND optional assets. Args: assets_required: The deprecated assets_required array Returns: Normalized assets as Pydantic models with explicit required=True """ warnings.warn( "normalize_assets_required() is deprecated. " "The assets_required field was removed in ADCP 3.0.0-beta.2. " "This function will be removed in a future version.", DeprecationWarning, stacklevel=2, ) normalized: list[FormatAsset] = [] for asset in assets_required: # Get asset data as dict if isinstance(asset, dict): asset_dict = asset else: asset_dict = asset.model_dump() if hasattr(asset, "model_dump") else dict(asset) # Map old fields to new schema format mapped = {**asset_dict, "required": True} # Ensure asset_id is present (map from asset_group_id if needed) if "asset_group_id" in mapped and "asset_id" not in mapped: mapped["asset_id"] = mapped.pop("asset_group_id") # Remove fields that don't exist in the new schema for old_field in ("min_count", "max_count", "assets"): mapped.pop(old_field, None) # Use AssetsModel (individual asset type) normalized.append(AssetsModel(**mapped)) return normalizedConvert deprecated assets_required to new assets format.
Deprecated since version: 3.2.0
The
assets_requiredfield was removed in ADCP 3.0.0-beta.2. This function will be removed in a future version.All assets in assets_required are required by definition (that's why they were in that array). The new
assetsfield has an explicitrequired: booleanto allow both required AND optional assets.- Args
- -----=
assets_required- The deprecated assets_required array
Returns -----= Normalized assets as Pydantic models with explicit required=True
def normalize_domain(value: str, *, allow_wildcard: bool = True) ‑> NormalizedIdentifier-
Expand source code
def normalize_domain(value: str, *, allow_wildcard: bool = True) -> NormalizedIdentifier: """Canonicalize a hostname (IDNA, lowercase, no trailing dot). URLs, ports, IP addresses and embedded wildcards are rejected. A leading ``*.`` is accepted only when ``allow_wildcard`` is true. No scheme or path is silently discarded. This validates syntax, not registration/ownership. """ if not isinstance(value, str): raise IdentifierValidationError("domain", "expected_string") canonical = value.strip().removesuffix(".").lower() wildcard = canonical.startswith("*.") host = canonical[2:] if wildcard else canonical if wildcard and not allow_wildcard: raise IdentifierValidationError("domain", "wildcard_not_allowed") if any(c in host for c in "/:@?#*\\"): raise IdentifierValidationError("domain", "expected_hostname") try: host = idna.encode(host, uts46=True, transitional=False).decode("ascii") except idna.IDNAError: raise IdentifierValidationError("domain", "invalid_idna") from None labels = host.split(".") if ( len(host) > 253 or len(labels) < 2 or not all(re.fullmatch(r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?", label) for label in labels) ): raise IdentifierValidationError("domain", "invalid_hostname") try: ipaddress.ip_address(host) except ValueError: pass else: raise IdentifierValidationError("domain", "ip_address_not_allowed") return NormalizedIdentifier("domain", ("*." if wildcard else "") + host, value)Canonicalize a hostname (IDNA, lowercase, no trailing dot).
URLs, ports, IP addresses and embedded wildcards are rejected. A leading
*.is accepted only whenallow_wildcardis true. No scheme or path is silently discarded. This validates syntax, not registration/ownership. def normalize_identifier(identifier_type: str, value: str) ‑> NormalizedIdentifier-
Expand source code
def normalize_identifier(identifier_type: str, value: str) -> NormalizedIdentifier: """Validate a declared identifier and report any canonical rewrite. Bundle/package and opaque IDs preserve case. Numeric store IDs contain digits only; Fire TV ASINs canonicalize to uppercase. Unknown types fail explicitly rather than being mistaken for domains. """ try: kind = PropertyIdentifierTypes(identifier_type).value except ValueError: raise IdentifierValidationError(identifier_type, "unknown_type") from None if not isinstance(value, str): raise IdentifierValidationError(kind, "expected_string") if kind in {"domain", "subdomain"}: try: result = normalize_domain(value, allow_wildcard=kind == "domain") except IdentifierValidationError as exc: raise IdentifierValidationError(kind, exc.reason) from None return NormalizedIdentifier(kind, result.value, value) canonical = value.strip() if not canonical or any(c.isspace() or ord(c) < 32 or ord(c) == 127 for c in canonical): raise IdentifierValidationError(kind, "empty_or_whitespace") if kind in {"ios_bundle", "apple_tv_bundle", "bundle_id"}: if not re.fullmatch(r"[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+", canonical): raise IdentifierValidationError(kind, "invalid_bundle") elif kind in {"android_package", "google_play_id"}: if not re.fullmatch(r"[A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z][A-Za-z0-9_]*)+", canonical): raise IdentifierValidationError(kind, "invalid_package") elif kind in {"apple_app_store_id", "roku_store_id", "apple_podcast_id"}: if not re.fullmatch(r"[0-9]+", canonical): raise IdentifierValidationError(kind, "expected_numeric_store_id") elif kind == "fire_tv_asin": canonical = canonical.upper() if not re.fullmatch(r"[A-Z0-9]{10}", canonical): raise IdentifierValidationError(kind, "invalid_asin") elif kind == "rss_url": try: parsed = urlsplit(canonical) if ( parsed.scheme not in {"http", "https"} or not parsed.hostname or parsed.username is not None ): raise ValueError # Accessing .port validates both numeric syntax and its range. parsed.port normalize_domain(parsed.hostname, allow_wildcard=False) except ValueError: raise IdentifierValidationError(kind, "expected_http_url") from None return NormalizedIdentifier(kind, canonical, value)Validate a declared identifier and report any canonical rewrite.
Bundle/package and opaque IDs preserve case. Numeric store IDs contain digits only; Fire TV ASINs canonicalize to uppercase. Unknown types fail explicitly rather than being mistaken for domains.
def parse_managerdomains(ads_txt_content: str) ‑> list[str]-
Expand source code
def parse_managerdomains(ads_txt_content: str) -> list[str]: """Extract MANAGERDOMAIN= directives from ads.txt content. Per IAB ads.txt: only directive-form lines (``MANAGERDOMAIN=value``) count — pure comment lines beginning with ``#`` are rejected. Order in source is preserved so callers can apply last-wins. """ managers: list[str] = [] for line in ads_txt_content.splitlines(): stripped = line.lstrip() if stripped.startswith("#"): continue match = _MANAGERDOMAIN_RE.match(line) if match: managers.append(match.group(1).lower()) return managersExtract MANAGERDOMAIN= directives from ads.txt content.
Per IAB ads.txt: only directive-form lines (
MANAGERDOMAIN=value) count — pure comment lines beginning with#are rejected. Order in source is preserved so callers can apply last-wins. def project_available_actions(change_terms: Iterable[Any] | None,
status: str,
*,
product_actions: Iterable[Any] | None = None,
authorized_actions: Iterable[str] | None = None,
delegated_actions: Iterable[str] | None = None,
policy_actions: Iterable[str] | None = None,
resolved_conditions: Mapping[str, bool] | None = None,
protocol_version: str = '3.2') ‑> MediaBuyActionProjection-
Expand source code
def project_available_actions( change_terms: Iterable[Any] | None, status: str, *, product_actions: Iterable[Any] | None = None, authorized_actions: Iterable[str] | None = None, delegated_actions: Iterable[str] | None = None, policy_actions: Iterable[str] | None = None, resolved_conditions: Mapping[str, bool] | None = None, protocol_version: str = "3.2", ) -> MediaBuyActionProjection: """Derive a fail-closed seller ``available_actions`` projection. ``None`` for an optional narrowing set means that gate has already been satisfied or is not applicable. An explicit empty set denies every action. Conditions must be explicitly resolved ``True``; absent, false, or unknown conditions omit the action. """ diagnostics: list[ActionDiagnostic] = [] if change_terms is None: return MediaBuyActionProjection( diagnostics=(ActionDiagnostic(code=ActionDiagnosticCode.legacy_terms_unknown),) ) if status not in _NON_TERMINAL_STATUSES: return MediaBuyActionProjection() terms: list[Mapping[str, Any]] = [] for index, raw_term in enumerate(change_terms): try: parsed_term = MediaBuyChangeTerm.model_validate(raw_term) except ValidationError: diagnostics.append( ActionDiagnostic( code=ActionDiagnosticCode.invalid_projection, field=f"change_terms[{index}]", ) ) continue terms.append(parsed_term.model_dump(mode="python", by_alias=True, exclude_unset=True)) seen_actions: set[str] = set() seen_ids: set[str] = set() product_index = ( _unique_action_index(product_actions, field="product_actions") if product_actions is not None else None ) gates = [ set(values) if values is not None else None for values in (authorized_actions, delegated_actions, policy_actions) ] supports_link = _supports_change_term_id(protocol_version) supports_task = _supports_action_task(protocol_version) actions: list[ProjectedMediaBuyAction] = [] for index, term in enumerate(terms): action = _string_value(term.get("action")) term_id = _string_value(term.get("term_id")) if action is None or term_id is None or _TERM_ID_RE.fullmatch(term_id) is None: diagnostics.append( ActionDiagnostic( code=ActionDiagnosticCode.invalid_projection, field=f"change_terms[{index}]", ) ) continue if action in seen_actions: diagnostics.append(_diagnostic(ActionDiagnosticCode.duplicate_action, detail=action)) continue if term_id in seen_ids: diagnostics.append(_diagnostic(ActionDiagnosticCode.duplicate_term_id, detail=term_id)) continue seen_actions.add(action) seen_ids.add(term_id) task = route_media_buy_action(action) if task is None: diagnostics.append(_diagnostic(ActionDiagnosticCode.unknown_action, detail=action)) continue allowed_statuses = _string_sequence(term.get("allowed_statuses")) if allowed_statuses and status not in allowed_statuses: continue if any(gate is not None and action not in gate for gate in gates): continue product_action = product_index.get(action) if product_index is not None else None if product_index is not None and product_action is None: continue mode = _string_value(term.get("service_mode")) if mode is None: diagnostics.append( ActionDiagnostic( code=ActionDiagnosticCode.invalid_projection, field=f"change_terms[{index}].service_mode", ) ) continue if product_action is not None: if mode not in _string_sequence(product_action.get("modes")): continue product_statuses = _string_sequence(product_action.get("allowed_statuses")) if product_statuses and status not in product_statuses: continue conditions = _string_sequence(term.get("conditions")) if conditions and ( resolved_conditions is None or any(resolved_conditions.get(condition) is not True for condition in conditions) ): diagnostics.append( _diagnostic(ActionDiagnosticCode.condition_unresolved, detail=action) ) continue constraint = _as_mapping(term.get("constraints")) if constraint: kind = _string_value(constraint.get("kind")) if action not in _CONSTRAINT_ACTIONS.get(kind or "", frozenset()): diagnostics.append( _diagnostic(ActionDiagnosticCode.invalid_projection, detail=action) ) continue wire_mode = "requires_approval" if not supports_link and mode == "seller_managed" else mode action_payload: dict[str, Any] = { "action": action, "mode": wire_mode, "sla": _as_mapping(term.get("processing_sla")) or None, } if supports_task: action_payload["task"] = task if supports_link: action_payload["change_term_id"] = term_id else: # This is an explicit adapter-generated alias. Arbitrary inbound # 3.1 terms_ref values are never interpreted this way. action_payload["terms_ref"] = term_id actions.append(ProjectedMediaBuyAction.model_validate(action_payload)) return MediaBuyActionProjection( actions=tuple(actions), diagnostics=tuple(_dedupe_diagnostics(diagnostics)) )Derive a fail-closed seller
available_actionsprojection.Nonefor an optional narrowing set means that gate has already been satisfied or is not applicable. An explicit empty set denies every action. Conditions must be explicitly resolvedTrue; absent, false, or unknown conditions omit the action. def properties_for_publisher_domain(properties: list[dict[str, Any]],
publisher_domain: str,
*,
include_unattributed: bool = True) ‑> list[dict[str, typing.Any]]-
Expand source code
def properties_for_publisher_domain( properties: list[dict[str, Any]], publisher_domain: str, *, include_unattributed: bool = True, ) -> list[dict[str, Any]]: """Attribute already-resolved properties to a publisher without network I/O. An explicit ``publisher_domain`` takes precedence and must name the same publisher (case, trailing dots and a leading ``www.`` are normalized). Otherwise, a domain or subdomain identifier must name the publisher or any subdomain, using :func:`domain_matches`. Properties without either kind of domain, such as bundle-only apps, are kept unless ``include_unattributed=False``. Invalid domain claims are excluded rather than treated as unattributed. Returns the original property objects in input order without mutation. This is attribution of trusted claims, not proof of authorization; use :func:`verify_cross_domain_properties` to verify cross-domain claims. Raises AdagentsValidationError if ``publisher_domain`` is not a hostname. """ domain = _publisher_attribution_domain(publisher_domain) selected: list[dict[str, Any]] = [] for prop in properties: if "publisher_domain" in prop: try: if _publisher_attribution_domain(prop["publisher_domain"]) == domain: selected.append(prop) except AdagentsValidationError: # An invalid explicit publisher claim cannot fall back to identifiers. logger.debug("Skipping property with invalid publisher_domain") continue domain_ids = _property_domain_identifiers(prop, include_subdomains=True) if any(_domain_identifier_is_under_publisher(i, domain) for i in domain_ids) or ( not domain_ids and include_unattributed ): selected.append(prop) return selectedAttribute already-resolved properties to a publisher without network I/O.
An explicit
publisher_domaintakes precedence and must name the same publisher (case, trailing dots and a leadingwww.are normalized). Otherwise, a domain or subdomain identifier must name the publisher or any subdomain, using :func:domain_matches(). Properties without either kind of domain, such as bundle-only apps, are kept unlessinclude_unattributed=False. Invalid domain claims are excluded rather than treated as unattributed.Returns the original property objects in input order without mutation. This is attribution of trusted claims, not proof of authorization; use :func:
verify_cross_domain_properties()to verify cross-domain claims.Raises AdagentsValidationError if
publisher_domainis not a hostname. def reassess_media_buy_action(action: str,
*,
currently_available_actions: Iterable[Any],
media_buy: Any,
product: Any | None = None,
proposal: Any | None = None,
intent: ActionIntent | Mapping[str, Any] | None = None,
now: datetime | None = None) ‑> MediaBuyActionAssessment-
Expand source code
def reassess_media_buy_action( action: str, *, currently_available_actions: Iterable[Any], media_buy: Any, product: Any | None = None, proposal: Any | None = None, intent: ActionIntent | Mapping[str, Any] | None = None, now: datetime | None = None, ) -> MediaBuyActionAssessment: """Reassess against an authoritative action-set echo after a race. ``ACTION_NOT_ALLOWED`` may carry ``currently_available_actions`` resolved at rejection time. This helper replaces only the stale action projection; proposal rights and all other MediaBuy state remain unchanged. Callers should still refresh the full MediaBuy before retrying with a new revision. """ refreshed = dict(_as_mapping(media_buy)) refreshed["available_actions"] = [ dict(_as_mapping(value)) for value in currently_available_actions ] return assess_media_buy_action( action, product=product, proposal=proposal, media_buy=refreshed, intent=intent, now=now, )Reassess against an authoritative action-set echo after a race.
ACTION_NOT_ALLOWEDmay carrycurrently_available_actionsresolved at rejection time. This helper replaces only the stale action projection; proposal rights and all other MediaBuy state remain unchanged. Callers should still refresh the full MediaBuy before retrying with a new revision. def resolve_properties_for_agent(adagents_data: dict[str, Any],
agent_url: str,
*,
mode: PropertyResolutionMode = 'strict',
publisher_domain: str | None = None) ‑> list[dict[str, typing.Any]]-
Expand source code
def resolve_properties_for_agent( adagents_data: dict[str, Any], agent_url: str, *, mode: PropertyResolutionMode = "strict", publisher_domain: str | None = None, ) -> list[dict[str, Any]]: """Resolve properties for an agent with an explicit strict/permissive mode. ``mode="strict"`` is identical to :func:`get_properties_by_agent` and only honors schema-conformant authorization selectors plus the historical inline ``properties`` legacy shape. ``mode="permissive"`` keeps every strict selector behavior unchanged, but treats one exact matching bare ``authorized_agents`` entry (``{"url": ..., "authorized_for": ...}``) as authorizing the file's top-level ``properties[]``. This is for operational binding of non-conformant publisher files that list an agent URL without an ``authorization_type`` or selector. If the agent is not listed, has any explicit or unknown selector field, or has multiple same-URL entries, the resolver still returns the strict result. ``publisher_domain`` gates only bare-entry fallback: a property must have a domain identifier naming that publisher or a subdomain. Self-declared ``publisher_domain`` values cannot satisfy the gate; apps and venues with no matching domain identifier are excluded. Typed selectors are unchanged. Args: adagents_data: Parsed adagents.json data agent_url: URL of the agent to filter by mode: ``"strict"`` for spec-conformant resolution, ``"permissive"`` to opt into bare-entry top-level property fallback. publisher_domain: Optional hostname attested by the caller's fetch origin, used to restrict permissive bare-entry fallback. Returns: List of properties for the specified agent. Raises: AdagentsValidationError: If adagents_data is malformed ValueError: If mode is not ``"strict"`` or ``"permissive"`` """ if mode not in {"strict", "permissive"}: raise ValueError("mode must be 'strict' or 'permissive'") domain = ( _publisher_attribution_domain(publisher_domain) if publisher_domain is not None else None ) return _resolve_properties_for_agent( adagents_data, agent_url, permissive_bare_top_level=mode == "permissive", publisher_domain=domain, )Resolve properties for an agent with an explicit strict/permissive mode.
mode="strict"is identical to :func:get_properties_by_agent()and only honors schema-conformant authorization selectors plus the historical inlinepropertieslegacy shape.mode="permissive"keeps every strict selector behavior unchanged, but treats one exact matching bareauthorized_agentsentry ({"url": ..., "authorized_for": ...}) as authorizing the file's top-levelproperties[]. This is for operational binding of non-conformant publisher files that list an agent URL without anauthorization_typeor selector. If the agent is not listed, has any explicit or unknown selector field, or has multiple same-URL entries, the resolver still returns the strict result.publisher_domaingates only bare-entry fallback: a property must have a domain identifier naming that publisher or a subdomain. Self-declaredpublisher_domainvalues cannot satisfy the gate; apps and venues with no matching domain identifier are excluded. Typed selectors are unchanged.- Args
- -----=
adagents_data- Parsed adagents.json data
agent_url- URL of the agent to filter by
mode"strict"for spec-conformant resolution,"permissive"to opt into bare-entry top-level property fallback.publisher_domain- Optional hostname attested by the caller's fetch origin, used to restrict permissive bare-entry fallback.
Returns -----= List of properties for the specified agent.
- Raises
- -----=
AdagentsValidationError- If adagents_data is malformed
ValueError- If mode is not
"strict"or"permissive"
def route_media_buy_action(action: str, *, version: str | None = None) ‑> ActionTask | None-
Expand source code
def route_media_buy_action(action: str, *, version: str | None = None) -> ActionTask | None: """Return the canonical compact task for an in-envelope action. Flight and package-addition changes require proposal refinement; creative lifecycle changes use ``sync_creatives``; the remaining accepted controls use ``control_media_buy``. A structured-only action the tables above have not been taught still routes when the bundle's merged ``enumMetadata`` says it mutates ``update_media_buy`` fields. The spec adds these additively and tells SDKs to dispatch on that block, so consulting it keeps a newer bundle working instead of failing closed on a name the tables predate -- which is the bug ``update_media_buy_frequency_cap`` exposed. Anything the bundle does not describe either still fails closed with ``None`` so callers do not guess a route. """ if action in _CONTROL_ACTIONS: return ActionTask.control_media_buy if action in _REFINEMENT_ACTIONS: return ActionTask.refine_proposals if action in _CREATIVE_ACTIONS: return ActionTask.sync_creatives if action_update_fields(version).get(action): return ActionTask.control_media_buy return NoneReturn the canonical compact task for an in-envelope action.
Flight and package-addition changes require proposal refinement; creative lifecycle changes use
sync_creatives; the remaining accepted controls usecontrol_media_buy.A structured-only action the tables above have not been taught still routes when the bundle's merged
enumMetadatasays it mutatesupdate_media_buyfields. The spec adds these additively and tells SDKs to dispatch on that block, so consulting it keeps a newer bundle working instead of failing closed on a name the tables predate – which is the bugupdate_media_buy_frequency_capexposed. Anything the bundle does not describe either still fails closed withNoneso callers do not guess a route. def sign_legacy_webhook(secret: str,
payload: dict[str, Any] | AdCPBaseModel,
*,
timestamp: str | int | None = None,
headers: dict[str, Any] | None = None) ‑> tuple[dict[str, str], bytes]-
Expand source code
def sign_legacy_webhook( secret: str, payload: dict[str, Any] | AdCPBaseModel, *, timestamp: str | int | None = None, headers: dict[str, Any] | None = None, ) -> tuple[dict[str, str], bytes]: """Return ``(signed_headers, body_bytes)`` for a legacy HMAC webhook. Byte-equality between signature input and HTTP body is guaranteed — callers POST ``content=body_bytes`` instead of ``json=payload``, so the separator-drift trap that caused silent 401s in every spaced-vs-compact interop is structurally impossible here. This is a lower-level companion to :func:`deliver` for callers who need to own the HTTP transport themselves (custom auth, pre-configured ``httpx.AsyncClient``, non-httpx clients). For the one-shot "send a webhook" path, prefer :func:`deliver`. The returned ``body_bytes`` use compact separators (``","``/``":"``) matching the canonical on-wire form pinned by adcontextprotocol/adcp#2478. Example: >>> signed, body = sign_legacy_webhook("shared-secret", payload) >>> headers = {**signed, "Content-Type": "application/json"} >>> await client.post(url, content=body, headers=headers) """ signature_headers, body_bytes = _compute_legacy_signature( secret=secret, timestamp=timestamp, payload=payload ) if headers is not None: merged = {str(k): str(v) for k, v in headers.items()} merged.update(signature_headers) return merged, body_bytes return signature_headers, body_bytesReturn
(signed_headers, body_bytes)for a legacy HMAC webhook.Byte-equality between signature input and HTTP body is guaranteed — callers POST
content=body_bytesinstead ofjson=payload, so the separator-drift trap that caused silent 401s in every spaced-vs-compact interop is structurally impossible here.This is a lower-level companion to :func:
deliverfor callers who need to own the HTTP transport themselves (custom auth, pre-configuredhttpx.AsyncClient, non-httpx clients). For the one-shot "send a webhook" path, prefer :func:deliver.The returned
body_bytesuse compact separators (","/":") matching the canonical on-wire form pinned by adcontextprotocol/adcp#2478.Example -----=
>>> signed, body = sign_legacy_webhook("shared-secret", payload) >>> headers = {**signed, "Content-Type": "application/json"} >>> await client.post(url, content=body, headers=headers) def sign_webhook(*,
method: str,
url: str,
headers: Mapping[str, str],
body: bytes,
private_key: PrivateKey,
key_id: str,
alg: str,
created: int | None = None,
expires_in_seconds: int = 300,
nonce: str | None = None,
label: str = 'sig1') ‑> SignedHeaders-
Expand source code
def sign_webhook( *, method: str, url: str, headers: Mapping[str, str], body: bytes, private_key: PrivateKey, key_id: str, alg: str, created: int | None = None, expires_in_seconds: int = DEFAULT_EXPIRES_IN_SECONDS, nonce: str | None = None, label: str = SIG_LABEL_DEFAULT, ) -> SignedHeaders: """Sign an outgoing webhook POST per adcp/webhook-signing/v1. ``cover_content_digest=True``, ``tag=WEBHOOK_TAG`` and unpadded Base64URL Signature encoding are pinned. The caller attaches ``SignedHeaders.as_dict()`` to the outgoing HTTP request. The ``method`` is normally ``"POST"`` for webhook delivery; passed through unchanged so callers signing a retried ``PUT`` or variant delivery verb are not forced into an extra translation. See also: :class:`adcp.webhooks.WebhookSender` — higher-level one-call helper that builds the payload, signs, and POSTs in a single call. Prefer it unless you need to own the HTTP transport yourself. """ return sign_request( method=method, url=url, headers=headers, body=body, private_key=private_key, key_id=key_id, alg=alg, cover_content_digest=True, created=created, expires_in_seconds=expires_in_seconds, nonce=nonce, tag=WEBHOOK_TAG, label=label, # Webhook-v1 keeps legacy Signature encoding even on AdCP 3.2 routes. # Explicit digest coverage preserves the existing Content-Digest bytes. signing_profile_version="3.1", )Sign an outgoing webhook POST per adcp/webhook-signing/v1.
cover_content_digest=True,tag=WEBHOOK_TAGand unpadded Base64URL Signature encoding are pinned. The caller attachesSignedHeaders.as_dict()to the outgoing HTTP request.The
methodis normally"POST"for webhook delivery; passed through unchanged so callers signing a retriedPUTor variant delivery verb are not forced into an extra translation.See also: :class:
WebhookSender— higher-level one-call helper that builds the payload, signs, and POSTs in a single call. Prefer it unless you need to own the HTTP transport yourself. -
Expand source code
async def start_oauth_authorization( metadata: OAuthAuthorizationServerMetadata, *, client_id: str, redirect_uri: str, store: PendingOAuthFlowStore, issuer_binding: OAuthIssuerBinding, scopes: Sequence[str] = (), resource: str | None = None, ttl_seconds: int = _DEFAULT_FLOW_TTL_SECONDS, clock: Callable[[], datetime] | None = None, allow_loopback_http: bool = False, ) -> OAuthAuthorizationRequest: """Create, persist, and return a browser authorization request. ``DISTINCT_REDIRECT_URI`` is an explicit assertion that this redirect URI is not shared with any other issuer. Prefer ``AUTHORIZATION_RESPONSE_ISS`` when the server advertises RFC 9207 support. """ _validate_public_client_metadata(metadata, allow_loopback_http=allow_loopback_http) if not 1 <= len(client_id) <= _MAX_CLIENT_ID_LENGTH or not _VSCHAR_RE.fullmatch(client_id): raise ValueError("client_id must use bounded RFC 6749 VSCHAR syntax") if isinstance(ttl_seconds, bool) or not 1 <= ttl_seconds <= 3600: raise ValueError("ttl_seconds must be between 1 and 3600") if not isinstance(issuer_binding, OAuthIssuerBinding): raise ValueError("issuer_binding must be an OAuthIssuerBinding value") try: _validate_absolute_url( redirect_uri, field="redirect_uri", allow_loopback_http=allow_loopback_http, ) except ValueError: policy = "HTTPS or a literal loopback HTTP address" if allow_loopback_http else "HTTPS" raise ValueError(f"redirect_uri must use {policy}") from None if ( issuer_binding is OAuthIssuerBinding.AUTHORIZATION_RESPONSE_ISS and not metadata.authorization_response_iss_parameter_supported ): raise ValueError("authorization server does not advertise RFC 9207 issuer responses") scope = _validate_scope(scopes) resource = _validate_resource(resource) now = (clock or (lambda: datetime.now(timezone.utc)))() if now.tzinfo is None: raise ValueError("clock must return a timezone-aware datetime") expires_at = now + timedelta(seconds=ttl_seconds) state = _random_urlsafe(32) verifier = _random_urlsafe(64) challenge = _pkce_challenge(verifier) pending = PendingOAuthAuthorization( state=state, code_verifier=SecretStr(verifier), issuer=metadata.issuer, authorization_endpoint=metadata.authorization_endpoint, token_endpoint=metadata.token_endpoint, client_id=client_id, redirect_uri=redirect_uri, scope=scope, resource=resource, issuer_binding=issuer_binding, allow_loopback_http=allow_loopback_http, created_at=now, expires_at=expires_at, ) if not await store.insert_if_absent(pending): raise OAuthFlowStoreError("state_collision", phase="store") parts = urlsplit(metadata.authorization_endpoint) query = parse_qsl(parts.query, keep_blank_values=True) query.extend( [ ("response_type", "code"), ("client_id", client_id), ("redirect_uri", redirect_uri), ("state", state), ("code_challenge", challenge), ("code_challenge_method", "S256"), ] ) if scope is not None: query.append(("scope", scope)) if resource is not None: query.append(("resource", resource)) authorization_url = urlunsplit((parts.scheme, parts.netloc, parts.path, urlencode(query), "")) if len(authorization_url) > _MAX_URL_LENGTH: # The flow remains stored and must not be reused. Consume it best-effort. await store.consume(state) raise ValueError("authorization URL exceeds the accepted length") return OAuthAuthorizationRequest( authorization_url=authorization_url, state=state, expires_at=expires_at, )Create, persist, and return a browser authorization request.
DISTINCT_REDIRECT_URIis an explicit assertion that this redirect URI is not shared with any other issuer. PreferAUTHORIZATION_RESPONSE_ISSwhen the server advertises RFC 9207 support. async def sync_principal_configuration(client: PrincipalClient,
configuration: Configuration | Mapping[str, Any],
**kwargs: Any) ‑> PrincipalSyncOutcome-
Expand source code
async def sync_principal_configuration( client: PrincipalClient, configuration: PrincipalConfiguration | Mapping[str, Any], **kwargs: Any, ) -> PrincipalSyncOutcome: """Functional wrapper for :meth:`PrincipalManager.sync`.""" return await PrincipalManager(client).sync(configuration, **kwargs)Functional wrapper for :meth:
PrincipalManager.sync(). def to_wire_dict(payload: AdCPBaseModel | Task | TaskStatusUpdateEvent | Mapping[str, Any]) ‑> dict[str, typing.Any]-
Expand source code
def to_wire_dict( payload: AdCPBaseModel | Task | TaskStatusUpdateEvent | Mapping[str, Any], ) -> dict[str, Any]: """Serialize any AdCP webhook payload to a JSON-ready dict. Single seam for adopters that accept "any AdCP webhook payload" — a sender wrapping :func:`create_a2a_webhook_payload` and :func:`create_mcp_webhook_payload` would otherwise have to write per-shape dispatch (``isinstance`` checks, ``MessageToDict`` for protobuf, ``model_dump`` for Pydantic, passthrough for dict). Brittle: a future a2a-sdk that swaps protobuf for a Pydantic façade silently changes which branch runs, and adopters duplicate the dispatch in every send path. Use this helper instead — the dispatch lives here. Behaviour by input shape: * a2a ``Task`` / ``TaskStatusUpdateEvent`` (protobuf, a2a-sdk 1.0+) → ``MessageToDict(..., preserving_proto_field_name=False)`` so JSON keys match the A2A wire spec (camelCase: ``id``, ``contextId``, ``artifactId``). Enum values are normalized from the 1.0 protobuf form (``TASK_STATE_COMPLETED``, ``ROLE_AGENT``) to the 0.3-spec lowercase form (``completed``, ``agent``) so 0.3 buyer receivers keep parsing. * Any Pydantic model (``McpWebhookPayload``, future Pydantic façades, :class:`AdCPBaseModel` subclasses) → ``model_dump(mode="json", exclude_none=True)``. * ``Mapping`` → coerced to ``dict``. Legacy adopter passthrough for callers that build the wire dict by hand. Raises: TypeError: payload is none of the above. """ if isinstance(payload, (Task, TaskStatusUpdateEvent)): data = MessageToDict(payload, preserving_proto_field_name=False) _normalize_a2a_task_state_to_v03(data) return data if hasattr(payload, "model_dump"): model = cast(AdCPBaseModel, payload) return model.model_dump(mode="json", exclude_none=True) if isinstance(payload, Mapping): return dict(payload) raise TypeError( f"Unsupported webhook payload type {type(payload).__name__}: expected " "a2a Task / TaskStatusUpdateEvent (protobuf), an AdCP Pydantic model " "(e.g. McpWebhookPayload), or a Mapping[str, Any]." )Serialize any AdCP webhook payload to a JSON-ready dict.
Single seam for adopters that accept "any AdCP webhook payload" — a sender wrapping :func:
create_a2a_webhook_payload()and :func:create_mcp_webhook_payload()would otherwise have to write per-shape dispatch (isinstancechecks,MessageToDictfor protobuf,model_dumpfor Pydantic, passthrough for dict). Brittle: a future a2a-sdk that swaps protobuf for a Pydantic façade silently changes which branch runs, and adopters duplicate the dispatch in every send path. Use this helper instead — the dispatch lives here.Behaviour by input shape:
- a2a
Task/TaskStatusUpdateEvent(protobuf, a2a-sdk 1.0+) →MessageToDict(..., preserving_proto_field_name=False)so JSON keys match the A2A wire spec (camelCase:id,contextId,artifactId). Enum values are normalized from the 1.0 protobuf form (TASK_STATE_COMPLETED,ROLE_AGENT) to the 0.3-spec lowercase form (completed,agent) so 0.3 buyer receivers keep parsing. - Any Pydantic model (
McpWebhookPayload, future Pydantic façades, :class:AdCPBaseModelsubclasses) →model_dump(mode="json", exclude_none=True). Mapping→ coerced todict. Legacy adopter passthrough for callers that build the wire dict by hand.
- Raises
- -----=
TypeError- payload is none of the above.
- a2a
def translate_universal_macros(pixel_url: str, mapping: MacroMapping) ‑> TranslateUniversalMacrosResult-
Expand source code
def translate_universal_macros( pixel_url: str, mapping: MacroMapping, ) -> TranslateUniversalMacrosResult: """Translate universal macros in query-parameter values. ``ValueMacroMapping`` values are UTF-8 percent-encoded with :func:`encode_unreserved`; ``NativeMacroMapping`` values are inserted verbatim after the full mapping passes the control-character guard. If a parameter value contains any unmapped universal macro, that whole parameter is dropped. Query keys, the path, the fragment, and parameters without universal macros pass through byte-for-byte. Replacement is single-pass. Consent macros supplied through ``ValueMacroMapping`` are translated but reported in ``frozen_consent_macros`` because freezing impression-time consent at producer time can create a privacy defect. Callers should also inspect ``dropped_consent_macros`` and ``suspect_native_values`` before publishing a tracker. Raises: UniversalMacroTranslationError: A native mapping, used or unused, contains U+0000-U+001F or U+007F. No URL is emitted. TypeError: A mapping entry is not a supported typed mapping model. """ frozen_consent_macros: list[str] = [] frozen_seen: set[str] = set() suspect_native_values: list[str] = [] suspect_seen: set[str] = set() validated_mapping: dict[str, MacroMappingEntry] = {} # Validate the entire raw-token trust boundary before doing any URL work. # An unused unsafe entry must reject just like an entry present in the URL. for macro, entry in mapping.items(): if isinstance(entry, NativeMacroMapping): native = entry.native if _has_unsafe_native_character(native): raise UniversalMacroTranslationError(macro) validated_mapping[macro] = NativeMacroMapping(native=native) elif isinstance(entry, ValueMacroMapping): value = entry.value if macro in _CONSENT_MACROS: _append_once(frozen_consent_macros, frozen_seen, macro) if _NATIVE_TOKEN_SHAPE.fullmatch(value): _append_once(suspect_native_values, suspect_seen, macro) validated_mapping[macro] = ValueMacroMapping(value=value) else: raise TypeError( f"mapping entry for {macro!r} must be NativeMacroMapping " "or ValueMacroMapping" ) fragment_index = pixel_url.find("#") if fragment_index == -1: without_fragment = pixel_url fragment = "" else: without_fragment = pixel_url[:fragment_index] fragment = pixel_url[fragment_index:] query_index = without_fragment.find("?") if query_index == -1: return TranslateUniversalMacrosResult( url=pixel_url, dropped_params=[], unmapped_macros=[], dropped_consent_macros=[], frozen_consent_macros=frozen_consent_macros, suspect_native_values=suspect_native_values, ) base = without_fragment[:query_index] raw_query = without_fragment[query_index + 1 :] dropped_params: list[str] = [] unmapped_macros: list[str] = [] unmapped_seen: set[str] = set() dropped_consent_macros: list[str] = [] dropped_consent_seen: set[str] = set() output_parts: list[str] = [] for raw_param in raw_query.split("&"): key, separator, value = raw_param.partition("=") tokens = _UNIVERSAL_MACRO.findall(value) if not tokens: output_parts.append(raw_param) continue missing = [token for token in tokens if token not in validated_mapping] if missing: dropped_params.append(key) for macro in missing: _append_once(unmapped_macros, unmapped_seen, macro) if macro in _CONSENT_MACROS: _append_once( dropped_consent_macros, dropped_consent_seen, macro, ) continue def replace(match: re.Match[str]) -> str: macro = match.group(0) entry = validated_mapping[macro] if isinstance(entry, NativeMacroMapping): return entry.native if isinstance(entry, ValueMacroMapping): return encode_unreserved(entry.value) # The mapping-wide validation above makes this unreachable even # for mutable custom Mapping implementations under normal use. raise TypeError(f"unsupported mapping entry for {macro!r}") translated = _UNIVERSAL_MACRO.sub(replace, value) output_parts.append(f"{key}{separator}{translated}") new_query = "&".join(output_parts) url = f"{base}?{new_query}{fragment}" if new_query else f"{base}{fragment}" return TranslateUniversalMacrosResult( url=url, dropped_params=dropped_params, unmapped_macros=unmapped_macros, dropped_consent_macros=dropped_consent_macros, frozen_consent_macros=frozen_consent_macros, suspect_native_values=suspect_native_values, )Translate universal macros in query-parameter values.
ValueMacroMappingvalues are UTF-8 percent-encoded with :func:encode_unreserved();NativeMacroMappingvalues are inserted verbatim after the full mapping passes the control-character guard. If a parameter value contains any unmapped universal macro, that whole parameter is dropped. Query keys, the path, the fragment, and parameters without universal macros pass through byte-for-byte. Replacement is single-pass.Consent macros supplied through
ValueMacroMappingare translated but reported infrozen_consent_macrosbecause freezing impression-time consent at producer time can create a privacy defect. Callers should also inspectdropped_consent_macrosandsuspect_native_valuesbefore publishing a tracker.- Raises
- -----=
UniversalMacroTranslationError- A native mapping, used or unused, contains U+0000-U+001F or U+007F. No URL is emitted.
TypeError- A mapping entry is not a supported typed mapping model.
def upgrade_legacy_format_id(value: FormatIdInput,
*,
default_agent_url: str = 'https://creative.adcontextprotocol.org') ‑> FormatReferenceStructuredObject-
Expand source code
def upgrade_legacy_format_id( value: FormatIdInput, *, default_agent_url: str = CANONICAL_CREATIVE_AGENT_URL, ) -> FormatId: """Return ``value`` as a canonical, parameterized ``FormatId`` when known. The current canonical upgrade maps legacy display size IDs such as ``display_300x250`` and ``display_300x250_image`` to ``display_image`` with ``width=300`` and ``height=250``. Unknown IDs are still returned as structured ``FormatId`` values so callers can compare them consistently. """ return _upgrade_legacy_format_id(value, default_agent_url=default_agent_url, param="value")Return
valueas a canonical, parameterizedFormatIdwhen known.The current canonical upgrade maps legacy display size IDs such as
display_300x250anddisplay_300x250_imagetodisplay_imagewithwidth=300andheight=250. Unknown IDs are still returned as structuredFormatIdvalues so callers can compare them consistently. def uses_deprecated_assets_field(format: FormatAssetsInput | Mapping[str, Any]) ‑> bool-
Expand source code
def uses_deprecated_assets_field(format: FormatAssetsInput | Mapping[str, Any]) -> bool: """Check if format uses deprecated assets_required field. .. deprecated:: 3.2.0 The ``assets_required`` field was removed in ADCP 3.0.0-beta.2. This function always returns False and will be removed in a future version. Args: format: The Format object Returns: Always False (deprecated field no longer exists) """ warnings.warn( "uses_deprecated_assets_field() is deprecated and always returns False. " "The assets_required field was removed in ADCP 3.0.0-beta.2. " "This function will be removed in a future version.", DeprecationWarning, stacklevel=2, ) return FalseCheck if format uses deprecated assets_required field.
Deprecated since version: 3.2.0
The
assets_requiredfield was removed in ADCP 3.0.0-beta.2. This function always returns False and will be removed in a future version.- Args
- -----=
format- The Format object
Returns -----= Always False (deprecated field no longer exists)
def validate_adagents(adagents: dict[str, Any]) ‑> None-
Expand source code
def validate_adagents(adagents: dict[str, Any]) -> None: """Validate an adagents.json structure. Args: adagents: The adagents.json dict Raises: ValidationError: If validation fails """ authorized_agents = adagents.get("authorized_agents") if isinstance(authorized_agents, list): for agent in authorized_agents: if isinstance(agent, dict): validate_agent_authorization(agent) revoked = adagents.get("revoked_publisher_domains") if revoked is not None: if not isinstance(revoked, list): raise ValidationError("'revoked_publisher_domains' must be an array") for entry in revoked: if not isinstance(entry, dict): raise ValidationError("revoked_publisher_domains entry must be an object") validate_revoked_publisher_domain_entry(entry)Validate an adagents.json structure.
- Args
- -----=
adagents- The adagents.json dict
- Raises
- -----=
ValidationError- If validation fails
async def validate_adagents_domain(publisher_domain: str,
timeout: float = 10.0,
user_agent: str = 'AdCP-Client/1.0',
client: httpx.AsyncClient | None = None,
*,
validate_structure: bool = True,
transport_factory: AdagentsTransportFactory | None = None) ‑> AdAgentsValidationResult-
Expand source code
async def validate_adagents_domain( publisher_domain: str, timeout: float = 10.0, user_agent: str = "AdCP-Client/1.0", client: httpx.AsyncClient | None = None, *, validate_structure: bool = True, transport_factory: AdagentsTransportFactory | None = None, ) -> AdAgentsValidationResult: """Discover and validate a publisher's adagents.json with provenance. Mirrors :func:`fetch_adagents` discovery semantics but returns a typed :class:`AdAgentsValidationResult` exposing which path produced the data (``discovery_method``) and the manager domain used for the ads.txt fallback (``manager_domain``), if any. Errors are reported on the result rather than raised. A manager domain 404 is a terminal failure: ``valid`` is False and ``manager_domain`` is recorded for diagnostics. .. warning:: When ``discovery_method == 'ads_txt_managerdomain'`` the data came from the manager, not the publisher. Callers wiring this into authorization decisions must verify that the source publisher is explicitly named in the manager's adagents.json (e.g., via ``publisher_properties.publisher_domain`` on the relevant authorized_agents entry) before trusting an agent claim — otherwise a manager that lists agent A unconditionally implicitly authorizes A for every publisher pointing MANAGERDOMAIN at the manager. """ try: normalized = _validate_publisher_domain(publisher_domain) except AdagentsValidationError as e: return AdAgentsValidationResult( domain=publisher_domain, url="", errors=[str(e)], ) url = f"https://{normalized}/.well-known/adagents.json" try: data, discovery, *_ = await _resolve_direct( normalized, timeout, user_agent, client, validate_structure=validate_structure, transport_factory=transport_factory, ) return AdAgentsValidationResult( domain=normalized, url=url, discovery_method=discovery, data=data, valid=True, ) except AdagentsNotFoundError as direct_error: direct_error_msg = str(direct_error) except (AdagentsValidationError, AdagentsTimeoutError) as e: return AdAgentsValidationResult( domain=normalized, url=url, errors=[str(e)], ) managers = await _fetch_ads_txt_managerdomains( normalized, timeout, user_agent, client, transport_factory=transport_factory ) if not managers: return AdAgentsValidationResult( domain=normalized, url=url, errors=[direct_error_msg], ) manager_domain = managers[-1] if manager_domain == normalized: return AdAgentsValidationResult( domain=normalized, url=url, errors=[ direct_error_msg, f"ads.txt managerdomain {manager_domain} points back to source publisher", ], ) manager_normalized = _ensure_safe_manager_domain(manager_domain) if manager_normalized is None: return AdAgentsValidationResult( domain=normalized, url=url, errors=[ direct_error_msg, f"ads.txt managerdomain {manager_domain!r} is malformed or " "targets a private/reserved address", ], ) try: manager_data, *_ = await _resolve_direct( manager_normalized, timeout, user_agent, client=None, validate_structure=validate_structure, transport_factory=transport_factory, ) except AdagentsNotFoundError: return AdAgentsValidationResult( domain=normalized, url=url, discovery_method="ads_txt_managerdomain", manager_domain=manager_normalized, errors=[ direct_error_msg, f"manager domain {manager_normalized} did not serve adagents.json", ], ) except (AdagentsValidationError, AdagentsTimeoutError) as e: return AdAgentsValidationResult( domain=normalized, url=url, discovery_method="ads_txt_managerdomain", manager_domain=manager_normalized, errors=[direct_error_msg, str(e)], ) return AdAgentsValidationResult( domain=normalized, url=url, discovery_method="ads_txt_managerdomain", manager_domain=manager_normalized, data=manager_data, valid=True, )Discover and validate a publisher's adagents.json with provenance.
Mirrors :func:
fetch_adagents()discovery semantics but returns a typed :class:AdAgentsValidationResultexposing which path produced the data (discovery_method) and the manager domain used for the ads.txt fallback (manager_domain), if any.Errors are reported on the result rather than raised. A manager domain 404 is a terminal failure:
validis False andmanager_domainis recorded for diagnostics.Warning
When
discovery_method == 'ads_txt_managerdomain'the data came from the manager, not the publisher. Callers wiring this into authorization decisions must verify that the source publisher is explicitly named in the manager's adagents.json (e.g., viapublisher_properties.publisher_domainon the relevant authorized_agents entry) before trusting an agent claim — otherwise a manager that lists agent A unconditionally implicitly authorizes A for every publisher pointing MANAGERDOMAIN at the manager. def validate_adagents_structure(adagents_data: dict[str, Any], *, source_url: str | None = None) ‑> AdagentsValidationReport-
Expand source code
def validate_adagents_structure( adagents_data: dict[str, Any], *, source_url: str | None = None ) -> AdagentsValidationReport: """Structurally validate a parsed adagents.json against the AdCP schema. Use this to distinguish a schema-invalid file from a valid file that doesn't list a particular agent. :func:`get_properties_by_agent` returns ``[]`` for both cases, which makes "publisher hasn't authorized us yet" indistinguishable from "publisher's file is structurally broken." This helper reports per-entry violations against the authoritative ``authorized_agents`` oneOf in the AdCP adagents.json schema. The two real-world failure modes this catches in production publisher files are: * **Bare entries** — ``{url, authorized_for}`` with no ``authorization_type``. The agent looks listed, but matches no schema variant, so the SDK treats the entry as authorizing nothing. * **Wrong selector for type** — e.g., ``{authorization_type: "property_ids", property_tags: [...]}``, where the discriminator and selector array disagree. Args: adagents_data: Parsed adagents.json (the dict returned by :func:`fetch_adagents` or loaded directly from JSON). source_url: Final URL that supplied the document. Required when validating a catalog containing ``reference_renderer`` because ``catalog_role`` is self-declared and does not establish trust. Returns: :class:`AdagentsValidationReport`. ``schema_valid`` is True only when every entry in ``authorized_agents`` satisfies the schema. Raises: AdagentsValidationError: If ``adagents_data`` is not a dict, or ``authorized_agents`` is not a list. These are input-shape errors, not per-entry schema violations. Notes: * URL-reference variants (``authoritative_location`` form) have no inline ``authorized_agents`` array. They're reported with ``is_reference=True``, ``authorized_agents_count == 0``, and ``schema_valid=True``. Callers should follow the redirect (e.g., via :func:`fetch_adagents`, which resolves it automatically) and re-validate the resolved file. * The schema targets AdCP 3.2. Files written against 2.5 (no signal_ids / signal_tags variants) will flag those entries as ``unknown_authorization_type`` — correct for the 3.2 target, but worth knowing if you're validating mixed-version traffic. * Selector-array *item* patterns (e.g., the ``^[a-zA-Z0-9_-]+$`` constraint on each signal_id) are out of scope. This helper validates the discriminator + required selector array; it does not deep-validate selector contents. """ if not isinstance(adagents_data, dict): raise AdagentsValidationError("adagents_data must be a dictionary") authorized_agents = adagents_data.get("authorized_agents") if authorized_agents is None: # URL-reference variant: file points at an authoritative_location # rather than carrying an inline authorized_agents array. properties = adagents_data.get("properties", []) is_reference = isinstance(adagents_data.get("authoritative_location"), str) missing_errors: list[AdagentsEntryError] = [] if not is_reference: missing_errors.append( AdagentsEntryError( index=-1, kind="missing_authorized_agents", message="inline adagents.json requires an authorized_agents array", ) ) return AdagentsValidationReport( schema_valid=not missing_errors, errors=missing_errors, authorized_agents_count=0, properties_count=len(properties) if isinstance(properties, list) else 0, is_reference=is_reference, ) if not isinstance(authorized_agents, list): raise AdagentsValidationError("'authorized_agents' must be an array") properties = adagents_data.get("properties", []) properties_count = len(properties) if isinstance(properties, list) else 0 errors: list[AdagentsEntryError] = [] has_catalog_content = any( isinstance(adagents_data.get(field_name), list) and adagents_data[field_name] for field_name in _CATALOG_CONTENT_FIELDS ) if len(authorized_agents) == 0 and not has_catalog_content: # Beta.3 permits an empty authorization list for catalog-only files, # but a file with neither authorization nor catalog content is invalid. errors.append( AdagentsEntryError( index=-1, kind="empty_authorized_agents", message=( "adagents.json requires at least one authorized agent or a non-empty " "formats, properties, placements, collections, or signals catalog" ), ) ) errors.extend(_reference_renderer_catalog_errors(adagents_data, source_url=source_url)) for index, entry in enumerate(authorized_agents): if not isinstance(entry, dict): errors.append( AdagentsEntryError( index=index, kind="not_an_object", message=f"authorized_agents[{index}] is not a JSON object", ) ) continue raw_url = entry.get("url") url = raw_url if isinstance(raw_url, str) and raw_url else None if url is None: errors.append( AdagentsEntryError( index=index, kind="missing_url", message=f"authorized_agents[{index}] is missing required 'url'", ) ) authorized_for = entry.get("authorized_for") if not isinstance(authorized_for, str) or not authorized_for: errors.append( AdagentsEntryError( index=index, kind="missing_authorized_for", message=( f"authorized_agents[{index}] is missing required " "'authorized_for' description (string, minLength 1)" ), url=url, ) ) authorization_type = entry.get("authorization_type") if authorization_type is None: errors.append( AdagentsEntryError( index=index, kind="missing_authorization_type", message=( f"authorized_agents[{index}] is missing required " "'authorization_type' discriminator (expected one of: " f"{', '.join(sorted(_AUTHORIZATION_TYPE_TO_SELECTOR))})" ), url=url, ) ) continue if authorization_type not in _AUTHORIZATION_TYPE_TO_SELECTOR: errors.append( AdagentsEntryError( index=index, kind="unknown_authorization_type", message=( f"authorized_agents[{index}] has unknown " f"authorization_type={authorization_type!r} " f"(expected one of: " f"{', '.join(sorted(_AUTHORIZATION_TYPE_TO_SELECTOR))})" ), url=url, ) ) continue required_selector = _AUTHORIZATION_TYPE_TO_SELECTOR[authorization_type] selector_value = entry.get(required_selector) if not isinstance(selector_value, list) or len(selector_value) == 0: errors.append( AdagentsEntryError( index=index, kind="missing_selector_for_type", message=( f"authorized_agents[{index}] has " f"authorization_type={authorization_type!r} but is " f"missing required non-empty {required_selector!r} array" ), url=url, ) ) return AdagentsValidationReport( schema_valid=not errors, errors=errors, authorized_agents_count=len(authorized_agents), properties_count=properties_count, )Structurally validate a parsed adagents.json against the AdCP schema.
Use this to distinguish a schema-invalid file from a valid file that doesn't list a particular agent. :func:
get_properties_by_agent()returns[]for both cases, which makes "publisher hasn't authorized us yet" indistinguishable from "publisher's file is structurally broken." This helper reports per-entry violations against the authoritativeauthorized_agentsoneOf in the AdCP adagents.json schema.The two real-world failure modes this catches in production publisher files are:
- Bare entries —
{url, authorized_for}with noauthorization_type. The agent looks listed, but matches no schema variant, so the SDK treats the entry as authorizing nothing. - Wrong selector for type — e.g.,
{authorization_type: "property_ids", property_tags: [...]}, where the discriminator and selector array disagree.
- Args
- -----=
adagents_data- Parsed adagents.json (the dict returned by
:func:
fetch_adagents()or loaded directly from JSON). source_url- Final URL that supplied the document. Required when
validating a catalog containing
reference_rendererbecausecatalog_roleis self-declared and does not establish trust.
Returns -----= :class:
AdagentsValidationReport.schema_validis True only when every entry inauthorized_agentssatisfies the schema.- Raises
- -----=
AdagentsValidationError- If
adagents_datais not a dict, orauthorized_agentsis not a list. These are input-shape errors, not per-entry schema violations.
Notes -----= * URL-reference variants (
authoritative_locationform) have no inlineauthorized_agentsarray. They're reported withis_reference=True,authorized_agents_count == 0, andschema_valid=True. Callers should follow the redirect (e.g., via :func:fetch_adagents(), which resolves it automatically) and re-validate the resolved file. * The schema targets AdCP 3.2. Files written against 2.5 (no signal_ids / signal_tags variants) will flag those entries asunknown_authorization_type— correct for the 3.2 target, but worth knowing if you're validating mixed-version traffic. * Selector-array item patterns (e.g., the^[a-zA-Z0-9_-]+$constraint on each signal_id) are out of scope. This helper validates the discriminator + required selector array; it does not deep-validate selector contents. - Bare entries —
-
Expand source code
def validate_agent_authorization(agent: dict[str, Any]) -> None: """Validate agent authorization discriminated union. AdCP v2.4.0+ uses discriminated unions with authorization_type discriminator: - authorization_type: "property_ids" requires property_ids - authorization_type: "property_tags" requires property_tags - authorization_type: "inline_properties" requires properties - authorization_type: "publisher_properties" requires publisher_properties For backward compatibility, also validates the old mutual exclusivity constraint. Args: agent: An agent dict from adagents.json Raises: ValidationError: If discriminator or field constraints are violated """ authorization_type = agent.get("authorization_type") auth_fields = ["properties", "property_ids", "property_tags", "publisher_properties"] present_fields = [field for field in auth_fields if field in agent and agent[field] is not None] # If authorization_type discriminator is present, validate discriminated union if authorization_type: if authorization_type == "property_ids" and "property_ids" not in present_fields: raise ValidationError( "Agent with authorization_type='property_ids' must have property_ids" ) elif authorization_type == "property_tags" and "property_tags" not in present_fields: raise ValidationError( "Agent with authorization_type='property_tags' must have property_tags" ) elif authorization_type == "inline_properties" and "properties" not in present_fields: raise ValidationError( "Agent with authorization_type='inline_properties' must have properties" ) elif ( authorization_type == "publisher_properties" and "publisher_properties" not in present_fields ): raise ValidationError( "Agent with authorization_type='publisher_properties' " "must have publisher_properties" ) elif authorization_type not in ( "property_ids", "property_tags", "inline_properties", "publisher_properties", ): raise ValidationError(f"Agent has invalid authorization_type: {authorization_type}") # Validate mutual exclusivity (for both old and new formats) if len(present_fields) > 1: raise ValidationError( f"Agent authorization cannot have multiple fields: {', '.join(present_fields)}. " f"Only one of {', '.join(auth_fields)} is allowed." ) if len(present_fields) == 0: raise ValidationError( f"Agent authorization must have exactly one of: {', '.join(auth_fields)}." ) # If using publisher_properties, validate each item if "publisher_properties" in present_fields: for pub_prop in agent["publisher_properties"]: validate_publisher_properties_item(pub_prop)Validate agent authorization discriminated union.
AdCP v2.4.0+ uses discriminated unions with authorization_type discriminator: - authorization_type: "property_ids" requires property_ids - authorization_type: "property_tags" requires property_tags - authorization_type: "inline_properties" requires properties - authorization_type: "publisher_properties" requires publisher_properties
For backward compatibility, also validates the old mutual exclusivity constraint.
- Args
- -----=
agent- An agent dict from adagents.json
- Raises
- -----=
ValidationError- If discriminator or field constraints are violated
def validate_capabilities(handler: Any, capabilities: GetAdcpCapabilitiesResponse) ‑> list[str]-
Expand source code
def validate_capabilities( handler: Any, capabilities: GetAdcpCapabilitiesResponse, ) -> list[str]: """Check that a handler implements the methods required by its declared features. Compares the features declared in a capabilities response against the handler's method implementations. Returns warnings for features that are declared but whose corresponding handler methods are not overridden from the base class. This is a development-time check — call it at startup to catch misconfigurations. Args: handler: An ADCPHandler instance (or any object with handler methods). capabilities: The capabilities response the handler will serve. Returns: List of warning strings. Empty if everything is consistent. """ # Late import to avoid circular dependency: server.base imports from adcp.types # which may transitively import from this module. from adcp.server.base import ADCPHandler resolver = FeatureResolver(capabilities) warnings: list[str] = [] for feature, handler_methods in FEATURE_HANDLER_MAP.items(): if not resolver.supports(feature): continue for method_name in handler_methods: if not hasattr(handler, method_name): warnings.append( f"Feature '{feature}' is declared but handler has no " f"'{method_name}' method" ) continue # Walk MRO to check if any class between the leaf and ADCPHandler # overrides the method (handles mixin / intermediate-class patterns). if isinstance(handler, ADCPHandler): overridden = any( method_name in cls.__dict__ for cls in type(handler).__mro__ if cls is not ADCPHandler and not issubclass(ADCPHandler, cls) ) if not overridden: warnings.append( f"Feature '{feature}' is declared but '{method_name}' " f"is not overridden from ADCPHandler" ) return warningsCheck that a handler implements the methods required by its declared features.
Compares the features declared in a capabilities response against the handler's method implementations. Returns warnings for features that are declared but whose corresponding handler methods are not overridden from the base class.
This is a development-time check — call it at startup to catch misconfigurations.
- Args
- -----=
handler- An ADCPHandler instance (or any object with handler methods).
capabilities- The capabilities response the handler will serve.
Returns -----= List of warning strings. Empty if everything is consistent.
def validate_identifier(identifier_type: str, value: str) ‑> NormalizedIdentifier-
Expand source code
def validate_identifier(identifier_type: str, value: str) -> NormalizedIdentifier: """Validate and return the canonical identifier and its rewrite information.""" return normalize_identifier(identifier_type, value)Validate and return the canonical identifier and its rewrite information.
def validate_product(product: dict[str, Any]) ‑> None-
Expand source code
def validate_product(product: dict[str, Any]) -> None: """Validate a Product object. Args: product: Product dict Raises: ValidationError: If validation fails """ if "publisher_properties" in product and product["publisher_properties"]: for item in product["publisher_properties"]: validate_publisher_properties_item(item)Validate a Product object.
- Args
- -----=
product- Product dict
- Raises
- -----=
ValidationError- If validation fails
def validate_publisher_domain(value: str) ‑> str-
Expand source code
def validate_publisher_domain(value: str) -> str: """Return a canonical publisher hostname; reject URLs and wildcards.""" return normalize_domain(value, allow_wildcard=False).valueReturn a canonical publisher hostname; reject URLs and wildcards.
def validate_publisher_properties_item(item: Any) ‑> None-
Expand source code
def validate_publisher_properties_item(item: Any) -> None: """Validate a single ``publisher_properties[]`` entry. Accepts either a raw ``dict`` (the wire form) or a parsed Pydantic model instance (``PublisherPropertySelector1`` / ``…2`` / ``…3``). For Pydantic instances the model is coerced via ``.model_dump(exclude_none=False)`` and the same checks apply. Two XORs are enforced per the publisher-property-selector JSON Schema (adcp#4504): * Selector XOR: exactly one of ``property_ids`` / ``property_tags`` is present for ``by_id`` / ``by_tag`` (``all`` requires neither). * Publisher XOR: exactly one of ``publisher_domain`` (singular) or ``publisher_domains`` (compact array) is present — both or neither both fail. ``publisher_domains`` is NOT allowed on ``selection_type='by_id'`` since property IDs are publisher-scoped; callers wanting per-publisher ID sets must use one entry per publisher. Why the Pydantic input form matters: ``datamodel-code-generator`` cannot translate the JSON Schema's ``allOf[not[required[both]]] + anyOf[required[either]]`` construct into Pydantic field constraints, so the typed surface (selector 1/3 direct instantiation) is laxer than the schema. Consumers parsing via Pydantic should call this helper post-construction to close the gap. Args: item: A single item from publisher_properties array — either a ``dict`` or a Pydantic ``BaseModel`` instance. Raises: ValidationError: If discriminator or field constraints are violated """ if hasattr(item, "model_dump"): item = item.model_dump(exclude_none=False) if not isinstance(item, dict): raise ValidationError( "publisher_properties item must be a dict or a Pydantic model " f"instance, got {type(item).__name__}" ) selection_type = item.get("selection_type") has_property_ids = "property_ids" in item and item["property_ids"] is not None has_property_tags = "property_tags" in item and item["property_tags"] is not None has_publisher_domain = "publisher_domain" in item and item["publisher_domain"] is not None publisher_domains = item.get("publisher_domains") has_publisher_domains = publisher_domains is not None if selection_type: if selection_type == "by_id" and not has_property_ids: raise ValidationError( "publisher_properties item with selection_type='by_id' must have property_ids" ) elif selection_type == "by_tag" and not has_property_tags: raise ValidationError( "publisher_properties item with selection_type='by_tag' must have property_tags" ) elif selection_type not in ("all", "by_id", "by_tag"): raise ValidationError( f"publisher_properties item has invalid selection_type: {selection_type}" ) if has_property_ids and has_property_tags: raise ValidationError( "publisher_properties item cannot have both property_ids and property_tags. " "These fields are mutually exclusive." ) # selection_type='all' carries neither selector array; older callers # without the discriminator must still provide one of the two. if selection_type not in ("all",) and not has_property_ids and not has_property_tags: raise ValidationError( "publisher_properties item must have either property_ids or property_tags. " "At least one is required." ) if has_publisher_domain and has_publisher_domains: raise ValidationError( "publisher_properties item cannot have both publisher_domain and " "publisher_domains. These fields are mutually exclusive (XOR)." ) if not has_publisher_domain and not has_publisher_domains: raise ValidationError( "publisher_properties item must have exactly one of publisher_domain " "or publisher_domains." ) if has_publisher_domains and selection_type == "by_id": # by_id is single-publisher only — property IDs are publisher-scoped, # so fanning the same ID set across multiple publishers is meaningless. raise ValidationError( "publisher_properties item with selection_type='by_id' cannot use " "publisher_domains[]; property IDs are publisher-scoped. Use one " "entry per publisher with publisher_domain." ) if has_publisher_domains: if not isinstance(publisher_domains, list) or len(publisher_domains) == 0: raise ValidationError( "publisher_properties item publisher_domains must be a non-empty array" ) if any(not isinstance(d, str) or not d for d in publisher_domains): raise ValidationError( "publisher_properties item publisher_domains entries must be non-empty strings" ) if len(set(publisher_domains)) != len(publisher_domains): raise ValidationError( "publisher_properties item publisher_domains entries must be unique" )Validate a single
publisher_properties[]entry.Accepts either a raw
dict(the wire form) or a parsed Pydantic model instance (PublisherPropertySelector1/…2/…3). For Pydantic instances the model is coerced via.model_dump(exclude_none=False)and the same checks apply.Two XORs are enforced per the publisher-property-selector JSON Schema (adcp#4504):
- Selector XOR: exactly one of
property_ids/property_tagsis present forby_id/by_tag(allrequires neither). - Publisher XOR: exactly one of
publisher_domain(singular) orpublisher_domains(compact array) is present — both or neither both fail.publisher_domainsis NOT allowed onselection_type='by_id'since property IDs are publisher-scoped; callers wanting per-publisher ID sets must use one entry per publisher.
Why the Pydantic input form matters:
datamodel-code-generatorcannot translate the JSON Schema'sallOf[not[required[both]]] + anyOf[required[either]]construct into Pydantic field constraints, so the typed surface (selector 1/3 direct instantiation) is laxer than the schema. Consumers parsing via Pydantic should call this helper post-construction to close the gap.- Args
- -----=
item- A single item from publisher_properties array — either a
dictor a PydanticBaseModelinstance. - Raises
- -----=
ValidationError- If discriminator or field constraints are violated
- Selector XOR: exactly one of
def validate_webhook_challenge_response(response: bytes | Mapping[str, Any],
*,
challenge: str,
field: str | None = None,
url: str | None = None) ‑> str-
Expand source code
def validate_webhook_challenge_response( response: bytes | Mapping[str, Any], *, challenge: str, field: str | None = None, url: str | None = None, ) -> str: """Validate that a receiver echoed the challenge value. Receivers may respond with either ``{"challenge": "<value>"}`` or ``{"token": "<value>"}``. The return value is the field that matched. """ try: if isinstance(response, bytes): decoded = json.loads(response.decode("utf-8")) else: decoded = dict(response) except (UnicodeDecodeError, json.JSONDecodeError, TypeError, ValueError) as exc: raise WebhookChallengeError( "webhook challenge response must be a JSON object", reason="invalid_json", field=field, url=url, ) from exc if not isinstance(decoded, Mapping): raise WebhookChallengeError( "webhook challenge response must be a JSON object", reason="invalid_json", field=field, url=url, ) for key in ("challenge", "token"): value = decoded.get(key) if value == challenge: return key if "challenge" in decoded or "token" in decoded: reason = "challenge_mismatch" message = "webhook challenge response did not echo the expected value" else: reason = "missing_echo" message = "webhook challenge response must include 'challenge' or 'token'" raise WebhookChallengeError(message, reason=reason, field=field, url=url)Validate that a receiver echoed the challenge value.
Receivers may respond with either
{"challenge": "<value>"}or{"token": "<value>"}. The return value is the field that matched. -
Expand source code
def verify_agent_authorization( adagents_data: dict[str, Any], agent_url: str, property_type: str | None = None, property_identifiers: list[dict[str, str]] | None = None, ) -> bool: """Check if agent is authorized for a property. Args: adagents_data: Parsed adagents.json data agent_url: URL of the sales agent to verify property_type: Type of property (website, app, etc.) - optional property_identifiers: List of identifiers to match - optional Returns: True if agent is authorized, False otherwise Raises: AdagentsValidationError: If adagents_data is malformed Notes: - If property_type/identifiers are None, checks if agent is authorized for ANY property on this domain - Implements AdCP domain matching rules - Agent URLs are matched ignoring protocol and trailing slash """ for agent in find_authorized_agent_entries(adagents_data, agent_url): # Found matching agent - now check properties properties = agent.get("properties") # If properties field is missing or empty, agent is authorized for all properties if properties is None or (isinstance(properties, list) and len(properties) == 0): return True # If no property filters specified, we found the agent - authorized if property_type is None and property_identifiers is None: return True # Check specific property authorization if isinstance(properties, list): for prop in properties: if not isinstance(prop, dict): continue # Check property type if specified if property_type is not None: prop_type = prop.get("property_type", "") if prop_type != property_type: continue # Check identifiers if specified if property_identifiers is not None: prop_identifiers = prop.get("identifiers", []) if not isinstance(prop_identifiers, list): continue if identifiers_match(property_identifiers, prop_identifiers): return True else: # Property type matched and no identifier check needed return True return FalseCheck if agent is authorized for a property.
- Args
- -----=
adagents_data- Parsed adagents.json data
agent_url- URL of the sales agent to verify
property_type- Type of property (website, app, etc.) - optional
property_identifiers- List of identifiers to match - optional
Returns -----= True if agent is authorized, False otherwise
- Raises
- -----=
AdagentsValidationError- If adagents_data is malformed
Notes -----= - If property_type/identifiers are None, checks if agent is authorized for ANY property on this domain - Implements AdCP domain matching rules - Agent URLs are matched ignoring protocol and trailing slash
async def verify_agent_for_property(publisher_domain: str,
agent_url: str,
property_identifiers: list[dict[str, str]],
property_type: str | None = None,
timeout: float = 10.0,
client: httpx.AsyncClient | None = None) ‑> bool-
Expand source code
async def verify_agent_for_property( publisher_domain: str, agent_url: str, property_identifiers: list[dict[str, str]], property_type: str | None = None, timeout: float = 10.0, client: httpx.AsyncClient | None = None, ) -> bool: """Convenience wrapper to fetch adagents.json and verify authorization in one call. Args: publisher_domain: Domain hosting the adagents.json file agent_url: URL of the sales agent to verify property_identifiers: List of identifiers to match property_type: Type of property (website, app, etc.) - optional timeout: Request timeout in seconds client: Optional httpx.AsyncClient for connection pooling Returns: True if agent is authorized, False otherwise Raises: AdagentsNotFoundError: If adagents.json not found (404) AdagentsValidationError: If JSON is invalid or malformed AdagentsTimeoutError: If request times out """ adagents_data = await fetch_adagents(publisher_domain, timeout=timeout, client=client) return verify_agent_authorization( adagents_data=adagents_data, agent_url=agent_url, property_type=property_type, property_identifiers=property_identifiers, )Convenience wrapper to fetch adagents.json and verify authorization in one call.
- Args
- -----=
publisher_domain- Domain hosting the adagents.json file
agent_url- URL of the sales agent to verify
property_identifiers- List of identifiers to match
property_type- Type of property (website, app, etc.) - optional
timeout- Request timeout in seconds
client- Optional httpx.AsyncClient for connection pooling
Returns -----= True if agent is authorized, False otherwise
- Raises
- -----=
AdagentsNotFoundError- If adagents.json not found (404)
AdagentsValidationError- If JSON is invalid or malformed
AdagentsTimeoutError- If request times out
async def verify_cross_domain_properties(properties: list[dict[str, Any]],
publisher_domain: str,
agent_url: str,
*,
fetcher: Callable[[str], Awaitable[dict[str, Any]]] | None = None) ‑> list[dict[str, typing.Any]]-
Expand source code
async def verify_cross_domain_properties( properties: list[dict[str, Any]], publisher_domain: str, agent_url: str, *, fetcher: Callable[[str], Awaitable[dict[str, Any]]] | None = None, ) -> list[dict[str, Any]]: """Return the subset of resolved properties vouched for by their domains. ``publisher_domain`` is the trusted origin of the source manifest, not a value read from that manifest. First resolve its agent selectors with :func:`get_properties_by_agent` or :func:`resolve_properties_for_agent`. Every external ``publisher_domain``, domain or subdomain identifier must authorize the same inventory for ``agent_url`` in strict resolution. Domain identifiers take precedence over file-local property IDs when comparing inventory. Inventory with no identifiers uses its publisher anchor and property ID. Remote authorizations must be attributable to the checked domain; unanchored apps in a shared manager file cannot vouch for it. Local properties (including subdomains) and unanchored non-domain inventory pass through; the latter cannot be verified by this helper. The default fetcher is :func:`fetch_adagents`, including its SSRF gates, ``authoritative_location`` following and ads.txt MANAGERDOMAIN discovery. Delegated manifests must still authorize the particular property; merely listing an agent or delegating to a manager is insufficient. A custom async ``fetcher(domain)`` must provide the same secure discovery semantics. Each external domain is fetched once per call, sequentially. Missing, invalid, revoked or unavailable authorizations are excluded, with failures logged at debug level. No recursive property verification is performed. Returns original objects in input order without mutation. """ source = _publisher_attribution_domain(publisher_domain) fetch = fetcher if fetcher is not None else fetch_adagents authorizations: dict[str, list[dict[str, Any]]] = {} verified: list[dict[str, Any]] = [] for prop in properties: try: anchor = ( _publisher_attribution_domain(prop["publisher_domain"]) if "publisher_domain" in prop else None ) domains = [anchor] if anchor is not None else [] for identifier in _property_domain_identifiers(prop, include_subdomains=True): normalized = _property_identity_identifier(identifier) if normalized is None: raise AdagentsValidationError("Invalid property domain identifier") domain = _publisher_attribution_domain(normalized["value"].removeprefix("*.")) if domain not in domains: domains.append(domain) except AdagentsValidationError: continue for domain in domains: if _domain_is_under_publisher(domain, source): continue # The anchor is checked first. Its verified authorization covers # its own subdomains, matching the source-domain trust boundary. if ( anchor is not None and domain != anchor and _domain_is_under_publisher(domain, anchor) ): continue if domain not in authorizations: try: data = await fetch(domain) revoked = { _publisher_attribution_domain(d) for d in _get_revoked_publisher_domains(data) } try: candidates = get_properties_by_agent(data, agent_url) except (TypeError, ValueError) as exc: raise AdagentsValidationError( "Malformed remote property authorization" ) from exc authorizations[domain] = ( [] if domain in revoked else properties_for_publisher_domain( candidates, domain, include_unattributed=False ) ) except ( AdagentsNotFoundError, AdagentsValidationError, AdagentsTimeoutError, httpx.HTTPError, OSError, ) as exc: logger.debug("Cross-domain authorization failed for %s: %s", domain, exc) authorizations[domain] = [] if not any(_same_authorized_property(prop, p) for p in authorizations[domain]): break else: verified.append(prop) return verifiedReturn the subset of resolved properties vouched for by their domains.
publisher_domainis the trusted origin of the source manifest, not a value read from that manifest. First resolve its agent selectors with :func:get_properties_by_agent()or :func:resolve_properties_for_agent().Every external
publisher_domain, domain or subdomain identifier must authorize the same inventory foragent_urlin strict resolution. Domain identifiers take precedence over file-local property IDs when comparing inventory. Inventory with no identifiers uses its publisher anchor and property ID. Remote authorizations must be attributable to the checked domain; unanchored apps in a shared manager file cannot vouch for it. Local properties (including subdomains) and unanchored non-domain inventory pass through; the latter cannot be verified by this helper.The default fetcher is :func:
fetch_adagents(), including its SSRF gates,authoritative_locationfollowing and ads.txt MANAGERDOMAIN discovery. Delegated manifests must still authorize the particular property; merely listing an agent or delegating to a manager is insufficient. A custom asyncfetcher(domain)must provide the same secure discovery semantics.Each external domain is fetched once per call, sequentially. Missing, invalid, revoked or unavailable authorizations are excluded, with failures logged at debug level. No recursive property verification is performed. Returns original objects in input order without mutation.
Classes
class ADCPAuthenticationError (message: str,
agent_id: str | None = None,
agent_uri: str | None = None,
*,
status_code: int | None = None,
www_authenticate: str | None = None)-
Expand source code
class ADCPAuthenticationError(ADCPError): """Authentication failed (401, 403). `is_retryable` defaults to ``False`` (inherited). Per the AdCP 3.0.4 prose tightening, `AUTH_REQUIRED` covers two sub-cases: credentials missing (correctable — supply credentials and retry) and credentials presented but rejected (terminal — re-presenting creates SSO retry-storm patterns). Defaulting to non-retryable is the safe biased-toward-the-dangerous-case choice; callers handling the missing-credentials case should retry only after attaching credentials, not on a timer. The 3.1 line splits this into `AUTH_MISSING` and `AUTH_INVALID`. MCP HTTP authentication failures expose ``status_code`` and ``www_authenticate`` when available, preserving the server's challenge for credential recovery. """ def __init__( self, message: str, agent_id: str | None = None, agent_uri: str | None = None, *, status_code: int | None = None, www_authenticate: str | None = None, ): """Initialize authentication error.""" self.status_code = status_code self.www_authenticate = www_authenticate suggestion = ( "Check that your auth_token is valid and not expired.\n" " Verify auth_type ('bearer' vs 'token') and auth_header are correct.\n" " Some agents (like Optable) require auth_type='bearer' and " "auth_header='Authorization'" ) super().__init__(message, agent_id, agent_uri, suggestion)Authentication failed (401, 403).
is_retryabledefaults toFalse(inherited). Per the AdCP 3.0.4 prose tightening,AUTH_REQUIREDcovers two sub-cases: credentials missing (correctable — supply credentials and retry) and credentials presented but rejected (terminal — re-presenting creates SSO retry-storm patterns). Defaulting to non-retryable is the safe biased-toward-the-dangerous-case choice; callers handling the missing-credentials case should retry only after attaching credentials, not on a timer. The 3.1 line splits this intoAUTH_MISSINGandAUTH_INVALID.MCP HTTP authentication failures expose
status_codeandwww_authenticatewhen available, preserving the server's challenge for credential recovery.Initialize authentication error.
Ancestors
- ADCPError
- builtins.Exception
- builtins.BaseException
Inherited members
class ADCPClient (agent_config: AgentConfig,
webhook_url_template: str | None = None,
webhook_secret: str | None = None,
on_activity: Callable[[Activity], None] | None = None,
webhook_timestamp_tolerance: int = 300,
capabilities_ttl: float = 3600.0,
validate_features: bool = False,
strict_idempotency: bool = False,
signing: SigningConfig | None = None,
context_id: str | None = None,
validation: ValidationHookConfig | None = None,
force_a2a_version: str | None = None,
adcp_version: str | None = None,
server_version: str | None = None,
legacy_format_converter: LegacyFormatConverter | None = None,
canonical_format_legacy_resolver: CanonicalFormatLegacyResolver | None = None,
allow_unauthenticated_webhooks: bool = False,
httpx_client_factory: MCPHttpxClientFactory | None = None,
account_policy: AccountPolicy | None = None,
account_storage: AccountStorage | None = None,
raise_account_errors: bool | None = None,
product_property_policy: ProductPropertyPolicy | None = None)-
Expand source code
class ADCPClient: """Client for interacting with a single AdCP agent.""" def __init__( self, agent_config: AgentConfig, webhook_url_template: str | None = None, webhook_secret: str | None = None, on_activity: Callable[[Activity], None] | None = None, webhook_timestamp_tolerance: int = 300, capabilities_ttl: float = 3600.0, validate_features: bool = False, strict_idempotency: bool = False, signing: SigningConfig | None = None, context_id: str | None = None, validation: ValidationHookConfig | None = None, force_a2a_version: str | None = None, adcp_version: str | None = None, server_version: str | None = None, legacy_format_converter: LegacyFormatConverter | None = None, canonical_format_legacy_resolver: CanonicalFormatLegacyResolver | None = None, allow_unauthenticated_webhooks: bool = False, httpx_client_factory: MCPHttpxClientFactory | None = None, account_policy: AccountPolicy | None = None, account_storage: AccountStorage | None = None, raise_account_errors: bool | None = None, product_property_policy: ProductPropertyPolicy | None = None, ): """ Initialize ADCP client for a single agent. Args: agent_config: Agent configuration product_property_policy: Optional buyer-side property-list check; filters or flags seller products and reports unjudgeable inventory in TaskResult.metadata. Disabled by default. webhook_url_template: Template for webhook URLs with {agent_id}, {task_type}, {operation_id} webhook_secret: Shared secret for the deprecated HMAC-SHA256 webhook fallback. Configure this only when the registration explicitly selected legacy HMAC; conformant public endpoints should use :class:`adcp.webhooks.WebhookReceiver` for RFC 9421 verification. allow_unauthenticated_webhooks: Explicit compatibility escape for accepting unsigned MCP webhooks when ``webhook_secret`` is not configured. Defaults to False so public webhook receivers fail closed. Only enable this for endpoints that cannot be reached from an untrusted network. A2A webhook handling is unaffected. on_activity: Callback for activity events webhook_timestamp_tolerance: Maximum age (in seconds) for webhook timestamps. Webhooks with timestamps older than this or more than this far in the future are rejected. Defaults to 300 (5 minutes). capabilities_ttl: Time-to-live in seconds for cached capabilities (default: 1 hour) account_policy: Default natural-key policy. ``off`` (the 8.x default) sends account references unchanged, as 8.0 did. ``auto`` omits unknown keys on optional discovery and rejects them elsewhere before transport; ``strict`` rejects them everywhere. Preflight rejections raise typed account errors. Leaving this unset emits a ``DeprecationWarning`` the first time a natural-key reference is sent: the default becomes ``auto`` in the next major release. account_storage: Async provisioning-record storage, private to the authenticated buyer. Defaults to in-memory storage. raise_account_errors: When True, seller-returned account errors (``ACCOUNT_NOT_FOUND``, ``ACCOUNT_REQUIRED``, ``ACCOUNT_SETUP_REQUIRED``, ``ACCOUNT_PAYMENT_REQUIRED``) raise ``AccountNotFoundError`` / ``AccountSetupRequiredError`` / ``AccountPaymentRequiredError`` (``ADCPTaskError`` subclasses). The 8.x default returns the failed ``TaskResult`` as 8.0 did and emits a ``DeprecationWarning`` when unset; the default becomes True in the next major release. validate_features: When True, automatically check that the seller supports required features before making task calls (e.g., sync_audiences requires audience_targeting). Requires capabilities to have been fetched first. strict_idempotency: When True, verify the seller declared ``adcp.idempotency.replay_ttl_seconds`` in capabilities before any mutating call. Fetches capabilities lazily on first use. Raises ``IdempotencyUnsupportedError`` if the declaration is missing — sellers that don't declare it provide no retry-safety guarantee per AdCP #2315. Defaults to False for backward compatibility. signing: Optional RFC 9421 request-signing config. When provided, the client automatically attaches ``Signature`` / ``Signature-Input`` / ``Content-Digest`` headers to operations the seller's ``request_signing`` capability lists in ``required_for``, ``warn_for``, or ``supported_for``. The seller's ``covers_content_digest`` policy determines whether the body is bound to the signature. Generate a key with ``adcp-keygen`` and publish the public JWK at your ``jwks_uri``. Supported on both A2A and MCP (``mcp_transport="streamable_http"``); SSE-transport MCP logs a warning and falls through unsigned. httpx_client_factory: MCP-only factory for the async HTTP client used by streamable HTTP, SSE, and explicit session close. Use this to enforce an application-owned egress policy. The factory must accept the standard MCP client kwargs and return a compatible client with ``trust_env=False`` and ``follow_redirects=False``; the SDK verifies both and composes request-signing hooks with the client's existing hooks. MCP SDK v2 uses ``httpx2``; a plain ``httpx.AsyncClient`` (including one using the signing package's httpx-native pinned transport) is not wire-compatible and is rejected explicitly. validation: Schema-driven validation modes for outgoing requests and incoming responses against the bundled AdCP JSON schemas. Defaults (matching the TS port): requests in ``warn`` mode (drift logged but not blocked — partial payloads in error-path tests still work) and responses in ``strict`` mode (agent drift fails the task). ``ADCP_VALIDATION_MODE=strict|warn|off`` overrides both sides at call time (matches the TS port); ``ADCP_ENV`` set to ``production`` / ``prod`` flips only the response default to ``warn``. Generic ``ENV`` / ``ENVIRONMENT`` / ``PYTHON_ENV`` are deliberately ignored — they collide with unrelated tooling. Storyboards and compliance runners that want hard-stop enforcement everywhere pass ``validation=ValidationHookConfig(requests="strict", responses="strict")``; high-throughput callers can set either side to ``"off"`` to skip the validator entirely with zero overhead. context_id: A2A-only. Seed the A2A conversation context. Pass a previously-returned ``context_id`` to resume a session across process restarts, or a self-assigned UUID to name the session with your own correlation key (the ADK server honors buyer-proposed ids). If omitted, the server mints one on the first message and this client auto-retains it for subsequent calls. Read the current value via ``client.context_id``; call ``client.reset_context()`` to start a fresh conversation. Rule of thumb: one ``ADCPClient`` per A2A conversation — if a buyer has multiple concurrent briefs with the same agent, construct one client per brief rather than sharing. For HITL flows that can span a process restart mid-task, use ``checkpoint()`` / ``from_checkpoint()`` instead of persisting ``context_id`` alone — full resume state is both ``context_id`` AND ``active_task_id``. Raises ``TypeError`` if passed with a non-A2A protocol. force_a2a_version: A2A-only. Pin the **A2A transport version** (e.g. ``"0.3"``, ``"1.0"``) by filtering the peer's advertised ``supported_interfaces`` to entries whose ``protocol_version`` matches. Not for AdCP protocol pinning — see ``adcp_version`` for that. Intended for tests or for forcing a 0.3-speaking path against a dual-advertising peer. Raises :class:`ADCPConnectionError` on the first call if no advertised interface matches. ``None`` (default) lets the SDK's ``ClientFactory`` pick the most capable transport the peer supports. Use :attr:`a2a_protocol_versions` to probe what a peer advertises before pinning. Raises ``TypeError`` if passed with a non-A2A protocol. adcp_version: Maximum AdCP protocol release to negotiate (release-precision string, e.g. ``"3.0"``, ``"3.1"``, ``"3.1-beta"``). Each call selects the highest release shared with the seller, at or below this ceiling. Application requests and responses use the SDK's latest models. ``None`` (default) resolves to the SDK's compile-time pin (``ADCP_VERSION`` packaged with the wheel). Cross-major pins raise :class:`ConfigurationError` at construction; install the SDK major that targets your wire version instead. Patch-precision strings (``"3.0.1"``) and build metadata (``"3.0.1+canary"``) are accepted at construction but normalized to release-precision before wire emission per the spec — patches and build metadata are not part of the negotiation contract. ``get_adcp_version()`` returns the normalized form. Caller-supplied ``adcp_version`` on a per-call params dict supplies that call's ceiling. ``server_version`` explicitly declares the peer's wire version and bypasses discovery. Migration from ``adcp_major_version`` (legacy integer wire field): generated request types still expose ``adcp_major_version: int | None`` from the pre-#3493 schema. Both fields will coexist on the wire through 3.x; servers prefer the new ``adcp_version`` when both are present. Stop populating ``adcp_major_version`` on request models once your seller advertises 3.1 in ``supported_versions``. server_version: AdCP wire shape the *seller* speaks. Most adopters leave this ``None`` — the SDK assumes a v3 seller and the seller's ``/.well-known/agent-card.json`` is the canonical source of truth once a probe-and-cache path lands. Pin explicitly when: * You're talking to a known-legacy seller (e.g. ``server_version="3.0"``). Canonical discovery results are upgraded for application code and canonical writes are downgraded only through preserved or explicit routes. * You want telemetry to attribute outbound traffic to a specific server-side version regardless of what the seller advertises. Retrieve the current value via :meth:`get_server_version`. """ self._adcp_version: str = resolve_adcp_version(adcp_version) self._server_version: str | None = _resolve_server_version(server_version) if type(allow_unauthenticated_webhooks) is not bool: raise TypeError("allow_unauthenticated_webhooks must be a bool") self.agent_config = agent_config if account_policy is not None and account_policy not in ACCOUNT_POLICIES: raise ValueError("account_policy must be 'off', 'auto', or 'strict'") if raise_account_errors is not None and type(raise_account_errors) is not bool: raise TypeError("raise_account_errors must be a bool") self._account_policy_explicit = account_policy is not None self._account_policy_warned = False self.account_policy: AccountPolicy = account_policy or "off" self._raise_account_errors_explicit = raise_account_errors is not None self.raise_account_errors = raise_account_errors is True self.accounts = AccountRegistry(self, account_storage) self.webhook_url_template = webhook_url_template self.webhook_secret = webhook_secret self.allow_unauthenticated_webhooks = allow_unauthenticated_webhooks self.on_activity = on_activity self.webhook_timestamp_tolerance = webhook_timestamp_tolerance self.capabilities_ttl = capabilities_ttl self.validate_features = validate_features self.strict_idempotency = strict_idempotency self.signing = signing self.product_property_policy = product_property_policy if httpx_client_factory is not None and not callable(httpx_client_factory): raise TypeError("httpx_client_factory must be callable") if httpx_client_factory is not None and agent_config.protocol != Protocol.MCP: raise TypeError( "httpx_client_factory is only supported for MCP protocol; " f"got {agent_config.protocol}" ) if ( signing is not None and agent_config.agent_uri.startswith("http://") and not is_loopback_http_uri(agent_config.agent_uri) ): raise ValueError( "request signing requires an https:// agent_uri for non-loopback hosts; " "plain HTTP is only allowed for localhost/loopback development" ) self.legacy_format_converter = legacy_format_converter self.canonical_format_legacy_resolver = canonical_format_legacy_resolver self._canonical_legacy_routes: dict[ tuple[str | None, str | None, str], list[dict[str, Any]] | None ] = {} # Capabilities cache self._capabilities: GetAdcpCapabilitiesResponse | None = None self._capabilities_wire_version: str | None = None self._task_wire_contexts: dict[tuple[str, str], ConversionResult] = {} self._feature_resolver: FeatureResolver | None = None self._capabilities_fetched_at: float | None = None self._idempotency_capability_verified: bool = False # Unique per-instance token so use_idempotency_key scopes to this # client and does not bleed to siblings (AdCP #2315 cross-seller risk). from uuid import uuid4 as _uuid4 self._idempotency_client_token: str = _uuid4().hex self._task_options_token = object() if force_a2a_version is not None and agent_config.protocol != Protocol.A2A: raise TypeError( f"force_a2a_version is only supported for A2A protocol; got {agent_config.protocol}" ) # Initialize protocol adapter self.adapter: ProtocolAdapter if agent_config.protocol == Protocol.A2A: self.adapter = A2AAdapter(agent_config, force_a2a_version=force_a2a_version) elif agent_config.protocol == Protocol.MCP: self.adapter = MCPAdapter( agent_config, httpx_client_factory=httpx_client_factory, ) else: raise ValueError(f"Unsupported protocol: {agent_config.protocol}") self.adapter.task_options_client_token = self._task_options_token if is_tracing_available(): self.adapter.tracing_request_hook = self._inject_outgoing_trace_context self.adapter.idempotency_client_token = self._idempotency_client_token if strict_idempotency: self.adapter.idempotency_capability_check = self._ensure_idempotency_capability if signing is not None: self._negotiated_signing_profiles = NegotiatedSigningProfiles() self.adapter.signing_request_hook = self._sign_outgoing_request self.adapter.signing_capability_check = self._prepare_signing_capabilities self.adapter.signing_request_scope = self._negotiated_signing_profiles.bind # Apply schema validation modes (default: requests=warn, responses=strict # in dev/test, warn in production — see ``ValidationHookConfig`` docs). self.adapter.configure_validation(validation) # Auto-inject the per-instance ``adcp_version`` pin into every # outbound request envelope. Caller-supplied values on the # request object win — the enricher is the default, not an # override — so per-call overrides remain available once the # generated request types declare the field. _pinned_version = self._server_version or self._adcp_version self._signing_profile_version = ( None if signing is None else signing.signing_profile_version or signing_profile_for_adcp_version(_pinned_version) ) def _inject_adcp_version(params: dict[str, Any]) -> dict[str, Any]: return {"adcp_version": _pinned_version, **params} self.adapter.envelope_enricher = _inject_adcp_version self.adapter.request_converter = self._prepare_versioned_task self.adapter.response_converter = self._convert_incoming_response if context_id: # Empty string is treated as "not provided" — callers using # ``context_id=os.getenv("...") or ""`` patterns shouldn't # silently seed an empty id on the wire. if not isinstance(self.adapter, A2AAdapter): raise TypeError( f"context_id is only supported for A2A protocol; got {agent_config.protocol}" ) self.adapter.set_context_id(context_id) # Initialize simple API accessor (lazy import to avoid circular dependency) from adcp.simple import SimpleAPI self.simple = SimpleAPI(self) async def _prepare_versioned_task(self, tool: str, params: dict[str, Any]) -> ConversionResult: """Convert version preflight failures to the public task-result contract.""" try: return await self._convert_outgoing_request(tool, params) except ADCPFeatureUnsupportedError as exc: message = str(exc) details: dict[str, Any] = {"wire_response_received": False} for name in ("pointer", "source_version", "target_version", "reason"): if getattr(exc, name, None) is not None: details[name] = getattr(exc, name) result = TaskResult[Any]( status=TaskStatus.FAILED, success=False, error=message, adcp_error={"code": "UNSUPPORTED_FEATURE", "message": message, "details": details}, idempotency_key=params.get("idempotency_key"), metadata={ CONVERSION_METADATA_KEY: { "wire_version": details.get("target_version"), "losses": [], } }, ) raise _TaskPreparationError( message, result=result, agent_id=self.agent_config.id, agent_uri=self.agent_config.agent_uri, ) from exc async def _convert_outgoing_request( self, tool: str, params: dict[str, Any] ) -> ConversionResult: """Negotiate independently for each call; discovery uses its own envelope.""" if tool == "get_adcp_capabilities": # An unversioned discovery request works before the peer's version # set is known. Preserve explicit discovery pins for callers. return ConversionResult(dict(params)) maximum = params.get("adcp_version") or self._adcp_version declared_peer = self._server_version or maximum if not str(declared_peer).startswith("3."): return ConversionResult(self.adapter._enrich_outgoing_params(params)) if "-" in str(declared_peer) and declared_peer != "3.2-rc.7": # Historical prerelease pins keep their exact contract and gates; # minor-release translators must not guess prerelease semantics. return ConversionResult(self.adapter._enrich_outgoing_params(params)) if self._server_version is not None: target = negotiate_version([self._server_version], maximum=maximum) else: caps = await self.fetch_capabilities() declared = caps.model_dump(mode="json", exclude_none=True).get("adcp", {}) supported = declared.get("supported_versions") if supported is None: # Major-only advertisements predate minor negotiation. supported = ["3.0"] if 3 in declared.get("major_versions", []) else [] target = negotiate_version(supported, maximum=maximum) prepared = deepcopy(params) prepared["adcp_version"] = target try: prepared, migrations = await self.accounts.preserve_wire_keys( tool, prepared, version=target ) except Exception: if self.account_policy != "off": raise logger.warning("Account continuity storage unavailable for %s", self.agent_config.id) migrations = [] continuity_losses: list[ConversionLoss] = [] for migration in migrations: pointer = migration["pointer"] if pointer == "/account": original, retained = params.get("account", {}), prepared.get("account", {}) else: index = int(pointer.split("/")[-1]) original, retained = params["accounts"][index], prepared["accounts"][index] dropped = [ name for name in ("operator_unit", "currency", "timezone") if name in original and name not in retained ] if "countries" in original.get("brand", {}) and "countries" not in retained.get( "brand", {} ): dropped.append("brand/countries") for name in dropped: loss = ConversionLoss( f"{pointer}/{name}", resolve_adcp_version(None), migration["provisioned_wire_version"], "account_identity_migration_pending", ) continuity_losses.append(loss) logger.warning("Account continuity retained an older identity at %s", loss.pointer) dialect = ( self._creative_dialect(prepared, legacy_projection_available=True) if tool in _LEGACY_CREATIVE_TASKS else None ) if dialect is CreativeDialect.LEGACY: for collection in ("packages", "new_packages"): for index, package in enumerate(prepared.get(collection) or []): if isinstance(package, dict): self._downgrade_package(package, field=f"{collection}[{index}]") for index, creative in enumerate(prepared.get("creatives") or []): if creative.get("format_kind") or creative.get("format_option_ref"): self._downgrade_creative(creative, field=f"creatives[{index}]") converted = convert_payload( tool, prepared, direction="request", source_version=resolve_adcp_version(None), target_version=target, # Buyer side: each dropped request field is buyer data the # seller will never see. loss_log_level=logging.WARNING, ) return ConversionResult( converted.payload, converted.losses + tuple(continuity_losses), dialect.value if dialect is not None else None, identity_migrations=tuple(migrations), ) def _convert_incoming_response( self, tool: str, result: TaskResult[Any], request: ConversionResult ) -> TaskResult[Any]: """Upgrade validated wire data and retain request losses on failures too.""" version = self.adapter._request_version(request.payload) losses = request.metadata() if result.success and isinstance(result.data, dict): version = version or result.data.get("adcp_version") if ( isinstance(version, str) and version.startswith("3.") and "-" not in resolve_adcp_version_alias(normalize_to_release_precision(version)) ): direction = result.data.get("status") try: converted = convert_payload( tool, result.data, direction=( direction if direction in {"submitted", "working", "input-required"} else "sync" ), source_version=version, target_version=resolve_adcp_version(None), request=request.payload, # Buyer side: a dropped response field is seller # data the buyer may care about. loss_log_level=logging.WARNING, ) result = result.model_copy(update={"data": converted.payload}) losses.extend(converted.metadata()) except ADCPFeatureUnsupportedError as exc: message = str(exc) metadata = dict(result.metadata or {}) metadata["adcp_conversion_wire_response"] = result.data details = { "source_version": version, "target_version": resolve_adcp_version(None), "wire_response_received": True, } for name in ("pointer", "reason"): if getattr(exc, name, None) is not None: details[name] = getattr(exc, name) result = result.model_copy( update={ "success": False, "status": TaskStatus.FAILED, "data": None, "error": message, "metadata": metadata, "adcp_error": { "code": "UNSUPPORTED_FEATURE", "message": message, "details": details, }, } ) if version is not None or losses: metadata = dict(result.metadata or {}) metadata[CONVERSION_METADATA_KEY] = {"wire_version": version, "losses": losses} if request.creative_dialect is not None: metadata[CONVERSION_METADATA_KEY]["creative_dialect"] = request.creative_dialect if request.identity_migrations: metadata[CONVERSION_METADATA_KEY]["account_identity_migration_pending"] = list( request.identity_migrations ) for migration in request.identity_migrations: logger.warning("Account identity migration pending at %s", migration["pointer"]) result = result.model_copy(update={"metadata": metadata}) if result.success and isinstance(version, str): body = result.data if isinstance(result.data, dict) else {} task_id = body.get("task_id") or (result.metadata or {}).get("task_id") if isinstance(task_id, str) and ( body.get("status") in {"submitted", "working", "input-required"} or result.status in {TaskStatus.SUBMITTED, TaskStatus.WORKING, TaskStatus.NEEDS_INPUT} ): context: dict[str, Any] = {"adcp_version": version} if request.payload.get("account") is not None: context["account"] = {} self._task_wire_contexts[(task_id, tool)] = ConversionResult( context, creative_dialect=request.creative_dialect ) if len(self._task_wire_contexts) > 1024: self._task_wire_contexts.pop(next(iter(self._task_wire_contexts))) return result def get_adcp_version(self) -> str: """Return the AdCP protocol release this client is pinned to. Resolved at construction from the ``adcp_version`` kwarg, with fallback to the SDK's compile-time pin (``ADCP_VERSION`` packaged with the wheel) when the caller didn't pin explicitly. Same value across the client's lifetime — the pin is per-instance, not per-call. See ``__init__``'s ``adcp_version`` parameter for the full semantics, including the cross-major fence and dialect selection. """ return self._adcp_version def get_server_version(self) -> str | None: """Return the seller's AdCP wire-shape version, or ``None``. ``None`` means the SDK is assuming a current-major seller (the default). Returns a release-precision string (``"3.0"``, ``"3.1"``, ``"2.5"``) when the adopter pinned via the ``server_version`` constructor arg or — once the agent-card probe lands — when the SDK detected the seller's version from its agent-card. See ``__init__``'s ``server_version`` parameter for negotiated canonical/legacy creative behavior. """ return self._server_version @property def context_id(self) -> str | None: """Current A2A conversation context_id. Reads the context_id currently associated with this client: the value assigned by the A2A server (auto-captured from the most recent response) or the one seeded via the constructor or ``reset_context()``. Returns ``None`` before the first A2A call in a fresh conversation, or for clients on non-A2A protocols — reads are lenient across protocols so generic code can probe ``if client.context_id: ...`` safely. Writes (constructor kwarg, ``reset_context``) raise on non-A2A because the operation has no meaning there. Not safe for concurrent calls on the same client — the adapter mutates this on every response. Rule of thumb: one ADCPClient per A2A conversation. For simple completed-task resume, persist this value and pass it to ``ADCPClient(context_id=...)``. For HITL flows that may restart mid-``input-required``, use ``checkpoint()`` / ``from_checkpoint()`` — full resume state is both this id AND ``active_task_id``. """ if isinstance(self.adapter, A2AAdapter): return self.adapter.context_id return None @property def active_task_id(self) -> str | None: """A2A task_id the next send must echo to resume the same task. Set when the last A2A response was non-terminal (``input-required``, ``working``, ``submitted``, ``auth-required``). The adapter echoes this id on the next outbound message so the server resumes the same task. Clears automatically when the task reaches a terminal state. Full resume state is *both* ``context_id`` and ``active_task_id`` — persist both (or use ``checkpoint()``) to survive a process restart mid-HITL without orphaning the task. Returns ``None`` for non-A2A clients. """ if isinstance(self.adapter, A2AAdapter): return self.adapter.active_task_id return None @property def a2a_protocol_versions(self) -> list[str] | None: """A2A ``protocol_version`` strings the peer advertises, sorted. Lazily populated after the first operation that fetches the peer's ``AgentCard`` (``fetch_capabilities``, ``list_tools``, ``get_agent_info``, or any skill-call). Returns ``None`` before the card has been fetched so callers can distinguish "not yet known" from "peer advertises nothing" (empty list). Returns ``None`` for non-A2A clients. Useful for probing which wire version a peer speaks — buyers running alongside both 0.3-era and 1.0-era agents can use this to confirm what they're talking to. """ if isinstance(self.adapter, A2AAdapter): return self.adapter.a2a_protocol_versions return None def reset_context(self, context_id: str | None = None) -> None: """Start a new A2A conversation on this client. Passing ``None`` (default) clears the current context so the server mints a fresh one on the next call. Passing a string uses it as the new conversation id — useful for resuming a specific prior session or for naming the conversation with your own correlation key. Note: some servers (notably ADK) rewrite client-supplied ids into their own session format; the client auto-adopts the rewritten id on the next response. Also clears any active_task_id — starting a new conversation discards any in-flight task on the old one. Raises ``TypeError`` when called on a non-A2A client. """ if not isinstance(self.adapter, A2AAdapter): raise TypeError( f"reset_context is only supported for A2A protocol; " f"got {self.agent_config.protocol}" ) self.adapter.set_context_id(context_id) def checkpoint(self) -> Checkpoint: """Return the minimal state needed to resume this A2A session. Full resume for HITL / multi-turn flows requires *both* ``context_id`` (which conversation) AND ``active_task_id`` (which in-flight task to echo). Persisting only ``context_id`` reconnects to the right conversation but orphans the pending task server-side — the next send starts a new task under the same context, and the original ``input-required`` task is abandoned. The returned dict also carries ``agent_id`` so a later ``from_checkpoint`` call against a different ``AgentConfig`` fails loudly instead of sending one agent's session ids to another. Pair with ``ADCPClient.from_checkpoint(agent_config, state)``. Returns a fully-populated ``Checkpoint`` on non-A2A clients with ``context_id``/``active_task_id`` set to ``None``, so generic persist-and-restore code can call this without branching on protocol. """ return Checkpoint( agent_id=self.agent_config.id, context_id=self.context_id, active_task_id=self.active_task_id, ) @classmethod def from_checkpoint( cls, agent_config: AgentConfig, state: Checkpoint, **kwargs: Any, ) -> ADCPClient: """Rehydrate an ADCPClient from a prior ``checkpoint()``. Restores both ``context_id`` and ``active_task_id`` so a process restart mid-``input-required`` can resume the same task, not orphan it. Accepts the same keyword arguments as ``__init__`` (signing, strict_idempotency, etc.) — the checkpoint only carries session-resume state; operational config is re-supplied by the caller. Raises ``ValueError`` if the checkpoint's ``agent_id`` doesn't match ``agent_config.id`` — a checkpoint minted for Agent A must not be restored onto Agent B, or the client will leak Agent A's opaque session ids to Agent B on the next message. Raises ``TypeError`` on a non-A2A ``agent_config`` if the checkpoint carries a non-empty ``context_id`` or ``active_task_id`` — session-resume state on a protocol that doesn't support it would be silently dropped, masking bugs. An empty/absent checkpoint round-trips cleanly on any protocol. """ saved_agent_id = state.get("agent_id") if state else None if saved_agent_id and saved_agent_id != agent_config.id: raise ValueError( f"checkpoint was minted for agent {saved_agent_id!r}, " f"cannot restore against {agent_config.id!r}" ) context_id = state.get("context_id") if state else None active_task_id = state.get("active_task_id") if state else None if active_task_id and agent_config.protocol != Protocol.A2A: raise TypeError( f"active_task_id in checkpoint is only supported for A2A " f"protocol; got {agent_config.protocol}" ) client = cls(agent_config, context_id=context_id, **kwargs) if active_task_id and isinstance(client.adapter, A2AAdapter): client.adapter._restore_active_task_id(active_task_id) return client @classmethod def from_mcp_client( cls, client: ClientSession, *, agent_id: str | None = None, validation: ValidationHookConfig | None = None, capabilities_ttl: float = 3600.0, validate_features: bool = False, strict_idempotency: bool = False, max_response_bytes: int | None = DEFAULT_MAX_RESPONSE_BYTES, ) -> ADCPClient: """Create an ADCPClient wrapping a pre-connected MCP ClientSession. Parity with JS ``AgentClient.fromMCPClient()`` (v5.19.0). The primary use case is compliance test fleets that wire a full ``ADCPClient`` against an in-process MCP server without standing up a loopback HTTP server. Warning: The returned client's ``close()`` and ``async with`` ``__aexit__`` are **no-ops** — the caller owns the injected session and is responsible for closing it. Code that relies on ``async with ADCPClient.from_mcp_client(...) as c:`` to clean up the session will leak the session. The **streaming** half of ``max_response_bytes`` does not apply: that budget is enforced in the transport under a client this SDK builds, and an injected session brings its own, so bounding bytes as they arrive is the caller's to do. The post-parse half does apply — an oversized ``content[].text`` item still raises :class:`~adcp.exceptions.ADCPResponseTooLargeError` before ``json.loads`` — and on this path it is the only bound there is. Set ``max_response_bytes`` here to raise or (with ``None``) remove it. Webhook delivery and ``on_activity`` callbacks are **not wired** on the in-process path — there is no HTTP transport for the seller to call back through. Don't pass these to the factory (they're absent from the signature on purpose). If the injected session has not been initialized (``await session.initialize()``), the first tool call surfaces as an opaque MCP protocol error in ``TaskResult.error``. The factory does not initialize for you — verify before calling. **Session lifecycle:** the caller owns the session — ``close()`` and ``async with`` exit on the returned client are no-ops. Use your own ``AsyncExitStack`` to scope both the transport and the client:: import contextlib from mcp import ClientSession from mcp.shared.memory import create_client_server_memory_streams async with contextlib.AsyncExitStack() as stack: (c_read, c_write), (s_read, s_write) = await stack.enter_async_context( create_client_server_memory_streams() ) # wire your in-process server to (s_read, s_write) here session = await stack.enter_async_context( ClientSession(c_read, c_write) ) await session.initialize() # close() is a no-op on injected sessions; no stack.enter_async_context needed. adcp_client = ADCPClient.from_mcp_client(session, agent_id="test-seller") result = await adcp_client.get_products(GetProductsRequest(...)) Note: Request signing is not supported on the injected-session path — the signing hook is wired into the HTTP transport layer that is bypassed here. ``signing=`` is intentionally absent from this factory's parameters. Args: client: A pre-connected ``mcp.ClientSession`` whose ``initialize()`` has already been awaited. agent_id: Identifier for the wrapped agent used in log messages and error objects. Defaults to a unique ``in-process-XXXXXXXX`` token; set this explicitly when running multiple in-process agents concurrently so log lines are distinguishable. validation: Schema-validation modes (same as ``__init__``). strict_idempotency: Verify seller declared idempotency support before each mutating call (same as ``__init__``). validate_features: Gate tool calls on fetched capability declarations (same as ``__init__``). capabilities_ttl: TTL for the capability cache in seconds (same as ``__init__``). max_response_bytes: Budget for the ``content[].text`` extraction bound, the only response-size bound that applies to an injected session. ``None`` removes it. Returns: A fully configured ``ADCPClient`` backed by the injected session. """ effective_id = agent_id if agent_id is not None else f"in-process-{uuid4().hex[:8]}" config = AgentConfig( id=effective_id, # RFC 2606 .invalid TLD — passes the http:// validator, guaranteed # not to route to a real host. Self-documenting in error messages. agent_uri="http://in-process.invalid", protocol=Protocol.MCP, max_response_bytes=max_response_bytes, ) instance = cls( config, validation=validation, strict_idempotency=strict_idempotency, validate_features=validate_features, capabilities_ttl=capabilities_ttl, ) if not isinstance(instance.adapter, MCPAdapter): raise RuntimeError( # pragma: no cover f"from_mcp_client: expected MCPAdapter but got {type(instance.adapter).__name__}" ) instance.adapter._inject_session(client) return instance async def _ensure_idempotency_capability(self) -> None: """Verify the seller positively declares idempotency support in capabilities. Called before every mutating request when ``strict_idempotency=True``. Fetches capabilities on first invocation; subsequent calls are no-ops once the declaration has been observed. Raises ``IdempotencyUnsupportedError`` when ``adcp.idempotency`` is missing, declares ``supported=False`` (seller does not dedupe — naive retry would double-process), or declares ``supported=True`` without a ``replay_ttl_seconds`` window. Sets ``_idempotency_capability_verified = True`` BEFORE calling ``fetch_capabilities`` so any recursive dispatch through the adapter terminates (``get_adcp_capabilities`` is non-mutating, so it would short-circuit anyway — but this guard protects against future refactors that might add it to the mutating set). """ from adcp.exceptions import IdempotencyUnsupportedError if self._idempotency_capability_verified: return self._idempotency_capability_verified = True try: caps = await self.fetch_capabilities() adcp_info = getattr(caps, "adcp", None) idempotency_info = getattr(adcp_info, "idempotency", None) if adcp_info else None if idempotency_info is None: raise IdempotencyUnsupportedError( agent_id=self.agent_config.id, agent_uri=self.agent_config.agent_uri, reason="seller did not declare adcp.idempotency", ) supported = getattr(idempotency_info, "supported", None) if supported is False: raise IdempotencyUnsupportedError( agent_id=self.agent_config.id, agent_uri=self.agent_config.agent_uri, reason="seller declared adcp.idempotency.supported=false", ) ttl = getattr(idempotency_info, "replay_ttl_seconds", None) if ttl is None: raise IdempotencyUnsupportedError( agent_id=self.agent_config.id, agent_uri=self.agent_config.agent_uri, reason=( "seller declared adcp.idempotency.supported=true but omitted " "replay_ttl_seconds" ), ) except BaseException: self._idempotency_capability_verified = False raise async def _prepare_signing_capabilities(self) -> None: """Populate signing policy before a transport writer sends a request.""" await self.fetch_capabilities() async def _inject_outgoing_trace_context(self, request: httpx.Request) -> None: """Inject trace context into tool requests, excluding discovery traffic.""" try: payload = json.loads(request.content) except (json.JSONDecodeError, TypeError, UnicodeDecodeError): payload = None bridged_headers = mcp_trace_headers_from_payload(payload) if bridged_headers: set_request_trace_headers(request, bridged_headers) return mcp_operation = self._mcp_operation_from_request(request) operation = mcp_operation or _signing_current_operation.get() if operation is None: return inject_trace_context(request) @staticmethod def _mcp_operation_from_request(request: httpx.Request) -> str | None: """Extract one MCP ``tools/call`` name from its JSON-RPC body.""" try: payload = json.loads(request.content) except (json.JSONDecodeError, TypeError, UnicodeDecodeError): return None if not isinstance(payload, dict) or payload.get("method") != "tools/call": return None params = payload.get("params") if not isinstance(params, dict): return None name = params.get("name") return name if isinstance(name, str) and name else None async def _sign_outgoing_request(self, request: httpx.Request) -> None: """httpx request event hook that attaches RFC 9421 signature headers. Installed on the protocol adapter's httpx client when a ``SigningConfig`` was passed to ``ADCPClient``. Consults the seller's advertised ``request_signing`` capability and signs only the operations the seller listed in ``required_f