-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathhandler.py
More file actions
2389 lines (2210 loc) · 98.1 KB
/
Copy pathhandler.py
File metadata and controls
2389 lines (2210 loc) · 98.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""``PlatformHandler`` — wire-shape shims that route to a DecisioningPlatform.
This module is the codegen target — ``scripts/generate_decisioning_handler.py``
will (in a follow-up PR) emit this file by walking the per-specialism
Protocols. For v6.0 alpha foundation, the file is hand-written; the
codegen drift test ships in Stage 4.
Each shim:
1. Accepts the typed Pydantic request + framework :class:`ToolContext`.
2. Resolves the account via ``platform.accounts.resolve``.
3. Builds the typed :class:`RequestContext` via
:func:`_build_request_context` (D2 + D9 + D15).
4. Calls :func:`_invoke_platform_method` to invoke the platform method,
which projects ``TaskHandoff`` and wraps non-``AdcpError`` exceptions
to the wire envelope.
5. Returns whatever the platform method returned — typed Pydantic
response, plain dict matching the wire shape, or the ``Submitted``
envelope dict from a TaskHandoff projection. The ``cast()`` on each
shim is a static-typing hint for callers; it is NOT a runtime
validation pass. The framework's transport layer
(``adcp.server.serve``) handles wire serialization for both Pydantic
and dict returns. Adopters relying on Pydantic round-trip validation
can opt in via ``response_validator`` middleware.
The class-level ``advertised_tools: ClassVar[set[str]]`` declaration is
auto-registered with the framework's tool-discovery seam via
:meth:`adcp.server.base.ADCPHandler.__init_subclass__` (PR #318). Adopters
get a focused ``tools/list`` filter without manual registration.
"""
from __future__ import annotations
import asyncio
import inspect
import logging
import warnings
from collections.abc import Awaitable, Callable
from typing import TYPE_CHECKING, Any, ClassVar, cast
from adcp.decisioning._get_products_helpers import _project_product_fields
from adcp.decisioning.context import AuthInfo
from adcp.decisioning.dispatch import (
_build_request_context,
_invoke_platform_method,
)
from adcp.decisioning.implementation_config import ProductConfigStore
from adcp.decisioning.pagination import _query_hash, apply_framework_pagination
from adcp.decisioning.property_list import (
maybe_apply_property_list_filter,
property_list_capability_enabled,
)
from adcp.decisioning.proposal_dispatch import (
mark_proposal_consumed,
maybe_hydrate_recipes_for_create_media_buy,
maybe_hydrate_recipes_for_media_buy_id,
maybe_intercept_finalize,
maybe_persist_draft_after_get_products,
release_proposal_reservation,
)
from adcp.decisioning.refine import (
RefineResult,
assert_buying_mode_consistent,
has_refine_support,
project_refine_response,
)
from adcp.decisioning.time_budget import project_incomplete_response, resolve_time_budget
from adcp.decisioning.webhook_emit import maybe_emit_sync_completion
from adcp.server.base import ADCPHandler, ToolContext
logger = logging.getLogger(__name__)
# Pydantic Request/Response types are imported at module scope (NOT
# under TYPE_CHECKING) so that ``typing.get_type_hints(method)`` can
# resolve every shim's ``params`` annotation at runtime. The dispatcher
# at ``adcp.server.mcp_tools._resolve_params_pydantic_model`` walks
# these hints to deserialise wire-shape dicts into the typed Pydantic
# models the shims expect; without runtime visibility, ``get_type_hints``
# raises ``NameError`` on the forward refs (the file uses
# ``from __future__ import annotations``), the resolver swallows the
# exception, and the dispatcher falls back to the dict path — which
# crashes inside the shim with ``'dict' object has no attribute
# 'account'`` (Emma sales-direct backend test, verdict 2/10).
from adcp.types import (
AccountReference,
AcquireRightsRequest,
AcquireRightsResponse,
ActivateSignalRequest,
ActivateSignalSuccessResponse,
BuildCreativeRequest,
BuildCreativeResponse,
CalibrateContentRequest,
CalibrateContentResponse,
CheckGovernanceRequest,
CheckGovernanceResponse,
CreateCollectionListRequest,
CreateCollectionListResponse,
CreateContentStandardsRequest,
CreateContentStandardsResponse,
CreateMediaBuyRequest,
CreateMediaBuyResponse,
CreatePropertyListRequest,
CreatePropertyListResponse,
DeleteCollectionListRequest,
DeleteCollectionListResponse,
DeletePropertyListRequest,
DeletePropertyListResponse,
GetBrandIdentityRequest,
GetBrandIdentitySuccessResponse,
GetCollectionListRequest,
GetCollectionListResponse,
GetContentStandardsRequest,
GetContentStandardsResponse,
GetCreativeDeliveryRequest,
GetCreativeDeliveryResponse,
GetCreativeFeaturesRequest,
GetCreativeFeaturesResponse,
GetMediaBuyArtifactsRequest,
GetMediaBuyArtifactsResponse,
GetMediaBuyDeliveryRequest,
GetMediaBuyDeliveryResponse,
GetMediaBuysRequest,
GetMediaBuysResponse,
GetPlanAuditLogsRequest,
GetPlanAuditLogsResponse,
GetProductsRequest,
GetProductsResponse,
GetPropertyListRequest,
GetPropertyListResponse,
GetRightsRequest,
GetRightsSuccessResponse,
GetSignalsRequest,
GetSignalsResponse,
ListCollectionListsRequest,
ListCollectionListsResponse,
ListContentStandardsRequest,
ListContentStandardsResponse,
ListCreativeFormatsRequest,
ListCreativeFormatsResponse,
ListCreativesRequest,
ListCreativesResponse,
ListPropertyListsRequest,
ListPropertyListsResponse,
PreviewCreativeRequest,
PreviewCreativeResponse,
ProvidePerformanceFeedbackRequest,
ProvidePerformanceFeedbackResponse,
ReportPlanOutcomeRequest,
ReportPlanOutcomeResponse,
SyncAudiencesRequest,
SyncAudiencesSuccessResponse,
SyncCreativesRequest,
SyncCreativesSuccessResponse,
SyncPlansRequest,
SyncPlansResponse,
UpdateCollectionListRequest,
UpdateCollectionListResponse,
UpdateContentStandardsRequest,
UpdateContentStandardsResponse,
UpdateMediaBuyRequest,
UpdateMediaBuySuccessResponse,
UpdatePropertyListRequest,
UpdatePropertyListResponse,
UpdateRightsRequest,
UpdateRightsResponse,
ValidateContentDeliveryRequest,
ValidateContentDeliveryResponse,
)
if TYPE_CHECKING:
from concurrent.futures import ThreadPoolExecutor
from adcp.decisioning.platform import DecisioningPlatform
from adcp.decisioning.property_list import PropertyListFetcher
from adcp.decisioning.registry import BuyerAgent, BuyerAgentRegistry
from adcp.decisioning.resolve import ResourceResolver
from adcp.decisioning.state import StateReader
from adcp.decisioning.task_registry import TaskRegistry
from adcp.decisioning.types import Account
from adcp.webhook_sender import WebhookSender
from adcp.webhook_supervisor import WebhookDeliverySupervisor
# ---------------------------------------------------------------------------
# Class-level advertised tool surface
# ---------------------------------------------------------------------------
#: All wire tools the PlatformHandler shim covers. Each Protocol family
#: contributes its required + optional methods. The framework's
#: ``tools/list`` filters to this set; adopters get only the tools their
#: claimed specialism Protocols cover, plus the framework's
#: ``_is_method_overridden`` filter drops shims whose platform method
#: isn't implemented (sales-only adopters don't accidentally advertise
#: ``build_creative``).
_SALES_ADVERTISED_TOOLS: frozenset[str] = frozenset(
{
"get_products",
"create_media_buy",
"update_media_buy",
"sync_creatives",
"get_media_buy_delivery",
"get_media_buys",
"provide_performance_feedback",
"list_creative_formats",
"list_creatives",
}
)
_CREATIVE_ADVERTISED_TOOLS: frozenset[str] = frozenset(
{
"build_creative",
"preview_creative",
"get_creative_delivery",
}
)
_SIGNALS_ADVERTISED_TOOLS: frozenset[str] = frozenset(
{
"get_signals",
"activate_signal",
}
)
_AUDIENCE_ADVERTISED_TOOLS: frozenset[str] = frozenset(
{
"sync_audiences",
}
)
_GOVERNANCE_ADVERTISED_TOOLS: frozenset[str] = frozenset(
{
"check_governance",
"sync_plans",
"report_plan_outcome",
"get_plan_audit_logs",
}
)
_BRAND_RIGHTS_ADVERTISED_TOOLS: frozenset[str] = frozenset(
{
"get_brand_identity",
"get_rights",
"acquire_rights",
"update_rights",
}
)
_CONTENT_STANDARDS_ADVERTISED_TOOLS: frozenset[str] = frozenset(
{
"list_content_standards",
"get_content_standards",
"create_content_standards",
"update_content_standards",
"calibrate_content",
"validate_content_delivery",
"get_media_buy_artifacts",
"get_creative_features",
}
)
_PROPERTY_LISTS_ADVERTISED_TOOLS: frozenset[str] = frozenset(
{
"create_property_list",
"update_property_list",
"get_property_list",
"list_property_lists",
"delete_property_list",
}
)
_COLLECTION_LISTS_ADVERTISED_TOOLS: frozenset[str] = frozenset(
{
"create_collection_list",
"update_collection_list",
"get_collection_list",
"list_collection_lists",
"delete_collection_list",
}
)
#: Methods adopters MAY leave unimplemented per their Protocol. The shim
#: surfaces ``AdcpError(code='UNSUPPORTED_FEATURE')`` to buyers calling
#: an unimplemented optional method instead of leaking AttributeError.
#: Required methods (per ``REQUIRED_METHODS_PER_SPECIALISM``) are
#: enforced at server boot by ``validate_platform`` — the optional set
#: complements that gate at runtime.
_OPTIONAL_PLATFORM_METHODS: frozenset[str] = frozenset(
{
# Sales-* optional (gated by claim, not method presence)
"get_media_buys",
"provide_performance_feedback",
"list_creative_formats",
"list_creatives",
# CreativeBuilderPlatform optional
"preview_creative",
# ContentStandardsPlatform optional analyzer reads
"get_media_buy_artifacts",
"get_creative_features",
# AudiencePlatform adopter-internal helper (not wire-served, but
# listed here for symmetry should a future shim wire it)
"poll_audience_statuses",
}
)
#: Map each spec specialism slug to the tools that specialism's Protocol
#: serves on the wire. Used by :meth:`PlatformHandler.advertised_tools_for_instance`
#: to filter ``tools/list`` to ONLY the tools the platform's claimed
#: specialisms are responsible for — without this filter, a sales-only
#: adopter would see all 40+ shims advertised (Emma cross-cutting P1
#: confirmed by 3 of 3 backend tests).
#:
#: Keys MUST be drawn from
#: :data:`adcp.decisioning.dispatch.SPEC_SPECIALISM_ENUM`. Slugs not in
#: this map (``signed-requests``, ``governance-aware-seller``) are
#: meta-claims that don't expose tools directly; they compose with
#: another specialism that does.
SPECIALISM_TO_ADVERTISED_TOOLS: dict[str, frozenset[str]] = {
# Sales-* archetypes — all use the unified SalesPlatform surface.
"sales-non-guaranteed": _SALES_ADVERTISED_TOOLS,
"sales-guaranteed": _SALES_ADVERTISED_TOOLS,
"sales-broadcast-tv": _SALES_ADVERTISED_TOOLS,
"sales-social": _SALES_ADVERTISED_TOOLS,
"sales-catalog-driven": _SALES_ADVERTISED_TOOLS,
"sales-proposal-mode": _SALES_ADVERTISED_TOOLS,
# Creative — Builder + AdServer. Builder claims expose
# build_creative + optional preview_creative; AdServer adds
# get_creative_delivery (per CreativeAdServerPlatform Protocol).
# Both share the same advertised set; the per-method override
# filter (``_is_method_overridden``) drops unimplemented optionals.
"creative-generative": _CREATIVE_ADVERTISED_TOOLS,
"creative-template": _CREATIVE_ADVERTISED_TOOLS,
"creative-ad-server": _CREATIVE_ADVERTISED_TOOLS,
# Signals — marketplace + owned share the same wire surface.
"signal-marketplace": _SIGNALS_ADVERTISED_TOOLS,
"signal-owned": _SIGNALS_ADVERTISED_TOOLS,
# Audience.
"audience-sync": _AUDIENCE_ADVERTISED_TOOLS,
# Governance — spend-authority + delivery-monitor share the
# CampaignGovernancePlatform Protocol surface.
"governance-spend-authority": _GOVERNANCE_ADVERTISED_TOOLS,
"governance-delivery-monitor": _GOVERNANCE_ADVERTISED_TOOLS,
# Brand rights, content standards, lists — one slug per Protocol.
"brand-rights": _BRAND_RIGHTS_ADVERTISED_TOOLS,
"content-standards": _CONTENT_STANDARDS_ADVERTISED_TOOLS,
"property-lists": _PROPERTY_LISTS_ADVERTISED_TOOLS,
"collection-lists": _COLLECTION_LISTS_ADVERTISED_TOOLS,
}
#: Map each spec specialism slug to the wire-protocol values it
#: contributes to ``supported_protocols`` on the
#: ``get_adcp_capabilities`` response. Source of truth is the
#: ``supported_protocols`` enum in
#: ``schemas/cache/protocol/get-adcp-capabilities-response.json``
#: (``media_buy | signals | governance | sponsored_intelligence |
#: creative | brand``). Composes with
#: :data:`SPECIALISM_TO_ADVERTISED_TOOLS` — a specialism whose tools
#: cross protocol boundaries (e.g. ``audience-sync`` exposes
#: ``sync_audiences``, a media_buy tool) declares the relevant set
#: explicitly here.
#:
#: Specialisms that are pure meta-claims (``governance-aware-seller``,
#: ``signed-requests``) contribute no protocol — they compose with a
#: non-meta specialism that does.
SPECIALISM_TO_PROTOCOLS: dict[str, frozenset[str]] = {
# Sales-* archetypes — all live under the media_buy protocol.
"sales-non-guaranteed": frozenset({"media_buy"}),
"sales-guaranteed": frozenset({"media_buy"}),
"sales-broadcast-tv": frozenset({"media_buy"}),
"sales-social": frozenset({"media_buy"}),
"sales-catalog-driven": frozenset({"media_buy"}),
"sales-proposal-mode": frozenset({"media_buy"}),
# Creative — generative / template / ad-server all expose creative
# tools; the ad-server variant additionally exposes
# ``get_creative_delivery`` which is a media_buy companion read,
# but the wire protocol is still ``creative``.
"creative-generative": frozenset({"creative"}),
"creative-template": frozenset({"creative"}),
"creative-ad-server": frozenset({"creative"}),
# Signals.
"signal-marketplace": frozenset({"signals"}),
"signal-owned": frozenset({"signals"}),
# Audience-sync's ``sync_audiences`` is a media_buy tool.
"audience-sync": frozenset({"media_buy"}),
# Governance.
"governance-spend-authority": frozenset({"governance"}),
"governance-delivery-monitor": frozenset({"governance"}),
# Brand-rights → brand protocol.
"brand-rights": frozenset({"brand"}),
# Content-standards / lists are governance-protocol tools per
# ``HANDLER_TO_DOMAIN`` in ``adcp.server.builder``.
"content-standards": frozenset({"governance"}),
"property-lists": frozenset({"governance"}),
"collection-lists": frozenset({"governance"}),
}
async def _resolve_buyer_agent(
registry: BuyerAgentRegistry,
auth_info: AuthInfo | None,
) -> BuyerAgent:
"""Resolve a :class:`BuyerAgent` from a wired registry.
The framework's commercial-identity gate. Runs before
:meth:`AccountStore.resolve` so a suspended / blocked / unknown
agent is rejected with the correct structured error code instead
of the rejection leaking into the account-resolution path as a
confused ``ACCOUNT_NOT_FOUND``.
Dispatches by credential kind:
* :class:`HttpSigCredential` →
:meth:`BuyerAgentRegistry.resolve_by_agent_url` with the
cryptographically-verified ``agent_url``.
* :class:`ApiKeyCredential` / :class:`OAuthCredential` →
:meth:`BuyerAgentRegistry.resolve_by_credential`.
* No credential at all (unauthenticated dev fixture, ``derived``
auth) → ``PERMISSION_DENIED`` (no ``details.scope``). Adopters
running a registry have implicitly opted out of unauthenticated
traffic.
All four denial paths surface as ``code="PERMISSION_DENIED"`` to
match the spec enum and prevent the cross-tenant onboarding-oracle
risk: an attacker watching the wire MUST NOT be able to
distinguish "this agent_url is unrecognized at this seller" from
"this agent_url is recognized but currently denied". The
discriminator is in ``details``:
* recognized + suspended →
``details = {scope: "agent", status: "suspended", agent_url: ...}``
* recognized + blocked →
``details = {scope: "agent", status: "blocked", agent_url: ...}``
* unrecognized (registry miss / no credential / unknown status) →
``details`` OMITTED — scope MUST NOT be set on the unestablished-
identity path (omit-on-unestablished-identity rule).
Note on parity: the *latency / headers / side-effects* parity
contract between the recognized and unrecognized paths is tracked
as a follow-up — the eager-raise pattern below still completes the
unrecognized path on a different code path than the recognized
one. Renaming closes the wire-code mismatch; folding all four
paths through a common emit point with deliberate latency padding
and identical audit/metric side-effects is the next step.
:raises AdcpError: ``PERMISSION_DENIED`` (all four denial paths).
Recovery is ``correctable`` per the spec's ``enumMetadata``
for ``PERMISSION_DENIED``. The wire-level recovery hint is
independent of the resolution channel: the buyer cannot
auto-retry a commercial-identity rejection, but the
``details.scope == "agent"`` discriminator (when present) is
the signal callers surface to a human operator rather than
loop on the request.
"""
from adcp.decisioning.registry import (
ApiKeyCredential,
HttpSigCredential,
OAuthCredential,
)
from adcp.decisioning.types import AdcpError
credential = auth_info.credential if auth_info is not None else None
agent: BuyerAgent | None = None
if credential is not None:
if isinstance(credential, HttpSigCredential):
agent = await registry.resolve_by_agent_url(credential.agent_url)
elif isinstance(credential, (ApiKeyCredential, OAuthCredential)):
agent = await registry.resolve_by_credential(credential)
else:
# Defensive: a future Credential variant lands and the
# dispatch path doesn't know how to route it. Fail closed
# with INTERNAL_ERROR rather than silently passing the
# request through (which would skip the registry gate
# entirely and leak the upgrade footgun into production).
raise AdcpError(
"INTERNAL_ERROR",
message=(
f"BuyerAgentRegistry dispatch received an unknown "
f"Credential variant {type(credential).__name__!r}. "
"The framework's resolver doesn't know which registry "
"method to call. Update _resolve_buyer_agent in "
"adcp.decisioning.handler to dispatch the new variant."
),
recovery="terminal",
)
# Generic message used on every denial path — MUST be identical
# across the unrecognized and the recognized-but-denied paths so
# the wire-level error.message is not itself a side channel
# leaking which agent_urls are onboarded with which sellers. The
# discriminator (when present at all) is in details, only on the
# recognized-but-denied paths.
_denied_message = (
"Buyer agent is not authorized for this seller. The seller's "
"commercial allowlist did not authorize this credential. "
"Resolve out-of-band via the seller's onboarding contact; this "
"is not a request-side error the buyer can correct."
)
if agent is None:
# Registry miss / no credential. ``details`` is OMITTED — the
# spec's omit-on-unestablished-identity rule says the
# unrecognized-agent path MUST be indistinguishable on the
# wire from the recognized-but-denied path, and ``scope``
# would itself be the discriminator.
raise AdcpError(
"PERMISSION_DENIED",
message=_denied_message,
recovery="correctable",
)
if agent.status == "active":
return agent
if agent.status == "suspended":
raise AdcpError(
"PERMISSION_DENIED",
message=_denied_message,
recovery="correctable",
details={
"scope": "agent",
"status": "suspended",
"agent_url": agent.agent_url,
},
)
if agent.status == "blocked":
raise AdcpError(
"PERMISSION_DENIED",
message=_denied_message,
recovery="correctable",
details={
"scope": "agent",
"status": "blocked",
"agent_url": agent.agent_url,
},
)
# Default-reject any non-active status the framework doesn't
# recognize (typo, future enum value, adopter-custom string). A
# silent fall-through to "active" would leak commercial state
# past the gate. ``details`` is OMITTED for the same reason as
# the registry-miss branch — the framework treats unknown statuses
# as the unrecognized-identity path (the row is in the registry
# but the framework cannot interpret it, which is operationally
# equivalent to "not authorized" without a defensible status
# claim to project on the wire).
raise AdcpError(
"PERMISSION_DENIED",
message=_denied_message,
recovery="correctable",
)
def _project_build_creative(result: Any) -> Any:
"""Project the adopter's ``build_creative`` return into the wire
envelope shape.
The :class:`CreativeBuilderPlatform.build_creative` Protocol
declares the return as ``CreativeManifest | Sequence[CreativeManifest]
| BuildCreativeSuccessResponse`` — three ergonomic arms. The wire
envelope per ``schemas/cache/media-buy/build-creative-response.json``
has only two success arms: ``{creative_manifest: ...}`` (single)
or ``{creative_manifests: [...]}`` (multi). This helper wraps the
bare-manifest and list cases.
Mirrors the JS-side ``projectBuildCreativeReturn`` at
``src/lib/server/decisioning/runtime/from-platform.ts``. Without
this, an adopter returning a bare :class:`CreativeManifest` (which
the Protocol explicitly allows) would ship an unwrapped object that
fails wire ``oneOf`` validation downstream.
"""
# Already an envelope (has the wire field present).
if hasattr(result, "creative_manifest") or hasattr(result, "creative_manifests"):
return result
if isinstance(result, dict) and (
"creative_manifest" in result or "creative_manifests" in result
):
return result
# Sequence of manifests → multi-success envelope.
if isinstance(result, list):
return {
"creative_manifests": [
m.model_dump(mode="json") if hasattr(m, "model_dump") else m for m in result
]
}
# Bare CreativeManifest → single-success envelope.
if hasattr(result, "model_dump"):
return {"creative_manifest": result.model_dump(mode="json")}
# Unknown shape — pass through and let wire validation surface.
return result
def _project_sync_audiences(result: Any) -> Any:
"""Project the adopter's ``sync_audiences`` return into the wire
envelope shape.
The :class:`AudiencePlatform.sync_audiences` Protocol allows
adopters to return either a list of audience-result rows (the
JS-side ergonomic) or a fully-shaped
:class:`SyncAudiencesSuccessResponse`. The wire envelope per
``schemas/cache/media-buy/sync-audiences-response.json`` is
``{audiences: [rows]}``. This helper wraps the list case.
Mirrors the JS-side response wrapping at
``src/lib/server/decisioning/runtime/from-platform.ts:2242-2249``.
"""
if isinstance(result, list):
return {
"audiences": [
r.model_dump(mode="json") if hasattr(r, "model_dump") else r for r in result
]
}
return result
def _method_accepts_configs(platform: Any, method_name: str) -> bool:
"""Return True when the platform's ``method_name`` declares a ``configs`` parameter."""
method = getattr(platform, method_name, None)
if method is None:
return False
try:
sig = inspect.signature(method)
return "configs" in sig.parameters
except (ValueError, TypeError):
return False
def _extract_media_buy_id(result: Any) -> str | None:
"""Pull ``media_buy_id`` off a ``create_media_buy`` return — handles
Pydantic models, plain dicts, and the ``Submitted`` envelope shape.
Returns ``None`` for handoff returns (no media_buy_id yet) or when
the field is missing — the caller skips ``mark_consumed`` in that
case and the proposal stays in ``COMMITTED`` state until a
subsequent successful create_media_buy hits the same ID.
"""
if result is None:
return None
if isinstance(result, dict):
# Submitted envelope path doesn't carry media_buy_id; the
# standard success shape does.
if result.get("status") == "submitted":
return None
value = result.get("media_buy_id")
else:
value = getattr(result, "media_buy_id", None)
if value is None:
return None
return str(value)
class PlatformHandler(ADCPHandler[ToolContext]):
"""ADCPHandler subclass that routes wire requests to a
:class:`DecisioningPlatform` via :func:`_invoke_platform_method`.
Constructed by :func:`adcp.decisioning.serve.create_adcp_server_from_platform`
— adopters never instantiate directly. The handler holds:
* ``platform`` — the adopter's :class:`DecisioningPlatform` subclass
instance. Method dispatches read/call this.
* ``executor`` — the framework-allocated thread-pool for sync platform
methods (D5).
* ``registry`` — the :class:`TaskRegistry` for handoff lifecycle.
* Optional ``state_reader`` / ``resource_resolver`` — Stage-3+ wiring
for v6.1 backing-store impls; defaults to the v6.0 stubs.
Per-method shims follow the same template:
1. Extract ``account_ref`` from the typed request (when the tool
carries ``account`` on the wire).
2. Resolve via ``platform.accounts.resolve(ref, auth_info=...)``.
3. Build :class:`RequestContext` via :func:`_build_request_context`.
4. Invoke the platform method via :func:`_invoke_platform_method`.
Adopters who don't override a given platform method get the framework's
``not_supported`` baseline (per ADCPHandler) on those tools — and the
override-detection filter drops the tool from ``tools/list`` unless
they pass ``advertise_all=True``.
"""
#: Class-level union of every tool the shim CAN serve. Used by the
#: framework's ``__init_subclass__`` registration so the class shows
#: up in :data:`adcp.server.mcp_tools._HANDLER_TOOLS`. The actual
#: per-instance advertisement is computed by
#: :meth:`advertised_tools_for_instance` from the platform's claimed
#: specialisms — without that intersection, a sales-only adopter
#: would advertise all 40+ shims (Emma cross-cutting P1).
advertised_tools: ClassVar[set[str]] = (
set(_SALES_ADVERTISED_TOOLS)
| set(_CREATIVE_ADVERTISED_TOOLS)
| set(_SIGNALS_ADVERTISED_TOOLS)
| set(_AUDIENCE_ADVERTISED_TOOLS)
| set(_GOVERNANCE_ADVERTISED_TOOLS)
| set(_BRAND_RIGHTS_ADVERTISED_TOOLS)
| set(_CONTENT_STANDARDS_ADVERTISED_TOOLS)
| set(_PROPERTY_LISTS_ADVERTISED_TOOLS)
| set(_COLLECTION_LISTS_ADVERTISED_TOOLS)
)
_agent_type = "decisioning platform"
def advertised_tools_for_instance(self) -> frozenset[str]:
"""Tools this handler advertises GIVEN ITS PLATFORM'S CLAIMED
SPECIALISMS.
Without this hook, ``get_tools_for_handler`` walks the class's
MRO + ``_is_method_overridden`` filter — both keyed on
``PlatformHandler``, which defines all 40+ shims as concrete
methods. Result: a sales-only adopter advertises
``acquire_rights``, ``build_creative``, every signals/audience
tool, etc. Buyers see a giant menu of tools that 501 on call;
Emma sales/creative/signals backend tests all flagged this as
P1 ("advertising 42 of 42 tools").
Per-instance advertisement intersects the universe of shim
coverage with what the platform's claimed specialisms are
responsible for via :data:`SPECIALISM_TO_ADVERTISED_TOOLS`.
Specialisms not in that map (``signed-requests``,
``governance-aware-seller``) are meta-claims and contribute no
tools — they compose with a non-meta claim that does.
:returns: The intersection of ``advertised_tools`` (universe)
with the per-specialism-allowed set. Empty when no
recognized specialisms are claimed (e.g., adopter still
piloting a novel slug not in the spec enum); transport
layer should fall back to the class-level set in that case
so the handler isn't accidentally muted.
"""
claimed = self._platform.capabilities.specialisms
serving: set[str] = set()
for entry in claimed:
# ``specialisms`` is ``list[Specialism | str]`` — spec-known
# entries are coerced to enum by ``__post_init__``; novel /
# pre-spec slugs pass through as strings.
slug = entry.value if hasattr(entry, "value") else entry
tools = SPECIALISM_TO_ADVERTISED_TOOLS.get(slug)
if tools is not None:
serving |= set(tools)
return frozenset(serving)
def get_advertised_tools(self, *, advertise_all: bool | None = None) -> frozenset[str]:
"""Names ``tools/list`` will return when this handler is served.
The class-level :attr:`advertised_tools` set is the *universe*
of tools the handler base supports across all specialisms (~50
entries on :class:`PlatformHandler`). What buyers actually see
on the wire is narrower:
1. Per-instance specialism filter — :meth:`advertised_tools_for_instance`
intersects the universe with the platform's claimed
specialisms (a sales-only adopter drops audience/governance
tools).
2. Override-detection filter — tools whose handler method is
still the SDK's ``not_supported`` default are dropped
(``advertise_all=False``, the spec-aligned default).
This method runs the same pipeline :func:`adcp.server.serve`
runs at boot, so adopters can inspect the effective set without
standing up a network port. The default ``advertise_all`` value
is whatever was configured on
:func:`adcp.decisioning.create_adcp_server_from_platform`
(``False`` when not set).
:param advertise_all: Override the configured value for this
call. ``True`` returns the per-specialism set without the
override filter; ``False`` applies the full filter.
:returns: Frozen set of tool names.
"""
from adcp.server.mcp_tools import get_tools_for_handler
effective = self._advertise_all if advertise_all is None else advertise_all
return frozenset(
tool["name"] for tool in get_tools_for_handler(self, advertise_all=effective)
)
def __init__(
self,
platform: DecisioningPlatform,
*,
executor: ThreadPoolExecutor,
registry: TaskRegistry,
state_reader: StateReader | None = None,
resource_resolver: ResourceResolver | None = None,
webhook_sender: WebhookSender | None = None,
webhook_supervisor: WebhookDeliverySupervisor | None = None,
auto_emit_completion_webhooks: bool = True,
buyer_agent_registry: BuyerAgentRegistry | None = None,
config_store: ProductConfigStore | None = None,
property_list_fetcher: PropertyListFetcher | None = None,
advertise_all: bool = False,
) -> None:
super().__init__()
self._platform = platform
self._executor = executor
self._registry = registry
self._state_reader = state_reader
self._resource_resolver = resource_resolver
self._webhook_sender = webhook_sender
self._webhook_supervisor = webhook_supervisor
self._auto_emit_completion_webhooks = auto_emit_completion_webhooks
self._buyer_agent_registry = buyer_agent_registry
self._config_store = config_store
self._property_list_fetcher = property_list_fetcher
self._advertise_all = advertise_all
# Cache whether the platform's create_media_buy accepts 'configs'
# so we only pay the inspect.signature cost at construction time.
self._create_media_buy_accepts_configs = _method_accepts_configs(
platform, "create_media_buy"
)
if config_store is None and self._create_media_buy_accepts_configs:
warnings.warn(
"create_media_buy declares a 'configs' parameter but no "
"ProductConfigStore was wired — the framework will inject "
"configs={} (empty dict) on every call. Wire a store via "
"config_store= in create_adcp_server_from_platform to enable "
"automatic implementation_config lookup.",
UserWarning,
stacklevel=2,
)
# ----- account resolution helper -----
async def _resolve_account(
self,
ref: AccountReference | None,
ctx: ToolContext,
) -> Account[Any]:
"""Resolve a wire :class:`AccountReference` to a typed
:class:`Account` via the platform's :class:`AccountStore`.
Pulls auth info from ``ctx.metadata['auth_info']`` when the
operator's ``context_factory`` populates it; otherwise None.
Adopter ``AccountStore`` impls handle missing-auth cases per
their own resolution mode (``'derived'`` tolerates None;
``'implicit'`` raises ``AUTH_INVALID``; ``'explicit'`` resolves
by ref).
``AccountStore.resolve`` takes a dict — convert the typed
Pydantic ``AccountReference`` via ``model_dump()`` so adopter
store impls see a normalized shape.
When a :class:`adcp.decisioning.BuyerAgentRegistry` is wired,
this method ALSO resolves the commercial buyer-agent identity
BEFORE calling ``AccountStore.resolve`` and stashes the result
on ``ctx.metadata['adcp.buyer_agent']`` for :meth:`_build_ctx`
to read into the typed :class:`RequestContext`. Suspended /
blocked / unrecognized agents are rejected here with
``PERMISSION_DENIED`` (recognized-but-denied paths carry
``details.scope="agent"`` + ``details.status``; the
unrecognized-agent path omits ``details`` so the wire shape
does not enumerate which ``agent_url``s are onboarded with
this seller) instead of the registry miss leaking into the
AccountStore as ``ACCOUNT_NOT_FOUND``.
"""
auth_info = self._extract_auth_info(ctx)
if self._buyer_agent_registry is not None:
buyer_agent = await _resolve_buyer_agent(
self._buyer_agent_registry,
auth_info,
)
ctx.metadata["adcp.buyer_agent"] = buyer_agent
# Handle both Pydantic AccountReference (typical wire path) and
# raw dict (test fixtures using model_construct, custom dispatch
# paths). Adopter stores implementing custom shapes are
# responsible for whatever they accept.
ref_dict: dict[str, Any] | None
if ref is None:
ref_dict = None
elif hasattr(ref, "model_dump"):
ref_dict = ref.model_dump()
elif isinstance(ref, dict):
ref_dict = ref
else:
ref_dict = cast("dict[str, Any]", ref)
result = self._platform.accounts.resolve(ref_dict, auth_info=auth_info)
if asyncio.iscoroutine(result):
resolved = cast("Account[Any]", await result)
else:
resolved = cast("Account[Any]", result)
# Phase 1 sandbox-authority — track explicit mode values for the
# comply controller's env-fallback fail-closed guard. Implicit
# default-live (resolver didn't populate mode) is intentionally
# NOT recorded so pre-migration adopters keep working with
# ADCP_SANDBOX=1.
from adcp.decisioning.observed_modes import record_resolved_account_mode
record_resolved_account_mode(resolved)
return resolved
@staticmethod
def _extract_auth_info(ctx: ToolContext) -> AuthInfo | None:
"""Pull AuthInfo from ToolContext.metadata when present.
The framework's existing auth integrations (BearerTokenAuthMiddleware,
custom context_factory) populate ``ctx.metadata`` with
principal/scope info. Adopter conventions vary; this helper checks
for an ``adcp.auth_info`` key — Stage 3 ``serve()`` wiring sets
this from the canonical principal. Returns None when no auth key
is present (dev / ``'derived'`` fixtures).
"""
raw = ctx.metadata.get("adcp.auth_info") if ctx.metadata else None
if isinstance(raw, AuthInfo):
return raw
if isinstance(raw, dict):
# Translate the legacy dict-shape into typed AuthInfo via
# the framework-internal classmethod that pre-synthesizes
# the bearer credential without firing the
# DeprecationWarning. The warning's actionable target is
# adopter code constructing AuthInfo directly — pointing
# it at this framework shim every request would be noise
# the adopter can't fix by changing their code.
return AuthInfo._from_legacy_dict(raw)
return None
def _maybe_auto_emit_sync_completion(
self,
method_name: str,
params: Any,
result: Any,
) -> None:
"""Fire the F12 sync-completion webhook if applicable.
Skips TaskHandoff projections — those go through the registry
completion path which emits its own webhook on terminal state.
The auto-emit fires on the sync-success arm only, mirroring the
JS-side ``routeIfHandoff`` logic at
``src/lib/server/decisioning/runtime/from-platform.ts``.
TaskHandoff projection returns the exact 2-key dict ``{"task_id":
..., "status": "submitted"}`` from ``_project_handoff``; we
match the full key set rather than the loose ``status ==
"submitted"`` predicate so an adopter who legitimately returns a
sync ``{"status": "submitted", ...}`` (e.g., synchronous queue
acceptance with extra metadata) still gets the auto-emit.
"""
if (
isinstance(result, dict)
and set(result.keys()) == {"task_id", "status"}
and result.get("status") == "submitted"
):
# TaskHandoff projection — registry completion path emits
# its own webhook on terminal state.
return
maybe_emit_sync_completion(
sender=self._webhook_sender,
supervisor=self._webhook_supervisor,
enabled=self._auto_emit_completion_webhooks,
method_name=method_name,
params=params,
result=result,
)
def _build_ctx(
self,
tool_ctx: ToolContext,
account: Account[Any],
) -> Any:
"""Wrap :func:`_build_request_context` with the handler's
wired StateReader / ResourceResolver overrides AND the
platform's AccountStore (for D9 round-3 composite cache
scope-key derivation).
Reads the resolved :class:`BuyerAgent` from
``tool_ctx.metadata['adcp.buyer_agent']`` (stashed by
:meth:`_resolve_account` when a registry is wired) and passes
it through to the typed :class:`RequestContext`. Uses
``pop`` so the value is consumed once — protects against
the pathological case where a misconfigured ``context_factory``
returns the same ``ToolContext`` across requests, which would
otherwise leak the prior request's resolved buyer-agent into
the next dispatch.
"""
auth_info = self._extract_auth_info(tool_ctx)
buyer_agent = tool_ctx.metadata.pop("adcp.buyer_agent", None) if tool_ctx.metadata else None
return _build_request_context(
tool_ctx,
account,
auth_info,
store=self._platform.accounts,
state_reader=self._state_reader,
resource_resolver=self._resource_resolver,
buyer_agent=buyer_agent,
)
# ----- Protocol discovery -----
async def get_adcp_capabilities(
self,
params: Any = None,
context: ToolContext | None = None,
) -> dict[str, Any]:
"""Project the platform's :class:`DecisioningCapabilities` into a
spec-conformant ``get_adcp_capabilities`` response.
The projection mirrors the wire spec block-by-block. Each
top-level capability block (``account``, ``media_buy``,
``signals``, ``governance``, ``sponsored_intelligence``,
``brand``, ``creative``, ``request_signing``, ``webhook_signing``,
``identity``, ``compliance_testing``) is emitted via
``model_dump(mode="json", exclude_none=True)`` when the
adopter has declared a value.
Auto-derives:
* ``adcp.idempotency`` from
:attr:`DecisioningCapabilities.adcp` (when set) or defaults
to ``{"supported": False}`` so the response stays spec-valid.
* ``supported_protocols`` from
:attr:`DecisioningCapabilities.supported_protocols` (override)
or, when None, the union of :data:`SPECIALISM_TO_PROTOCOLS`