adcp 1.0.5__tar.gz → 1.2.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.2.0}/PKG-INFO +61 -16
- {adcp-1.0.5 → adcp-1.2.0}/README.md +60 -15
- {adcp-1.0.5 → adcp-1.2.0}/pyproject.toml +1 -1
- {adcp-1.0.5 → adcp-1.2.0}/src/adcp/__init__.py +1 -1
- {adcp-1.0.5 → adcp-1.2.0}/src/adcp/client.py +96 -5
- {adcp-1.0.5 → adcp-1.2.0}/src/adcp/protocols/a2a.py +4 -0
- {adcp-1.0.5 → adcp-1.2.0}/src/adcp/protocols/mcp.py +41 -41
- {adcp-1.0.5 → adcp-1.2.0}/src/adcp/types/core.py +3 -4
- {adcp-1.0.5 → adcp-1.2.0}/src/adcp/types/generated.py +172 -41
- adcp-1.2.0/src/adcp/utils/preview_cache.py +461 -0
- {adcp-1.0.5 → adcp-1.2.0/src/adcp.egg-info}/PKG-INFO +61 -16
- {adcp-1.0.5 → adcp-1.2.0}/src/adcp.egg-info/SOURCES.txt +2 -0
- {adcp-1.0.5 → adcp-1.2.0}/tests/test_client.py +107 -0
- adcp-1.2.0/tests/test_preview_html.py +376 -0
- {adcp-1.0.5 → adcp-1.2.0}/tests/test_protocols.py +113 -0
- {adcp-1.0.5 → adcp-1.2.0}/LICENSE +0 -0
- {adcp-1.0.5 → adcp-1.2.0}/setup.cfg +0 -0
- {adcp-1.0.5 → adcp-1.2.0}/src/adcp/__main__.py +0 -0
- {adcp-1.0.5 → adcp-1.2.0}/src/adcp/config.py +0 -0
- {adcp-1.0.5 → adcp-1.2.0}/src/adcp/exceptions.py +0 -0
- {adcp-1.0.5 → adcp-1.2.0}/src/adcp/protocols/__init__.py +0 -0
- {adcp-1.0.5 → adcp-1.2.0}/src/adcp/protocols/base.py +0 -0
- {adcp-1.0.5 → adcp-1.2.0}/src/adcp/types/__init__.py +0 -0
- {adcp-1.0.5 → adcp-1.2.0}/src/adcp/types/tasks.py +0 -0
- {adcp-1.0.5 → adcp-1.2.0}/src/adcp/utils/__init__.py +0 -0
- {adcp-1.0.5 → adcp-1.2.0}/src/adcp/utils/operation_id.py +0 -0
- {adcp-1.0.5 → adcp-1.2.0}/src/adcp/utils/response_parser.py +0 -0
- {adcp-1.0.5 → adcp-1.2.0}/src/adcp.egg-info/dependency_links.txt +0 -0
- {adcp-1.0.5 → adcp-1.2.0}/src/adcp.egg-info/entry_points.txt +0 -0
- {adcp-1.0.5 → adcp-1.2.0}/src/adcp.egg-info/requires.txt +0 -0
- {adcp-1.0.5 → adcp-1.2.0}/src/adcp.egg-info/top_level.txt +0 -0
- {adcp-1.0.5 → adcp-1.2.0}/tests/test_cli.py +0 -0
- {adcp-1.0.5 → adcp-1.2.0}/tests/test_code_generation.py +0 -0
- {adcp-1.0.5 → adcp-1.2.0}/tests/test_format_id_validation.py +0 -0
- {adcp-1.0.5 → adcp-1.2.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.2.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.2.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."""
|