adcp 1.0.5__tar.gz → 1.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {adcp-1.0.5/src/adcp.egg-info → adcp-1.1.0}/PKG-INFO +61 -16
- {adcp-1.0.5 → adcp-1.1.0}/README.md +60 -15
- {adcp-1.0.5 → adcp-1.1.0}/pyproject.toml +1 -1
- {adcp-1.0.5 → adcp-1.1.0}/src/adcp/__init__.py +1 -1
- {adcp-1.0.5 → adcp-1.1.0}/src/adcp/client.py +96 -5
- {adcp-1.0.5 → adcp-1.1.0}/src/adcp/protocols/a2a.py +4 -0
- {adcp-1.0.5 → adcp-1.1.0}/src/adcp/protocols/mcp.py +41 -41
- {adcp-1.0.5 → adcp-1.1.0}/src/adcp/types/core.py +3 -4
- {adcp-1.0.5 → adcp-1.1.0}/src/adcp/types/generated.py +58 -35
- adcp-1.1.0/src/adcp/utils/preview_cache.py +461 -0
- {adcp-1.0.5 → adcp-1.1.0/src/adcp.egg-info}/PKG-INFO +61 -16
- {adcp-1.0.5 → adcp-1.1.0}/src/adcp.egg-info/SOURCES.txt +2 -0
- {adcp-1.0.5 → adcp-1.1.0}/tests/test_client.py +107 -0
- adcp-1.1.0/tests/test_preview_html.py +376 -0
- {adcp-1.0.5 → adcp-1.1.0}/tests/test_protocols.py +113 -0
- {adcp-1.0.5 → adcp-1.1.0}/LICENSE +0 -0
- {adcp-1.0.5 → adcp-1.1.0}/setup.cfg +0 -0
- {adcp-1.0.5 → adcp-1.1.0}/src/adcp/__main__.py +0 -0
- {adcp-1.0.5 → adcp-1.1.0}/src/adcp/config.py +0 -0
- {adcp-1.0.5 → adcp-1.1.0}/src/adcp/exceptions.py +0 -0
- {adcp-1.0.5 → adcp-1.1.0}/src/adcp/protocols/__init__.py +0 -0
- {adcp-1.0.5 → adcp-1.1.0}/src/adcp/protocols/base.py +0 -0
- {adcp-1.0.5 → adcp-1.1.0}/src/adcp/types/__init__.py +0 -0
- {adcp-1.0.5 → adcp-1.1.0}/src/adcp/types/tasks.py +0 -0
- {adcp-1.0.5 → adcp-1.1.0}/src/adcp/utils/__init__.py +0 -0
- {adcp-1.0.5 → adcp-1.1.0}/src/adcp/utils/operation_id.py +0 -0
- {adcp-1.0.5 → adcp-1.1.0}/src/adcp/utils/response_parser.py +0 -0
- {adcp-1.0.5 → adcp-1.1.0}/src/adcp.egg-info/dependency_links.txt +0 -0
- {adcp-1.0.5 → adcp-1.1.0}/src/adcp.egg-info/entry_points.txt +0 -0
- {adcp-1.0.5 → adcp-1.1.0}/src/adcp.egg-info/requires.txt +0 -0
- {adcp-1.0.5 → adcp-1.1.0}/src/adcp.egg-info/top_level.txt +0 -0
- {adcp-1.0.5 → adcp-1.1.0}/tests/test_cli.py +0 -0
- {adcp-1.0.5 → adcp-1.1.0}/tests/test_code_generation.py +0 -0
- {adcp-1.0.5 → adcp-1.1.0}/tests/test_format_id_validation.py +0 -0
- {adcp-1.0.5 → adcp-1.1.0}/tests/test_response_parser.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: adcp
|
|
3
|
-
Version: 1.0
|
|
3
|
+
Version: 1.1.0
|
|
4
4
|
Summary: Official Python client for the Ad Context Protocol (AdCP)
|
|
5
5
|
Author-email: AdCP Community <maintainers@adcontextprotocol.org>
|
|
6
6
|
License: Apache-2.0
|
|
@@ -64,8 +64,8 @@ pip install adcp
|
|
|
64
64
|
```python
|
|
65
65
|
from adcp import ADCPMultiAgentClient, AgentConfig, GetProductsRequest
|
|
66
66
|
|
|
67
|
-
# Configure agents and handlers
|
|
68
|
-
|
|
67
|
+
# Configure agents and handlers (context manager ensures proper cleanup)
|
|
68
|
+
async with ADCPMultiAgentClient(
|
|
69
69
|
agents=[
|
|
70
70
|
AgentConfig(
|
|
71
71
|
id="agent_x",
|
|
@@ -91,21 +91,21 @@ client = ADCPMultiAgentClient(
|
|
|
91
91
|
if metadata.status == "completed" else None
|
|
92
92
|
)
|
|
93
93
|
}
|
|
94
|
-
)
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
result = await agent.get_products(request)
|
|
94
|
+
) as client:
|
|
95
|
+
# Execute operation - library handles operation IDs, webhook URLs, context management
|
|
96
|
+
agent = client.agent("agent_x")
|
|
97
|
+
request = GetProductsRequest(brief="Coffee brands")
|
|
98
|
+
result = await agent.get_products(request)
|
|
100
99
|
|
|
101
|
-
# Check result
|
|
102
|
-
if result.status == "completed":
|
|
103
|
-
|
|
104
|
-
|
|
100
|
+
# Check result
|
|
101
|
+
if result.status == "completed":
|
|
102
|
+
# Agent completed synchronously!
|
|
103
|
+
print(f"✅ Sync completion: {len(result.data.products)} products")
|
|
105
104
|
|
|
106
|
-
if result.status == "submitted":
|
|
107
|
-
|
|
108
|
-
|
|
105
|
+
if result.status == "submitted":
|
|
106
|
+
# Agent will send webhook when complete
|
|
107
|
+
print(f"⏳ Async - webhook registered at: {result.submitted.webhook_url}")
|
|
108
|
+
# Connections automatically cleaned up here
|
|
109
109
|
```
|
|
110
110
|
|
|
111
111
|
## Features
|
|
@@ -210,6 +210,51 @@ Or use the CLI:
|
|
|
210
210
|
uvx adcp --debug myagent get_products '{"brief":"TV ads"}'
|
|
211
211
|
```
|
|
212
212
|
|
|
213
|
+
### Resource Management
|
|
214
|
+
|
|
215
|
+
**Why use async context managers?**
|
|
216
|
+
- Ensures HTTP connections are properly closed, preventing resource leaks
|
|
217
|
+
- Handles cleanup even when exceptions occur
|
|
218
|
+
- Required for production applications with connection pooling
|
|
219
|
+
- Prevents issues with async task group cleanup in MCP protocol
|
|
220
|
+
|
|
221
|
+
The recommended pattern uses async context managers:
|
|
222
|
+
|
|
223
|
+
```python
|
|
224
|
+
from adcp import ADCPClient, AgentConfig, GetProductsRequest
|
|
225
|
+
|
|
226
|
+
# Recommended: Automatic cleanup with context manager
|
|
227
|
+
config = AgentConfig(id="agent_x", agent_uri="https://...", protocol="a2a")
|
|
228
|
+
async with ADCPClient(config) as client:
|
|
229
|
+
request = GetProductsRequest(brief="Coffee brands")
|
|
230
|
+
result = await client.get_products(request)
|
|
231
|
+
# Connection automatically closed on exit
|
|
232
|
+
|
|
233
|
+
# Multi-agent client also supports context managers
|
|
234
|
+
async with ADCPMultiAgentClient(agents) as client:
|
|
235
|
+
# Execute across all agents in parallel
|
|
236
|
+
results = await client.get_products(request)
|
|
237
|
+
# All agent connections closed automatically (even if some failed)
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
Manual cleanup is available for special cases (e.g., managing client lifecycle manually):
|
|
241
|
+
|
|
242
|
+
```python
|
|
243
|
+
# Use manual cleanup when you need fine-grained control over lifecycle
|
|
244
|
+
client = ADCPClient(config)
|
|
245
|
+
try:
|
|
246
|
+
result = await client.get_products(request)
|
|
247
|
+
finally:
|
|
248
|
+
await client.close() # Explicit cleanup
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
**When to use manual cleanup:**
|
|
252
|
+
- Managing client lifecycle across multiple functions
|
|
253
|
+
- Testing scenarios requiring explicit control
|
|
254
|
+
- Integration with frameworks that manage resources differently
|
|
255
|
+
|
|
256
|
+
In most cases, prefer the context manager pattern.
|
|
257
|
+
|
|
213
258
|
### Error Handling
|
|
214
259
|
|
|
215
260
|
The library provides a comprehensive exception hierarchy with helpful error messages:
|
|
@@ -27,8 +27,8 @@ pip install adcp
|
|
|
27
27
|
```python
|
|
28
28
|
from adcp import ADCPMultiAgentClient, AgentConfig, GetProductsRequest
|
|
29
29
|
|
|
30
|
-
# Configure agents and handlers
|
|
31
|
-
|
|
30
|
+
# Configure agents and handlers (context manager ensures proper cleanup)
|
|
31
|
+
async with ADCPMultiAgentClient(
|
|
32
32
|
agents=[
|
|
33
33
|
AgentConfig(
|
|
34
34
|
id="agent_x",
|
|
@@ -54,21 +54,21 @@ client = ADCPMultiAgentClient(
|
|
|
54
54
|
if metadata.status == "completed" else None
|
|
55
55
|
)
|
|
56
56
|
}
|
|
57
|
-
)
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
result = await agent.get_products(request)
|
|
57
|
+
) as client:
|
|
58
|
+
# Execute operation - library handles operation IDs, webhook URLs, context management
|
|
59
|
+
agent = client.agent("agent_x")
|
|
60
|
+
request = GetProductsRequest(brief="Coffee brands")
|
|
61
|
+
result = await agent.get_products(request)
|
|
63
62
|
|
|
64
|
-
# Check result
|
|
65
|
-
if result.status == "completed":
|
|
66
|
-
|
|
67
|
-
|
|
63
|
+
# Check result
|
|
64
|
+
if result.status == "completed":
|
|
65
|
+
# Agent completed synchronously!
|
|
66
|
+
print(f"✅ Sync completion: {len(result.data.products)} products")
|
|
68
67
|
|
|
69
|
-
if result.status == "submitted":
|
|
70
|
-
|
|
71
|
-
|
|
68
|
+
if result.status == "submitted":
|
|
69
|
+
# Agent will send webhook when complete
|
|
70
|
+
print(f"⏳ Async - webhook registered at: {result.submitted.webhook_url}")
|
|
71
|
+
# Connections automatically cleaned up here
|
|
72
72
|
```
|
|
73
73
|
|
|
74
74
|
## Features
|
|
@@ -173,6 +173,51 @@ Or use the CLI:
|
|
|
173
173
|
uvx adcp --debug myagent get_products '{"brief":"TV ads"}'
|
|
174
174
|
```
|
|
175
175
|
|
|
176
|
+
### Resource Management
|
|
177
|
+
|
|
178
|
+
**Why use async context managers?**
|
|
179
|
+
- Ensures HTTP connections are properly closed, preventing resource leaks
|
|
180
|
+
- Handles cleanup even when exceptions occur
|
|
181
|
+
- Required for production applications with connection pooling
|
|
182
|
+
- Prevents issues with async task group cleanup in MCP protocol
|
|
183
|
+
|
|
184
|
+
The recommended pattern uses async context managers:
|
|
185
|
+
|
|
186
|
+
```python
|
|
187
|
+
from adcp import ADCPClient, AgentConfig, GetProductsRequest
|
|
188
|
+
|
|
189
|
+
# Recommended: Automatic cleanup with context manager
|
|
190
|
+
config = AgentConfig(id="agent_x", agent_uri="https://...", protocol="a2a")
|
|
191
|
+
async with ADCPClient(config) as client:
|
|
192
|
+
request = GetProductsRequest(brief="Coffee brands")
|
|
193
|
+
result = await client.get_products(request)
|
|
194
|
+
# Connection automatically closed on exit
|
|
195
|
+
|
|
196
|
+
# Multi-agent client also supports context managers
|
|
197
|
+
async with ADCPMultiAgentClient(agents) as client:
|
|
198
|
+
# Execute across all agents in parallel
|
|
199
|
+
results = await client.get_products(request)
|
|
200
|
+
# All agent connections closed automatically (even if some failed)
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
Manual cleanup is available for special cases (e.g., managing client lifecycle manually):
|
|
204
|
+
|
|
205
|
+
```python
|
|
206
|
+
# Use manual cleanup when you need fine-grained control over lifecycle
|
|
207
|
+
client = ADCPClient(config)
|
|
208
|
+
try:
|
|
209
|
+
result = await client.get_products(request)
|
|
210
|
+
finally:
|
|
211
|
+
await client.close() # Explicit cleanup
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
**When to use manual cleanup:**
|
|
215
|
+
- Managing client lifecycle across multiple functions
|
|
216
|
+
- Testing scenarios requiring explicit control
|
|
217
|
+
- Integration with frameworks that manage resources differently
|
|
218
|
+
|
|
219
|
+
In most cases, prefer the context manager pattern.
|
|
220
|
+
|
|
176
221
|
### Error Handling
|
|
177
222
|
|
|
178
223
|
The library provides a comprehensive exception hierarchy with helpful error messages:
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "adcp"
|
|
7
|
-
version = "1.0
|
|
7
|
+
version = "1.1.0"
|
|
8
8
|
description = "Official Python client for the Ad Context Protocol (AdCP)"
|
|
9
9
|
authors = [
|
|
10
10
|
{name = "AdCP Community", email = "maintainers@adcontextprotocol.org"}
|
|
@@ -37,6 +37,8 @@ from adcp.types.generated import (
|
|
|
37
37
|
ListCreativeFormatsResponse,
|
|
38
38
|
ListCreativesRequest,
|
|
39
39
|
ListCreativesResponse,
|
|
40
|
+
PreviewCreativeRequest,
|
|
41
|
+
PreviewCreativeResponse,
|
|
40
42
|
ProvidePerformanceFeedbackRequest,
|
|
41
43
|
ProvidePerformanceFeedbackResponse,
|
|
42
44
|
SyncCreativesRequest,
|
|
@@ -101,16 +103,31 @@ class ADCPClient:
|
|
|
101
103
|
async def get_products(
|
|
102
104
|
self,
|
|
103
105
|
request: GetProductsRequest,
|
|
106
|
+
fetch_previews: bool = False,
|
|
107
|
+
preview_output_format: str = "url",
|
|
108
|
+
creative_agent_client: ADCPClient | None = None,
|
|
104
109
|
) -> TaskResult[GetProductsResponse]:
|
|
105
110
|
"""
|
|
106
111
|
Get advertising products.
|
|
107
112
|
|
|
108
113
|
Args:
|
|
109
114
|
request: Request parameters
|
|
115
|
+
fetch_previews: If True, generate preview URLs for each product's formats
|
|
116
|
+
(uses batch API for 5-10x performance improvement)
|
|
117
|
+
preview_output_format: "url" for iframe URLs (default), "html" for direct
|
|
118
|
+
embedding (2-3x faster, no iframe overhead)
|
|
119
|
+
creative_agent_client: Client for creative agent (required if
|
|
120
|
+
fetch_previews=True)
|
|
110
121
|
|
|
111
122
|
Returns:
|
|
112
|
-
TaskResult containing GetProductsResponse
|
|
123
|
+
TaskResult containing GetProductsResponse with optional preview URLs in metadata
|
|
124
|
+
|
|
125
|
+
Raises:
|
|
126
|
+
ValueError: If fetch_previews=True but creative_agent_client is not provided
|
|
113
127
|
"""
|
|
128
|
+
if fetch_previews and not creative_agent_client:
|
|
129
|
+
raise ValueError("creative_agent_client is required when fetch_previews=True")
|
|
130
|
+
|
|
114
131
|
operation_id = create_operation_id()
|
|
115
132
|
params = request.model_dump(exclude_none=True)
|
|
116
133
|
|
|
@@ -137,20 +154,40 @@ class ADCPClient:
|
|
|
137
154
|
)
|
|
138
155
|
)
|
|
139
156
|
|
|
140
|
-
|
|
157
|
+
result = self.adapter._parse_response(raw_result, GetProductsResponse)
|
|
158
|
+
|
|
159
|
+
if fetch_previews and result.success and result.data and creative_agent_client:
|
|
160
|
+
from adcp.utils.preview_cache import add_preview_urls_to_products
|
|
161
|
+
|
|
162
|
+
products_with_previews = await add_preview_urls_to_products(
|
|
163
|
+
result.data.products,
|
|
164
|
+
creative_agent_client,
|
|
165
|
+
use_batch=True,
|
|
166
|
+
output_format=preview_output_format,
|
|
167
|
+
)
|
|
168
|
+
result.metadata = result.metadata or {}
|
|
169
|
+
result.metadata["products_with_previews"] = products_with_previews
|
|
170
|
+
|
|
171
|
+
return result
|
|
141
172
|
|
|
142
173
|
async def list_creative_formats(
|
|
143
174
|
self,
|
|
144
175
|
request: ListCreativeFormatsRequest,
|
|
176
|
+
fetch_previews: bool = False,
|
|
177
|
+
preview_output_format: str = "url",
|
|
145
178
|
) -> TaskResult[ListCreativeFormatsResponse]:
|
|
146
179
|
"""
|
|
147
180
|
List supported creative formats.
|
|
148
181
|
|
|
149
182
|
Args:
|
|
150
183
|
request: Request parameters
|
|
184
|
+
fetch_previews: If True, generate preview URLs for each format using
|
|
185
|
+
sample manifests (uses batch API for 5-10x performance improvement)
|
|
186
|
+
preview_output_format: "url" for iframe URLs (default), "html" for direct
|
|
187
|
+
embedding (2-3x faster, no iframe overhead)
|
|
151
188
|
|
|
152
189
|
Returns:
|
|
153
|
-
TaskResult containing ListCreativeFormatsResponse
|
|
190
|
+
TaskResult containing ListCreativeFormatsResponse with optional preview URLs in metadata
|
|
154
191
|
"""
|
|
155
192
|
operation_id = create_operation_id()
|
|
156
193
|
params = request.model_dump(exclude_none=True)
|
|
@@ -178,8 +215,62 @@ class ADCPClient:
|
|
|
178
215
|
)
|
|
179
216
|
)
|
|
180
217
|
|
|
181
|
-
|
|
182
|
-
|
|
218
|
+
result = self.adapter._parse_response(raw_result, ListCreativeFormatsResponse)
|
|
219
|
+
|
|
220
|
+
if fetch_previews and result.success and result.data:
|
|
221
|
+
from adcp.utils.preview_cache import add_preview_urls_to_formats
|
|
222
|
+
|
|
223
|
+
formats_with_previews = await add_preview_urls_to_formats(
|
|
224
|
+
result.data.formats,
|
|
225
|
+
self,
|
|
226
|
+
use_batch=True,
|
|
227
|
+
output_format=preview_output_format,
|
|
228
|
+
)
|
|
229
|
+
result.metadata = result.metadata or {}
|
|
230
|
+
result.metadata["formats_with_previews"] = formats_with_previews
|
|
231
|
+
|
|
232
|
+
return result
|
|
233
|
+
|
|
234
|
+
async def preview_creative(
|
|
235
|
+
self,
|
|
236
|
+
request: PreviewCreativeRequest,
|
|
237
|
+
) -> TaskResult[PreviewCreativeResponse]:
|
|
238
|
+
"""
|
|
239
|
+
Generate preview of a creative manifest.
|
|
240
|
+
|
|
241
|
+
Args:
|
|
242
|
+
request: Request parameters
|
|
243
|
+
|
|
244
|
+
Returns:
|
|
245
|
+
TaskResult containing PreviewCreativeResponse with preview URLs
|
|
246
|
+
"""
|
|
247
|
+
operation_id = create_operation_id()
|
|
248
|
+
params = request.model_dump(exclude_none=True)
|
|
249
|
+
|
|
250
|
+
self._emit_activity(
|
|
251
|
+
Activity(
|
|
252
|
+
type=ActivityType.PROTOCOL_REQUEST,
|
|
253
|
+
operation_id=operation_id,
|
|
254
|
+
agent_id=self.agent_config.id,
|
|
255
|
+
task_type="preview_creative",
|
|
256
|
+
timestamp=datetime.now(timezone.utc).isoformat(),
|
|
257
|
+
)
|
|
258
|
+
)
|
|
259
|
+
|
|
260
|
+
raw_result = await self.adapter.preview_creative(params) # type: ignore[attr-defined]
|
|
261
|
+
|
|
262
|
+
self._emit_activity(
|
|
263
|
+
Activity(
|
|
264
|
+
type=ActivityType.PROTOCOL_RESPONSE,
|
|
265
|
+
operation_id=operation_id,
|
|
266
|
+
agent_id=self.agent_config.id,
|
|
267
|
+
task_type="preview_creative",
|
|
268
|
+
status=raw_result.status,
|
|
269
|
+
timestamp=datetime.now(timezone.utc).isoformat(),
|
|
270
|
+
)
|
|
271
|
+
)
|
|
272
|
+
|
|
273
|
+
return self.adapter._parse_response(raw_result, PreviewCreativeResponse)
|
|
183
274
|
|
|
184
275
|
async def sync_creatives(
|
|
185
276
|
self,
|
|
@@ -244,6 +244,10 @@ class A2AAdapter(ProtocolAdapter):
|
|
|
244
244
|
"""Provide performance feedback."""
|
|
245
245
|
return await self._call_a2a_tool("provide_performance_feedback", params)
|
|
246
246
|
|
|
247
|
+
async def preview_creative(self, params: dict[str, Any]) -> TaskResult[Any]:
|
|
248
|
+
"""Generate preview URLs for a creative manifest."""
|
|
249
|
+
return await self._call_a2a_tool("preview_creative", params)
|
|
250
|
+
|
|
247
251
|
async def list_tools(self) -> list[str]:
|
|
248
252
|
"""
|
|
249
253
|
List available tools from A2A agent.
|
|
@@ -40,6 +40,39 @@ class MCPAdapter(ProtocolAdapter):
|
|
|
40
40
|
self._session: Any = None
|
|
41
41
|
self._exit_stack: Any = None
|
|
42
42
|
|
|
43
|
+
async def _cleanup_failed_connection(self, context: str) -> None:
|
|
44
|
+
"""
|
|
45
|
+
Clean up resources after a failed connection attempt.
|
|
46
|
+
|
|
47
|
+
This method handles cleanup without raising exceptions to avoid
|
|
48
|
+
masking the original connection error.
|
|
49
|
+
|
|
50
|
+
Args:
|
|
51
|
+
context: Description of the context for logging (e.g., "during connection attempt")
|
|
52
|
+
"""
|
|
53
|
+
if self._exit_stack is not None:
|
|
54
|
+
old_stack = self._exit_stack
|
|
55
|
+
self._exit_stack = None
|
|
56
|
+
self._session = None
|
|
57
|
+
try:
|
|
58
|
+
await old_stack.aclose()
|
|
59
|
+
except asyncio.CancelledError:
|
|
60
|
+
logger.debug(f"MCP session cleanup cancelled {context}")
|
|
61
|
+
except RuntimeError as cleanup_error:
|
|
62
|
+
# Known anyio task group cleanup issue
|
|
63
|
+
error_msg = str(cleanup_error).lower()
|
|
64
|
+
if "cancel scope" in error_msg or "async context" in error_msg:
|
|
65
|
+
logger.debug(f"Ignoring anyio cleanup error {context}: {cleanup_error}")
|
|
66
|
+
else:
|
|
67
|
+
logger.warning(
|
|
68
|
+
f"Unexpected RuntimeError during cleanup {context}: {cleanup_error}"
|
|
69
|
+
)
|
|
70
|
+
except Exception as cleanup_error:
|
|
71
|
+
# Log unexpected cleanup errors but don't raise to preserve original error
|
|
72
|
+
logger.warning(
|
|
73
|
+
f"Unexpected error during cleanup {context}: {cleanup_error}", exc_info=True
|
|
74
|
+
)
|
|
75
|
+
|
|
43
76
|
async def _get_session(self) -> ClientSession:
|
|
44
77
|
"""
|
|
45
78
|
Get or create MCP client session with URL fallback handling.
|
|
@@ -115,35 +148,8 @@ class MCPAdapter(ProtocolAdapter):
|
|
|
115
148
|
return self._session # type: ignore[no-any-return]
|
|
116
149
|
except Exception as e:
|
|
117
150
|
last_error = e
|
|
118
|
-
# Clean up the exit stack on failure to avoid
|
|
119
|
-
|
|
120
|
-
old_stack = self._exit_stack
|
|
121
|
-
self._exit_stack = None # Clear immediately to prevent reuse
|
|
122
|
-
self._session = None
|
|
123
|
-
try:
|
|
124
|
-
await old_stack.aclose()
|
|
125
|
-
except asyncio.CancelledError:
|
|
126
|
-
# Expected during shutdown
|
|
127
|
-
pass
|
|
128
|
-
except RuntimeError as cleanup_error:
|
|
129
|
-
# Known MCP SDK async cleanup issue
|
|
130
|
-
if (
|
|
131
|
-
"async context" in str(cleanup_error).lower()
|
|
132
|
-
or "cancel scope" in str(cleanup_error).lower()
|
|
133
|
-
):
|
|
134
|
-
logger.debug(
|
|
135
|
-
"Ignoring MCP SDK async context error during cleanup: "
|
|
136
|
-
f"{cleanup_error}"
|
|
137
|
-
)
|
|
138
|
-
else:
|
|
139
|
-
logger.warning(
|
|
140
|
-
f"Unexpected RuntimeError during cleanup: {cleanup_error}"
|
|
141
|
-
)
|
|
142
|
-
except Exception as cleanup_error:
|
|
143
|
-
# Unexpected cleanup errors should be logged
|
|
144
|
-
logger.warning(
|
|
145
|
-
f"Unexpected error during cleanup: {cleanup_error}", exc_info=True
|
|
146
|
-
)
|
|
151
|
+
# Clean up the exit stack on failure to avoid resource leaks
|
|
152
|
+
await self._cleanup_failed_connection("during connection attempt")
|
|
147
153
|
|
|
148
154
|
# If this isn't the last URL to try, create a new exit stack and continue
|
|
149
155
|
if url != urls_to_try[-1]:
|
|
@@ -341,6 +347,10 @@ class MCPAdapter(ProtocolAdapter):
|
|
|
341
347
|
"""Provide performance feedback."""
|
|
342
348
|
return await self._call_mcp_tool("provide_performance_feedback", params)
|
|
343
349
|
|
|
350
|
+
async def preview_creative(self, params: dict[str, Any]) -> TaskResult[Any]:
|
|
351
|
+
"""Generate preview URLs for a creative manifest."""
|
|
352
|
+
return await self._call_mcp_tool("preview_creative", params)
|
|
353
|
+
|
|
344
354
|
async def list_tools(self) -> list[str]:
|
|
345
355
|
"""List available tools from MCP agent."""
|
|
346
356
|
session = await self._get_session()
|
|
@@ -348,15 +358,5 @@ class MCPAdapter(ProtocolAdapter):
|
|
|
348
358
|
return [tool.name for tool in result.tools]
|
|
349
359
|
|
|
350
360
|
async def close(self) -> None:
|
|
351
|
-
"""Close the MCP session."""
|
|
352
|
-
|
|
353
|
-
old_stack = self._exit_stack
|
|
354
|
-
self._exit_stack = None
|
|
355
|
-
self._session = None
|
|
356
|
-
try:
|
|
357
|
-
await old_stack.aclose()
|
|
358
|
-
except (asyncio.CancelledError, RuntimeError):
|
|
359
|
-
# Cleanup errors during shutdown are expected
|
|
360
|
-
pass
|
|
361
|
-
except Exception as e:
|
|
362
|
-
logger.debug(f"Error during MCP session cleanup: {e}")
|
|
361
|
+
"""Close the MCP session and clean up resources."""
|
|
362
|
+
await self._cleanup_failed_connection("during close")
|
|
@@ -5,7 +5,7 @@ from __future__ import annotations
|
|
|
5
5
|
from enum import Enum
|
|
6
6
|
from typing import Any, Generic, Literal, TypeVar
|
|
7
7
|
|
|
8
|
-
from pydantic import BaseModel, Field, field_validator
|
|
8
|
+
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
|
9
9
|
|
|
10
10
|
|
|
11
11
|
class Protocol(str, Enum):
|
|
@@ -125,6 +125,8 @@ class DebugInfo(BaseModel):
|
|
|
125
125
|
class TaskResult(BaseModel, Generic[T]):
|
|
126
126
|
"""Result from task execution."""
|
|
127
127
|
|
|
128
|
+
model_config = ConfigDict(arbitrary_types_allowed=True)
|
|
129
|
+
|
|
128
130
|
status: TaskStatus
|
|
129
131
|
data: T | None = None
|
|
130
132
|
message: str | None = None # Human-readable message from agent (e.g., MCP content text)
|
|
@@ -135,9 +137,6 @@ class TaskResult(BaseModel, Generic[T]):
|
|
|
135
137
|
metadata: dict[str, Any] | None = None
|
|
136
138
|
debug_info: DebugInfo | None = None
|
|
137
139
|
|
|
138
|
-
class Config:
|
|
139
|
-
arbitrary_types_allowed = True
|
|
140
|
-
|
|
141
140
|
|
|
142
141
|
class ActivityType(str, Enum):
|
|
143
142
|
"""Types of activity events."""
|
|
@@ -32,23 +32,6 @@ ReportingCapabilities = dict[str, Any]
|
|
|
32
32
|
# CORE DOMAIN TYPES
|
|
33
33
|
# ============================================================================
|
|
34
34
|
|
|
35
|
-
class FormatId(BaseModel):
|
|
36
|
-
"""Structured format identifier with agent URL and format name"""
|
|
37
|
-
|
|
38
|
-
agent_url: str = Field(description="URL of the agent that defines this format (e.g., 'https://creatives.adcontextprotocol.org' for standard formats, or 'https://publisher.com/.well-known/adcp/sales' for custom formats)")
|
|
39
|
-
id: str = Field(description="Format identifier within the agent's namespace (e.g., 'display_300x250', 'video_standard_30s')")
|
|
40
|
-
|
|
41
|
-
@field_validator("id")
|
|
42
|
-
@classmethod
|
|
43
|
-
def validate_id_pattern(cls, v: str) -> str:
|
|
44
|
-
"""Validate format ID contains only alphanumeric characters, hyphens, and underscores."""
|
|
45
|
-
if not re.match(r"^[a-zA-Z0-9_-]+$", v):
|
|
46
|
-
raise ValueError(
|
|
47
|
-
f"Invalid format ID: {v!r}. Must contain only alphanumeric characters, hyphens, and underscores"
|
|
48
|
-
)
|
|
49
|
-
return v
|
|
50
|
-
|
|
51
|
-
|
|
52
35
|
class Product(BaseModel):
|
|
53
36
|
"""Represents available advertising inventory"""
|
|
54
37
|
|
|
@@ -68,6 +51,8 @@ class Product(BaseModel):
|
|
|
68
51
|
is_custom: bool | None = Field(None, description="Whether this is a custom product")
|
|
69
52
|
brief_relevance: str | None = Field(None, description="Explanation of why this product matches the brief (only included when brief is provided)")
|
|
70
53
|
expires_at: str | None = Field(None, description="Expiration timestamp for custom products")
|
|
54
|
+
product_card: dict[str, Any] | None = Field(None, description="Optional standard visual card (300x400px) for displaying this product in user interfaces. Can be rendered via preview_creative or pre-generated.")
|
|
55
|
+
product_card_detailed: dict[str, Any] | None = Field(None, description="Optional detailed card with carousel and full specifications. Provides rich product presentation similar to media kit pages.")
|
|
71
56
|
|
|
72
57
|
|
|
73
58
|
class MediaBuy(BaseModel):
|
|
@@ -151,7 +136,7 @@ class Format(BaseModel):
|
|
|
151
136
|
format_id: FormatId = Field(description="Structured format identifier with agent URL and format name")
|
|
152
137
|
name: str = Field(description="Human-readable format name")
|
|
153
138
|
description: str | None = Field(None, description="Plain text explanation of what this format does and what assets it requires")
|
|
154
|
-
preview_image: str | None = Field(None, description="Optional preview image URL for format browsing/discovery UI. Should be 400x300px (4:3 aspect ratio) PNG or JPG. Used as thumbnail/card image in format browsers.")
|
|
139
|
+
preview_image: str | None = Field(None, description="DEPRECATED: Use format_card instead. Optional preview image URL for format browsing/discovery UI. Should be 400x300px (4:3 aspect ratio) PNG or JPG. Used as thumbnail/card image in format browsers. This field is maintained for backward compatibility but format_card provides a more flexible, structured approach.")
|
|
155
140
|
example_url: str | None = Field(None, description="Optional URL to showcase page with examples and interactive demos of this format")
|
|
156
141
|
type: Literal["audio", "video", "display", "native", "dooh", "rich_media", "universal"] = Field(description="Media type of this format - determines rendering method and asset requirements")
|
|
157
142
|
renders: list[dict[str, Any]] | None = Field(None, description="Specification of rendered pieces for this format. Most formats produce a single render. Companion ad formats (video + banner), adaptive formats, and multi-placement formats produce multiple renders. Each render specifies its role and dimensions.")
|
|
@@ -159,6 +144,8 @@ class Format(BaseModel):
|
|
|
159
144
|
delivery: dict[str, Any] | None = Field(None, description="Delivery method specifications (e.g., hosted, VAST, third-party tags)")
|
|
160
145
|
supported_macros: list[str] | None = Field(None, description="List of universal macros supported by this format (e.g., MEDIA_BUY_ID, CACHEBUSTER, DEVICE_ID). Used for validation and developer tooling.")
|
|
161
146
|
output_format_ids: list[FormatId] | None = Field(None, description="For generative formats: array of format IDs that this format can generate. When a format accepts inputs like brand_manifest and message, this specifies what concrete output formats can be produced (e.g., a generative banner format might output standard image banner formats).")
|
|
147
|
+
format_card: dict[str, Any] | None = Field(None, description="Optional standard visual card (300x400px) for displaying this format in user interfaces. Can be rendered via preview_creative or pre-generated.")
|
|
148
|
+
format_card_detailed: dict[str, Any] | None = Field(None, description="Optional detailed card with carousel and full specifications. Provides rich format documentation similar to ad spec pages.")
|
|
162
149
|
|
|
163
150
|
|
|
164
151
|
class Targeting(BaseModel):
|
|
@@ -469,15 +456,6 @@ class ListCreativesRequest(BaseModel):
|
|
|
469
456
|
fields: list[Literal["creative_id", "name", "format", "status", "created_date", "updated_date", "tags", "assignments", "performance", "sub_assets"]] | None = Field(None, description="Specific fields to include in response (omit for all fields)")
|
|
470
457
|
|
|
471
458
|
|
|
472
|
-
class PreviewCreativeRequest(BaseModel):
|
|
473
|
-
"""Request to generate a preview of a creative manifest in a specific format. The creative_manifest should include all assets required by the format (e.g., promoted_offerings for generative formats)."""
|
|
474
|
-
|
|
475
|
-
format_id: FormatId = Field(description="Format identifier for rendering the preview")
|
|
476
|
-
creative_manifest: CreativeManifest = Field(description="Complete creative manifest with all required assets (including promoted_offerings if required by the format)")
|
|
477
|
-
inputs: list[dict[str, Any]] | None = Field(None, description="Array of input sets for generating multiple preview variants. Each input set defines macros and context values for one preview rendering. If not provided, creative agent will generate default previews.")
|
|
478
|
-
template_id: str | None = Field(None, description="Specific template ID for custom format rendering")
|
|
479
|
-
|
|
480
|
-
|
|
481
459
|
class ProvidePerformanceFeedbackRequest(BaseModel):
|
|
482
460
|
"""Request payload for provide_performance_feedback task"""
|
|
483
461
|
|
|
@@ -599,14 +577,6 @@ class ListCreativesResponse(BaseModel):
|
|
|
599
577
|
status_summary: dict[str, Any] | None = Field(None, description="Breakdown of creatives by status")
|
|
600
578
|
|
|
601
579
|
|
|
602
|
-
class PreviewCreativeResponse(BaseModel):
|
|
603
|
-
"""Response containing preview links for a creative. Each preview URL returns an HTML page that can be embedded in an iframe to display the rendered creative."""
|
|
604
|
-
|
|
605
|
-
previews: list[dict[str, Any]] = Field(description="Array of preview variants. Each preview corresponds to an input set from the request. If no inputs were provided, returns a single default preview.")
|
|
606
|
-
interactive_url: str | None = Field(None, description="Optional URL to an interactive testing page that shows all preview variants with controls to switch between them, modify macro values, and test different scenarios.")
|
|
607
|
-
expires_at: str = Field(description="ISO 8601 timestamp when preview links expire")
|
|
608
|
-
|
|
609
|
-
|
|
610
580
|
class ProvidePerformanceFeedbackResponse(BaseModel):
|
|
611
581
|
"""Response payload for provide_performance_feedback task"""
|
|
612
582
|
|
|
@@ -630,3 +600,56 @@ class UpdateMediaBuyResponse(BaseModel):
|
|
|
630
600
|
affected_packages: list[dict[str, Any]] | None = Field(None, description="Array of packages that were modified")
|
|
631
601
|
errors: list[Error] | None = Field(None, description="Task-specific errors and warnings (e.g., partial update failures)")
|
|
632
602
|
|
|
603
|
+
|
|
604
|
+
|
|
605
|
+
# ============================================================================
|
|
606
|
+
# CUSTOM IMPLEMENTATIONS (override type aliases from generator)
|
|
607
|
+
# ============================================================================
|
|
608
|
+
# The simple code generator produces type aliases (e.g., PreviewCreativeRequest = Any)
|
|
609
|
+
# for complex schemas that use oneOf. We override them here with proper Pydantic classes
|
|
610
|
+
# to maintain type safety and enable batch API support.
|
|
611
|
+
|
|
612
|
+
|
|
613
|
+
class FormatId(BaseModel):
|
|
614
|
+
"""Structured format identifier with agent URL and format name"""
|
|
615
|
+
|
|
616
|
+
agent_url: str = Field(description="URL of the agent that defines this format (e.g., 'https://creatives.adcontextprotocol.org' for standard formats, or 'https://publisher.com/.well-known/adcp/sales' for custom formats)")
|
|
617
|
+
id: str = Field(description="Format identifier within the agent's namespace (e.g., 'display_300x250', 'video_standard_30s')")
|
|
618
|
+
|
|
619
|
+
@field_validator("id")
|
|
620
|
+
@classmethod
|
|
621
|
+
def validate_id_pattern(cls, v: str) -> str:
|
|
622
|
+
"""Validate format ID contains only alphanumeric characters, hyphens, and underscores."""
|
|
623
|
+
if not re.match(r"^[a-zA-Z0-9_-]+$", v):
|
|
624
|
+
raise ValueError(
|
|
625
|
+
f"Invalid format ID: {v!r}. Must contain only alphanumeric characters, hyphens, and underscores"
|
|
626
|
+
)
|
|
627
|
+
return v
|
|
628
|
+
|
|
629
|
+
|
|
630
|
+
class PreviewCreativeRequest(BaseModel):
|
|
631
|
+
"""Request to generate a preview of a creative manifest. Supports single or batch mode."""
|
|
632
|
+
|
|
633
|
+
# Single mode fields
|
|
634
|
+
format_id: FormatId | None = Field(default=None, description="Format identifier for rendering the preview (single mode)")
|
|
635
|
+
creative_manifest: CreativeManifest | None = Field(default=None, description="Complete creative manifest with all required assets (single mode)")
|
|
636
|
+
inputs: list[dict[str, Any]] | None = Field(default=None, description="Array of input sets for generating multiple preview variants")
|
|
637
|
+
template_id: str | None = Field(default=None, description="Specific template ID for custom format rendering")
|
|
638
|
+
|
|
639
|
+
# Batch mode field
|
|
640
|
+
requests: list[dict[str, Any]] | None = Field(default=None, description="Array of preview requests for batch processing (1-50 items)")
|
|
641
|
+
|
|
642
|
+
# Output format (applies to both modes)
|
|
643
|
+
output_format: Literal["url", "html"] | None = Field(default="url", description="Output format: 'url' for iframe URLs, 'html' for direct embedding")
|
|
644
|
+
|
|
645
|
+
|
|
646
|
+
class PreviewCreativeResponse(BaseModel):
|
|
647
|
+
"""Response containing preview links for one or more creatives. Format matches the request: single preview response for single requests, batch results for batch requests."""
|
|
648
|
+
|
|
649
|
+
# Single mode fields
|
|
650
|
+
previews: list[dict[str, Any]] | None = Field(default=None, description="Array of preview variants (single mode)")
|
|
651
|
+
interactive_url: str | None = Field(default=None, description="Optional URL to interactive testing page (single mode)")
|
|
652
|
+
expires_at: str | None = Field(default=None, description="ISO 8601 timestamp when preview links expire (single mode)")
|
|
653
|
+
|
|
654
|
+
# Batch mode field
|
|
655
|
+
results: list[dict[str, Any]] | None = Field(default=None, description="Array of preview results for batch processing")
|