-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathmcp_server.py
More file actions
3098 lines (2647 loc) · 102 KB
/
Copy pathmcp_server.py
File metadata and controls
3098 lines (2647 loc) · 102 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
# Author: Green Mountain Systems AI Inc.
# Donated to IAB Tech Lab
"""MCP (Model Context Protocol) server for the Ad Buyer Agent.
Exposes buyer operations as MCP tools via FastMCP SSE transport.
This is the foundation server that all other MCP tool modules build upon.
Tool categories:
- Foundation: get_setup_status, health_check, get_config
- Setup Wizard: run_setup_wizard, get_wizard_step,
complete_wizard_step, skip_wizard_step (buyer-byk)
- Campaign Management: list_campaigns, get_campaign_status,
check_pacing, review_budgets (buyer-3w3)
- Deal Library: list_deals, search_deals, inspect_deal,
import_deals_csv, create_deal_manual, get_portfolio_summary (buyer-4ds)
- Seller Discovery: discover_sellers, get_seller_media_kit,
compare_sellers (buyer-nob)
- Negotiation: start_negotiation, get_negotiation_status,
list_active_negotiations (buyer-r0j)
- Orders: list_orders, get_order_status, transition_order (buyer-r0j)
Mount into a FastAPI app:
from ad_buyer.interfaces.mcp_server import mount_mcp
mount_mcp(app)
This creates an SSE endpoint at /mcp/sse for MCP client connections
(Claude Desktop, ChatGPT, Cursor, Windsurf, etc.).
"""
from __future__ import annotations
import csv
import io
import json
import logging
import os
import sqlite3
from datetime import UTC, datetime, timedelta
from typing import Any
from fastapi import FastAPI
from mcp.server.fastmcp import FastMCP
from mcp.server.fastmcp.prompts.base import Message
from ..auth.key_store import ApiKeyStore
from ..clients.mixpeek_client import MixpeekClient, MixpeekError
from ..config.settings import Settings
from ..media_kit.client import MediaKitClient
from ..media_kit.models import MediaKitError
from ..registry.client import RegistryClient
from ..services.setup_wizard import SetupWizard
from ..storage.campaign_store import CampaignStore
from ..storage.deal_store import DealStore
from ..storage.order_store import OrderStore
from ..storage.pacing_store import PacingStore
from ..tools.deal_import import (
ImportResult as CsvImportResult,
)
from ..tools.deal_import import (
_parse_row,
_resolve_columns,
)
from ..tools.deal_library.connectors import (
IndexExchangeConnector, # noqa: F401 - looked up dynamically via _get_ssp_connector_class
MagniteConnector, # noqa: F401
PubMaticConnector, # noqa: F401
)
from ..tools.deal_library.deal_entry import (
ManualDealEntry,
create_manual_deal,
)
logger = logging.getLogger(__name__)
# ---------------------------------------------------------------------------
# MCP Server Instance
# ---------------------------------------------------------------------------
mcp = FastMCP(
name="ad-buyer-agent",
instructions=(
"You are the IAB Tech Lab Ad Buyer Agent assistant. "
"You help users manage advertising campaigns, deals, seller "
"relationships, and buyer operations through the buyer agent system. "
"Use the available tools to check system status, review configuration, "
"and manage buyer workflows."
),
# streamable_http_path="/" so that when mounted at /mcp in FastAPI the
# endpoint resolves to /mcp (not /mcp/mcp which is the default).
streamable_http_path="/",
# host="0.0.0.0" disables the auto DNS-rebinding protection that FastMCP
# applies when host is 127.0.0.1/localhost. That protection blocks requests
# from Cloud Run (Host header is the public *.run.app domain) with 421.
host="0.0.0.0",
)
def _get_settings() -> Settings:
"""Get a fresh Settings instance.
Returns a new instance each time so that environment changes
(and test patches) are reflected.
"""
return Settings()
def _get_campaign_store() -> CampaignStore:
"""Get a connected CampaignStore instance.
Uses the database URL from settings. Returns a new connected
instance each time so that test patches are reflected.
"""
settings = _get_settings()
store = CampaignStore(settings.database_url)
store.connect()
return store
def _get_pacing_store() -> PacingStore:
"""Get a connected PacingStore instance.
Uses the database URL from settings. Returns a new connected
instance each time so that test patches are reflected.
"""
settings = _get_settings()
store = PacingStore(settings.database_url)
store.connect()
return store
# Deal store with test-injection support
_deal_store_override: DealStore | None = None
def _get_deal_store() -> DealStore:
"""Get a connected DealStore instance.
If a test override has been set via ``_set_deal_store()``, returns
that instance. Otherwise creates a new one from settings.
"""
if _deal_store_override is not None:
return _deal_store_override
settings = _get_settings()
store = DealStore(settings.database_url)
store.connect()
return store
def _set_deal_store(store: DealStore | None) -> None:
"""Set (or clear) a DealStore override for testing.
Pass a connected in-memory DealStore to inject test data.
Pass None to revert to the default settings-based store.
"""
global _deal_store_override
_deal_store_override = store
def _get_registry_client() -> RegistryClient:
"""Get a RegistryClient instance.
Uses the IAB server URL from settings as the registry URL.
Returns a new instance each time so that test patches are reflected.
"""
settings = _get_settings()
return RegistryClient(registry_url=settings.iab_server_url)
def _get_api_key_store() -> ApiKeyStore:
"""Get an ApiKeyStore instance.
Uses the default store path (~/.ad_buyer/seller_keys.json).
Returns a new instance each time so that test patches are reflected.
"""
return ApiKeyStore()
def _mask_key(key: str) -> str:
"""Mask an API key for display, showing only last 4 characters."""
if len(key) <= 4:
return "****"
return "*" * (len(key) - 4) + key[-4:]
def _get_media_kit_client() -> MediaKitClient:
"""Get a MediaKitClient instance.
Uses the API key from settings for authenticated access.
Returns a new instance each time so that test patches are reflected.
"""
settings = _get_settings()
return MediaKitClient(api_key=settings.api_key)
def _get_order_store() -> OrderStore:
"""Get a connected OrderStore instance.
Uses the database URL from settings. Returns a new connected
instance each time so that test patches are reflected.
"""
settings = _get_settings()
store = OrderStore(settings.database_url)
store.connect()
return store
# ---------------------------------------------------------------------------
# Foundation Tools
# ---------------------------------------------------------------------------
@mcp.tool()
def get_setup_status() -> str:
"""Check the current setup and configuration state of the buyer agent.
Returns a JSON object with:
- setup_complete: whether all required configuration is in place
- checks: individual status checks (seller endpoints, database, etc.)
"""
settings = _get_settings()
checks: dict[str, bool] = {}
# Check seller endpoints
seller_endpoints = settings.get_seller_endpoints()
checks["seller_endpoints_configured"] = len(seller_endpoints) > 0
# Check database accessibility
db_accessible = False
try:
db_url = settings.database_url
# Strip sqlite:/// prefix for direct connection test
if db_url.startswith("sqlite:///"):
db_path = db_url[len("sqlite:///") :]
else:
db_path = db_url
# Try a lightweight connection test
conn = sqlite3.connect(db_path)
conn.execute("SELECT 1")
conn.close()
db_accessible = True
except (sqlite3.Error, OSError):
db_accessible = False
checks["database_accessible"] = db_accessible
# Check API key configuration
checks["api_key_configured"] = bool(settings.api_key)
# Check LLM configuration
checks["llm_configured"] = bool(settings.anthropic_api_key)
# Overall setup completeness
# Minimum required: seller endpoints + database
setup_complete = checks["seller_endpoints_configured"] and checks["database_accessible"]
result = {
"setup_complete": setup_complete,
"checks": checks,
"timestamp": datetime.now(UTC).isoformat(),
}
return json.dumps(result, indent=2)
@mcp.tool()
def health_check() -> str:
"""Check the health of buyer agent services.
Returns a JSON object with:
- status: overall health (healthy, degraded, unhealthy)
- version: system version
- services: individual service health details
"""
from .. import __version__
settings = _get_settings()
services: dict[str, dict] = {}
# Check database service
try:
db_url = settings.database_url
if db_url.startswith("sqlite:///"):
db_path = db_url[len("sqlite:///") :]
else:
db_path = db_url
conn = sqlite3.connect(db_path)
conn.execute("SELECT 1")
conn.close()
services["database"] = {"status": "healthy"}
except (sqlite3.Error, OSError) as exc:
services["database"] = {"status": "unhealthy", "error": str(exc)}
# Check seller connectivity (lightweight -- just config presence)
seller_endpoints = settings.get_seller_endpoints()
if seller_endpoints:
services["seller_connections"] = {
"status": "configured",
"endpoint_count": len(seller_endpoints),
}
else:
services["seller_connections"] = {
"status": "not_configured",
"endpoint_count": 0,
}
# Check event bus availability
services["event_bus"] = {"status": "healthy"}
# Determine overall status
unhealthy_count = sum(1 for s in services.values() if s.get("status") == "unhealthy")
if unhealthy_count == 0:
overall_status = "healthy"
elif unhealthy_count < len(services):
overall_status = "degraded"
else:
overall_status = "unhealthy"
result = {
"status": overall_status,
"version": __version__,
"services": services,
"timestamp": datetime.now(UTC).isoformat(),
}
return json.dumps(result, indent=2)
@mcp.tool()
def get_config() -> str:
"""Get the current buyer agent configuration.
Returns non-sensitive configuration values. API keys and secrets
are never exposed through this tool.
Returns a JSON object with:
- environment: current environment (development, staging, production)
- seller_endpoints: configured seller agent URLs
- database_url: database connection string
- llm settings: model names, temperature, etc.
"""
settings = _get_settings()
result = {
"environment": settings.environment,
"seller_endpoints": settings.get_seller_endpoints(),
"iab_server_url": settings.iab_server_url,
"database_url": settings.database_url,
"default_llm_model": settings.default_llm_model,
"manager_llm_model": settings.manager_llm_model,
"llm_temperature": settings.llm_temperature,
"llm_max_tokens": settings.llm_max_tokens,
"cors_allowed_origins": settings.get_cors_origins(),
"log_level": settings.log_level,
"crew_memory_enabled": settings.crew_memory_enabled,
"crew_verbose": settings.crew_verbose,
"crew_max_iterations": settings.crew_max_iterations,
}
return json.dumps(result, indent=2)
# ---------------------------------------------------------------------------
# Setup Wizard Tools (buyer-byk)
# ---------------------------------------------------------------------------
# Module-level wizard instance for state persistence across MCP calls.
_wizard_instance: SetupWizard | None = None
def _get_wizard() -> SetupWizard:
"""Get or create the module-level SetupWizard instance."""
global _wizard_instance
if _wizard_instance is None:
_wizard_instance = SetupWizard()
return _wizard_instance
def _set_wizard(wizard: SetupWizard | None) -> None:
"""Set (or clear) the wizard instance for testing."""
global _wizard_instance
_wizard_instance = wizard
@mcp.tool()
def run_setup_wizard() -> str:
"""Run the setup wizard and get the current status of all steps.
Auto-detects completed steps from existing configuration, then
returns the full wizard state including all 8 steps, progress
percentage, and current phase (developer or business).
Returns a JSON object with:
- steps: list of all 8 wizard steps with status and config
- completed: whether all steps are done
- progress_pct: percentage of steps completed (0-100)
- current_phase: 'developer' or 'business'
- timestamp: when this status was generated
"""
wizard = _get_wizard()
result = wizard.run_wizard()
result["timestamp"] = datetime.now(UTC).isoformat()
return json.dumps(result, indent=2)
@mcp.tool()
def get_wizard_step(step_number: int) -> str:
"""Get detailed information about a specific wizard step.
Args:
step_number: The step number (1-8).
Returns a JSON object with:
- step_number, title, description, phase
- config_fields: fields this step configures
- defaults: sensible default values
- status: not_started, completed, skipped, or auto_detected
- config: current configuration (if completed)
- error: present only if step_number is invalid
"""
wizard = _get_wizard()
try:
step = wizard.get_step(step_number)
result = step.to_dict()
result["timestamp"] = datetime.now(UTC).isoformat()
return json.dumps(result, indent=2)
except ValueError as exc:
return json.dumps(
{
"error": str(exc),
"timestamp": datetime.now(UTC).isoformat(),
},
indent=2,
)
@mcp.tool()
def complete_wizard_step(step_number: int, config: str = "{}") -> str:
"""Complete a wizard step with the given configuration.
Args:
step_number: The step number (1-8) to complete.
config: JSON string of configuration values for this step.
Example: '{"agency_name": "My Agency", "seat_id": "ttd-123"}'
Returns a JSON object with:
- success: whether the step was completed
- step_number: the completed step number
- status: the new step status
- error: present only on failure
"""
wizard = _get_wizard()
try:
config_dict = json.loads(config)
step = wizard.complete_step(step_number, config_dict)
return json.dumps(
{
"success": True,
"step_number": step.step_number,
"status": step.status.value,
"timestamp": datetime.now(UTC).isoformat(),
},
indent=2,
)
except (ValueError, json.JSONDecodeError) as exc:
return json.dumps(
{
"success": False,
"error": str(exc),
"timestamp": datetime.now(UTC).isoformat(),
},
indent=2,
)
@mcp.tool()
def skip_wizard_step(step_number: int) -> str:
"""Skip a wizard step, applying its sensible defaults.
Step 8 (Review & Launch) cannot be skipped.
Args:
step_number: The step number (1-7) to skip.
Returns a JSON object with:
- success: whether the step was skipped
- step_number: the skipped step number
- defaults_applied: the default values that were applied
- error: present only on failure (e.g., trying to skip step 8)
"""
wizard = _get_wizard()
try:
step = wizard.skip_step(step_number)
return json.dumps(
{
"success": True,
"step_number": step.step_number,
"status": step.status.value,
"defaults_applied": step.defaults,
"timestamp": datetime.now(UTC).isoformat(),
},
indent=2,
)
except ValueError as exc:
return json.dumps(
{
"error": str(exc),
"timestamp": datetime.now(UTC).isoformat(),
},
indent=2,
)
# ---------------------------------------------------------------------------
# Campaign Management Tools (buyer-3w3)
# ---------------------------------------------------------------------------
@mcp.tool()
def list_campaigns(status: str | None = None) -> str:
"""List all campaigns with optional status filter.
Args:
status: Optional campaign status to filter by
(e.g. DRAFT, PLANNING, BOOKING, READY, ACTIVE, PAUSED,
COMPLETED, CANCELED). If omitted, returns all campaigns.
Returns a JSON object with:
- total: number of campaigns matching the filter
- campaigns: list of campaign summary objects
"""
store = _get_campaign_store()
try:
kwargs: dict[str, Any] = {}
if status is not None:
kwargs["status"] = status
campaigns = store.list_campaigns(**kwargs)
campaign_summaries = []
for c in campaigns:
campaign_summaries.append(
{
"campaign_id": c["campaign_id"],
"campaign_name": c["campaign_name"],
"advertiser_id": c["advertiser_id"],
"status": c["status"],
"total_budget": c["total_budget"],
"currency": c.get("currency", "USD"),
"flight_start": c["flight_start"],
"flight_end": c["flight_end"],
}
)
result = {
"total": len(campaign_summaries),
"campaigns": campaign_summaries,
"timestamp": datetime.now(UTC).isoformat(),
}
return json.dumps(result, indent=2)
finally:
store.disconnect()
@mcp.tool()
def get_campaign_status(campaign_id: str) -> str:
"""Get detailed status of a specific campaign.
Args:
campaign_id: The unique identifier of the campaign.
Returns a JSON object with:
- campaign_id, campaign_name, status, budget, flight dates
- pacing: latest pacing snapshot data (or null if no data)
- error: present only if the campaign was not found
"""
campaign_store = _get_campaign_store()
pacing_store = _get_pacing_store()
try:
campaign = campaign_store.get_campaign(campaign_id)
if campaign is None:
return json.dumps(
{"error": f"Campaign not found: {campaign_id}"},
indent=2,
)
# Get latest pacing snapshot
latest = pacing_store.get_latest_pacing_snapshot(campaign_id)
pacing_data = None
if latest is not None:
pacing_data = {
"total_spend": latest.total_spend,
"expected_spend": latest.expected_spend,
"pacing_pct": latest.pacing_pct,
"deviation_pct": latest.deviation_pct,
"snapshot_timestamp": latest.timestamp.isoformat(),
}
# Parse channels JSON if present
channels_raw = campaign.get("channels")
channels: list[dict[str, Any]] = []
if channels_raw:
try:
channels = json.loads(channels_raw)
except (json.JSONDecodeError, TypeError):
channels = []
result = {
"campaign_id": campaign["campaign_id"],
"campaign_name": campaign["campaign_name"],
"advertiser_id": campaign["advertiser_id"],
"status": campaign["status"],
"total_budget": campaign["total_budget"],
"currency": campaign.get("currency", "USD"),
"flight_start": campaign["flight_start"],
"flight_end": campaign["flight_end"],
"channels": channels,
"pacing": pacing_data,
"timestamp": datetime.now(UTC).isoformat(),
}
return json.dumps(result, indent=2)
finally:
campaign_store.disconnect()
pacing_store.disconnect()
@mcp.tool()
def check_pacing(campaign_id: str) -> str:
"""Check budget pacing for a campaign.
Determines whether the campaign is on track, behind, or ahead
of its expected spend based on the latest pacing snapshot.
Pacing thresholds:
- on_track: deviation within +/- 10%
- behind: deviation below -10%
- ahead: deviation above +10%
- no_data: no pacing snapshots available
Args:
campaign_id: The unique identifier of the campaign.
Returns a JSON object with:
- pacing_status: on_track, behind, ahead, or no_data
- pacing_pct: current pacing percentage
- deviation_pct: deviation from expected pacing
- total_budget, total_spend, expected_spend
- channel_pacing: per-channel pacing breakdown (if available)
- error: present only if the campaign was not found
"""
campaign_store = _get_campaign_store()
pacing_store = _get_pacing_store()
try:
campaign = campaign_store.get_campaign(campaign_id)
if campaign is None:
return json.dumps(
{"error": f"Campaign not found: {campaign_id}"},
indent=2,
)
latest = pacing_store.get_latest_pacing_snapshot(campaign_id)
if latest is None:
result = {
"campaign_id": campaign_id,
"campaign_name": campaign["campaign_name"],
"pacing_status": "no_data",
"total_budget": campaign["total_budget"],
"total_spend": 0.0,
"expected_spend": 0.0,
"pacing_pct": 0.0,
"deviation_pct": 0.0,
"channel_pacing": [],
"timestamp": datetime.now(UTC).isoformat(),
}
return json.dumps(result, indent=2)
# Determine pacing status from deviation
deviation = latest.deviation_pct
if deviation < -10.0:
pacing_status = "behind"
elif deviation > 10.0:
pacing_status = "ahead"
else:
pacing_status = "on_track"
# Build channel pacing breakdown
channel_pacing = []
for ch in latest.channel_snapshots:
channel_pacing.append(
{
"channel": ch.channel,
"allocated_budget": ch.allocated_budget,
"spend": ch.spend,
"pacing_pct": ch.pacing_pct,
"impressions": ch.impressions,
}
)
result = {
"campaign_id": campaign_id,
"campaign_name": campaign["campaign_name"],
"pacing_status": pacing_status,
"total_budget": latest.total_budget,
"total_spend": latest.total_spend,
"expected_spend": latest.expected_spend,
"pacing_pct": latest.pacing_pct,
"deviation_pct": latest.deviation_pct,
"channel_pacing": channel_pacing,
"timestamp": datetime.now(UTC).isoformat(),
}
return json.dumps(result, indent=2)
finally:
campaign_store.disconnect()
pacing_store.disconnect()
@mcp.tool()
def review_budgets() -> str:
"""Review budget allocation and spend across all campaigns.
Provides an aggregate view of total budget and spend across all
campaigns, plus per-campaign budget breakdowns with delivery
percentages.
Returns a JSON object with:
- total_budget: sum of all campaign budgets
- total_spend: sum of all campaign spend (from latest pacing)
- campaigns: per-campaign budget and spend details
- timestamp: when this review was generated
"""
campaign_store = _get_campaign_store()
pacing_store = _get_pacing_store()
try:
campaigns = campaign_store.list_campaigns()
total_budget = 0.0
total_spend = 0.0
campaign_budgets = []
for c in campaigns:
budget = c["total_budget"]
total_budget += budget
# Get latest pacing for spend data
latest = pacing_store.get_latest_pacing_snapshot(c["campaign_id"])
spend = latest.total_spend if latest else 0.0
total_spend += spend
# Calculate delivery percentage
delivery_pct = (spend / budget * 100.0) if budget > 0 else 0.0
campaign_budgets.append(
{
"campaign_id": c["campaign_id"],
"campaign_name": c["campaign_name"],
"status": c["status"],
"total_budget": budget,
"total_spend": spend,
"delivery_pct": round(delivery_pct, 1),
"currency": c.get("currency", "USD"),
}
)
result = {
"total_budget": total_budget,
"total_spend": total_spend,
"overall_delivery_pct": (
round(total_spend / total_budget * 100.0, 1) if total_budget > 0 else 0.0
),
"campaign_count": len(campaign_budgets),
"campaigns": campaign_budgets,
"timestamp": datetime.now(UTC).isoformat(),
}
return json.dumps(result, indent=2)
finally:
campaign_store.disconnect()
pacing_store.disconnect()
# ---------------------------------------------------------------------------
# Deal Library Tools (buyer-4ds)
# ---------------------------------------------------------------------------
@mcp.tool()
def list_deals(
status: str | None = None,
deal_type: str | None = None,
media_type: str | None = None,
seller_domain: str | None = None,
limit: int = 50,
) -> str:
"""List deals in the portfolio with optional filters.
Args:
status: Filter by deal status (e.g. draft, active, paused, imported).
deal_type: Filter by deal type (PG, PD, PA, OPEN_AUCTION, UPFRONT, SCATTER).
media_type: Filter by media type (DIGITAL, CTV, LINEAR_TV, AUDIO, DOOH).
seller_domain: Filter by seller domain (e.g. espn.com).
limit: Maximum number of deals to return (default 50).
Returns a JSON object with:
- total: number of deals matching the filter
- deals: list of deal summary objects
- timestamp: when this list was generated
"""
store = _get_deal_store()
try:
kwargs: dict[str, Any] = {}
if status is not None:
kwargs["status"] = status
if deal_type is not None:
kwargs["deal_type"] = deal_type
if media_type is not None:
kwargs["media_type"] = media_type
if seller_domain is not None:
kwargs["seller_domain"] = seller_domain
kwargs["limit"] = limit
deals = store.list_deals(**kwargs)
deal_summaries = []
for d in deals:
deal_summaries.append(
{
"deal_id": d["id"],
"display_name": d.get("display_name") or d.get("product_name") or "(unnamed)",
"status": d.get("status", "unknown"),
"deal_type": d.get("deal_type", "unknown"),
"media_type": d.get("media_type"),
"seller_org": d.get("seller_org"),
"seller_domain": d.get("seller_domain"),
"price": d.get("price"),
"impressions": d.get("impressions"),
"flight_start": d.get("flight_start"),
"flight_end": d.get("flight_end"),
}
)
result = {
"total": len(deal_summaries),
"deals": deal_summaries,
"timestamp": datetime.now(UTC).isoformat(),
}
return json.dumps(result, indent=2)
finally:
if _deal_store_override is None:
store.disconnect()
@mcp.tool()
def search_deals(query: str) -> str:
"""Search deals in the portfolio by free-text query.
Performs case-insensitive matching against display_name, description,
seller_org, and seller_domain fields.
Args:
query: Search string. Must not be empty.
Returns a JSON object with:
- total: number of matching deals
- deals: list of matching deal objects with match context
- timestamp: when this search was performed
"""
if not query or not query.strip():
return json.dumps(
{"error": "Search query must not be empty."},
indent=2,
)
query = query.strip()
query_lower = query.lower()
store = _get_deal_store()
try:
# Fetch all deals for search (search needs full scan)
deals = store.list_deals(limit=10000)
# Search fields and their labels
search_fields = [
("display_name", "display name"),
("product_name", "product name"),
("description", "description"),
("seller_org", "seller organization"),
("seller_domain", "seller domain"),
]
matches = []
for deal in deals:
matched_fields = []
for field_name, field_label in search_fields:
value = deal.get(field_name)
if value and query_lower in str(value).lower():
matched_fields.append(field_label)
if matched_fields:
matches.append(
{
"deal_id": deal["id"],
"display_name": (
deal.get("display_name") or deal.get("product_name") or "(unnamed)"
),
"status": deal.get("status", "unknown"),
"deal_type": deal.get("deal_type", "unknown"),
"media_type": deal.get("media_type"),
"seller_org": deal.get("seller_org"),
"seller_domain": deal.get("seller_domain"),
"price": deal.get("price"),
"matched_in": matched_fields,
}
)
result = {
"total": len(matches),
"query": query,
"deals": matches,
"timestamp": datetime.now(UTC).isoformat(),
}
return json.dumps(result, indent=2)
finally:
if _deal_store_override is None:
store.disconnect()
# ---------------------------------------------------------------------------
# Seller Discovery Tools (buyer-nob)
# ---------------------------------------------------------------------------
@mcp.tool()
async def discover_sellers(capability: str | None = None) -> str:
"""Discover available seller agents from the IAB AAMP registry.
Queries the agent registry to find seller agents, optionally
filtering by capability name (e.g., "ctv", "display", "video").
Args:
capability: Optional capability name to filter sellers by.
If omitted, returns all sellers in the registry.
Returns a JSON object with:
- total: number of sellers found
- sellers: list of seller agent cards with id, name, url,
capabilities, trust_level, and protocols
"""
registry = _get_registry_client()
try:
caps_filter = [capability] if capability else None
sellers = await registry.discover_sellers(
capabilities_filter=caps_filter,
)
seller_list = []
for seller in sellers:
seller_list.append(
{
"agent_id": seller.agent_id,
"name": seller.name,
"url": seller.url,
"capabilities": [
{"name": c.name, "description": c.description, "tags": c.tags}
for c in seller.capabilities
],
"trust_level": seller.trust_level.value,
"protocols": seller.protocols,
}
)
result = {
"total": len(seller_list),
"sellers": seller_list,
"timestamp": datetime.now(UTC).isoformat(),
}
return json.dumps(result, indent=2)
except Exception as exc:
logger.warning("Failed to discover sellers: %s", exc)
result = {
"error": f"Failed to discover sellers: {exc}",
"total": 0,
"sellers": [],
"timestamp": datetime.now(UTC).isoformat(),
}
return json.dumps(result, indent=2)
@mcp.tool()
async def get_seller_media_kit(seller_url: str) -> str:
"""Fetch a specific seller's media kit with inventory and pricing.
Retrieves the media kit from a seller agent, showing available
packages, ad formats, pricing ranges, and capabilities.
Args:
seller_url: The base URL of the seller agent
(e.g., "http://localhost:8001").
Returns a JSON object with:
- seller_name: the seller's display name
- seller_url: the seller's base URL
- total_packages: number of available packages