forked from a2aproject/a2a-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgrpc_handler.py
More file actions
391 lines (345 loc) · 14.3 KB
/
grpc_handler.py
File metadata and controls
391 lines (345 loc) · 14.3 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
# ruff: noqa: N802
import logging
from collections.abc import AsyncIterable, Awaitable, Callable
from typing import TypeVar
import grpc
import grpc.aio
from google.protobuf import empty_pb2
from a2a.compat.v0_3 import (
a2a_v0_3_pb2,
a2a_v0_3_pb2_grpc,
conversions,
proto_utils,
)
from a2a.compat.v0_3 import (
types as types_v03,
)
from a2a.compat.v0_3.request_handler import RequestHandler03
from a2a.extensions.common import HTTP_EXTENSION_HEADER
from a2a.server.context import ServerCallContext
from a2a.server.request_handlers.grpc_handler import (
_ERROR_CODE_MAP,
DefaultGrpcContextBuilder,
GrpcContextBuilder,
)
from a2a.server.request_handlers.request_handler import RequestHandler
from a2a.types.a2a_pb2 import AgentCard
from a2a.utils.errors import A2AError, InvalidParamsError
from a2a.utils.helpers import maybe_await, validate
logger = logging.getLogger(__name__)
TResponse = TypeVar('TResponse')
class CompatGrpcHandler(a2a_v0_3_pb2_grpc.A2AServiceServicer):
"""Backward compatible gRPC handler for A2A v0.3."""
def __init__(
self,
agent_card: AgentCard,
request_handler: RequestHandler,
context_builder: GrpcContextBuilder | None = None,
card_modifier: Callable[[AgentCard], Awaitable[AgentCard] | AgentCard]
| None = None,
):
"""Initializes the CompatGrpcHandler.
Args:
agent_card: The AgentCard describing the agent's capabilities (v1.0).
request_handler: The underlying `RequestHandler` instance to
delegate requests to.
context_builder: Optional custom user builder to extract user from the
gRPC context.
card_modifier: An optional callback to dynamically modify the public
agent card before it is served.
"""
self.agent_card = agent_card
self.handler03 = RequestHandler03(request_handler=request_handler)
self._context_builder = context_builder or DefaultGrpcContextBuilder()
self.card_modifier = card_modifier
async def _handle_unary(
self,
context: grpc.aio.ServicerContext,
handler_func: Callable[[ServerCallContext], Awaitable[TResponse]],
default_response: TResponse,
) -> TResponse:
"""Centralized error handling and context management for unary calls."""
try:
server_context = self._context_builder.build(context)
result = await handler_func(server_context)
self._set_extension_metadata(context, server_context)
except A2AError as e:
await self.abort_context(e, context)
else:
return result
return default_response
async def _handle_stream(
self,
context: grpc.aio.ServicerContext,
handler_func: Callable[[ServerCallContext], AsyncIterable[TResponse]],
) -> AsyncIterable[TResponse]:
"""Centralized error handling and context management for streaming calls."""
try:
server_context = self._context_builder.build(context)
async for item in handler_func(server_context):
yield item
self._set_extension_metadata(context, server_context)
except A2AError as e:
await self.abort_context(e, context)
def _extract_task_id(self, resource_name: str) -> str:
"""Extracts task_id from resource name."""
m = proto_utils.TASK_NAME_MATCH.match(resource_name)
if not m:
raise InvalidParamsError(message=f'No task for {resource_name}')
return m.group(1)
def _extract_task_and_config_id(
self, resource_name: str
) -> tuple[str, str]:
"""Extracts task_id and config_id from resource name."""
m = proto_utils.TASK_PUSH_CONFIG_NAME_MATCH.match(resource_name)
if not m:
raise InvalidParamsError(
message=f'Bad resource name {resource_name}'
)
return m.group(1), m.group(2)
async def abort_context(
self, error: A2AError, context: grpc.aio.ServicerContext
) -> None:
"""Sets the grpc errors appropriately in the context."""
code = _ERROR_CODE_MAP.get(type(error))
if code:
await context.abort(
code,
f'{type(error).__name__}: {error.message}',
)
else:
await context.abort(
grpc.StatusCode.UNKNOWN,
f'Unknown error type: {error}',
)
def _set_extension_metadata(
self,
context: grpc.aio.ServicerContext,
server_context: ServerCallContext,
) -> None:
if server_context.activated_extensions:
context.set_trailing_metadata(
[
(HTTP_EXTENSION_HEADER.lower(), e)
for e in sorted(server_context.activated_extensions)
]
)
async def SendMessage(
self,
request: a2a_v0_3_pb2.SendMessageRequest,
context: grpc.aio.ServicerContext,
) -> a2a_v0_3_pb2.SendMessageResponse:
"""Handles the 'SendMessage' gRPC method (v0.3)."""
async def _handler(
server_context: ServerCallContext,
) -> a2a_v0_3_pb2.SendMessageResponse:
req_v03 = types_v03.SendMessageRequest(
id=0, params=proto_utils.FromProto.message_send_params(request)
)
result = await self.handler03.on_message_send(
req_v03, server_context
)
if isinstance(result, types_v03.Task):
return a2a_v0_3_pb2.SendMessageResponse(
task=proto_utils.ToProto.task(result)
)
return a2a_v0_3_pb2.SendMessageResponse(
msg=proto_utils.ToProto.message(result)
)
return await self._handle_unary(
context, _handler, a2a_v0_3_pb2.SendMessageResponse()
)
async def SendStreamingMessage(
self,
request: a2a_v0_3_pb2.SendMessageRequest,
context: grpc.aio.ServicerContext,
) -> AsyncIterable[a2a_v0_3_pb2.StreamResponse]:
"""Handles the 'SendStreamingMessage' gRPC method (v0.3)."""
@validate(
lambda _: self.agent_card.capabilities.streaming,
'Streaming is not supported by the agent',
)
async def _handler(
server_context: ServerCallContext,
) -> AsyncIterable[a2a_v0_3_pb2.StreamResponse]:
req_v03 = types_v03.SendMessageRequest(
id=0, params=proto_utils.FromProto.message_send_params(request)
)
async for v03_stream_resp in self.handler03.on_message_send_stream(
req_v03, server_context
):
yield proto_utils.ToProto.stream_response(
v03_stream_resp.result
)
async for item in self._handle_stream(context, _handler):
yield item
async def GetTask(
self,
request: a2a_v0_3_pb2.GetTaskRequest,
context: grpc.aio.ServicerContext,
) -> a2a_v0_3_pb2.Task:
"""Handles the 'GetTask' gRPC method (v0.3)."""
async def _handler(
server_context: ServerCallContext,
) -> a2a_v0_3_pb2.Task:
req_v03 = types_v03.GetTaskRequest(
id=0, params=proto_utils.FromProto.task_query_params(request)
)
task = await self.handler03.on_get_task(req_v03, server_context)
return proto_utils.ToProto.task(task)
return await self._handle_unary(context, _handler, a2a_v0_3_pb2.Task())
async def CancelTask(
self,
request: a2a_v0_3_pb2.CancelTaskRequest,
context: grpc.aio.ServicerContext,
) -> a2a_v0_3_pb2.Task:
"""Handles the 'CancelTask' gRPC method (v0.3)."""
async def _handler(
server_context: ServerCallContext,
) -> a2a_v0_3_pb2.Task:
req_v03 = types_v03.CancelTaskRequest(
id=0, params=proto_utils.FromProto.task_id_params(request)
)
task = await self.handler03.on_cancel_task(req_v03, server_context)
return proto_utils.ToProto.task(task)
return await self._handle_unary(context, _handler, a2a_v0_3_pb2.Task())
async def TaskSubscription(
self,
request: a2a_v0_3_pb2.TaskSubscriptionRequest,
context: grpc.aio.ServicerContext,
) -> AsyncIterable[a2a_v0_3_pb2.StreamResponse]:
"""Handles the 'TaskSubscription' gRPC method (v0.3)."""
@validate(
lambda _: self.agent_card.capabilities.streaming,
'Streaming is not supported by the agent',
)
async def _handler(
server_context: ServerCallContext,
) -> AsyncIterable[a2a_v0_3_pb2.StreamResponse]:
req_v03 = types_v03.TaskResubscriptionRequest(
id=0, params=proto_utils.FromProto.task_id_params(request)
)
async for v03_stream_resp in self.handler03.on_subscribe_to_task(
req_v03, server_context
):
yield proto_utils.ToProto.stream_response(
v03_stream_resp.result
)
async for item in self._handle_stream(context, _handler):
yield item
async def CreateTaskPushNotificationConfig(
self,
request: a2a_v0_3_pb2.CreateTaskPushNotificationConfigRequest,
context: grpc.aio.ServicerContext,
) -> a2a_v0_3_pb2.TaskPushNotificationConfig:
"""Handles the 'CreateTaskPushNotificationConfig' gRPC method (v0.3)."""
@validate(
lambda _: self.agent_card.capabilities.push_notifications,
'Push notifications are not supported by the agent',
)
async def _handler(
server_context: ServerCallContext,
) -> a2a_v0_3_pb2.TaskPushNotificationConfig:
req_v03 = types_v03.SetTaskPushNotificationConfigRequest(
id=0,
params=proto_utils.FromProto.task_push_notification_config_request(
request
),
)
res_v03 = (
await self.handler03.on_create_task_push_notification_config(
req_v03, server_context
)
)
return proto_utils.ToProto.task_push_notification_config(res_v03)
return await self._handle_unary(
context, _handler, a2a_v0_3_pb2.TaskPushNotificationConfig()
)
async def GetTaskPushNotificationConfig(
self,
request: a2a_v0_3_pb2.GetTaskPushNotificationConfigRequest,
context: grpc.aio.ServicerContext,
) -> a2a_v0_3_pb2.TaskPushNotificationConfig:
"""Handles the 'GetTaskPushNotificationConfig' gRPC method (v0.3)."""
async def _handler(
server_context: ServerCallContext,
) -> a2a_v0_3_pb2.TaskPushNotificationConfig:
task_id, config_id = self._extract_task_and_config_id(request.name)
req_v03 = types_v03.GetTaskPushNotificationConfigRequest(
id=0,
params=types_v03.GetTaskPushNotificationConfigParams(
id=task_id, push_notification_config_id=config_id
),
)
res_v03 = await self.handler03.on_get_task_push_notification_config(
req_v03, server_context
)
return proto_utils.ToProto.task_push_notification_config(res_v03)
return await self._handle_unary(
context, _handler, a2a_v0_3_pb2.TaskPushNotificationConfig()
)
async def ListTaskPushNotificationConfig(
self,
request: a2a_v0_3_pb2.ListTaskPushNotificationConfigRequest,
context: grpc.aio.ServicerContext,
) -> a2a_v0_3_pb2.ListTaskPushNotificationConfigResponse:
"""Handles the 'ListTaskPushNotificationConfig' gRPC method (v0.3)."""
async def _handler(
server_context: ServerCallContext,
) -> a2a_v0_3_pb2.ListTaskPushNotificationConfigResponse:
task_id = self._extract_task_id(request.parent)
req_v03 = types_v03.ListTaskPushNotificationConfigRequest(
id=0,
params=types_v03.ListTaskPushNotificationConfigParams(
id=task_id
),
)
res_v03 = (
await self.handler03.on_list_task_push_notification_configs(
req_v03, server_context
)
)
return a2a_v0_3_pb2.ListTaskPushNotificationConfigResponse(
configs=[
proto_utils.ToProto.task_push_notification_config(c)
for c in res_v03
]
)
return await self._handle_unary(
context,
_handler,
a2a_v0_3_pb2.ListTaskPushNotificationConfigResponse(),
)
async def GetAgentCard(
self,
request: a2a_v0_3_pb2.GetAgentCardRequest,
context: grpc.aio.ServicerContext,
) -> a2a_v0_3_pb2.AgentCard:
"""Get the agent card for the agent served (v0.3)."""
card_to_serve = self.agent_card
if self.card_modifier:
card_to_serve = await maybe_await(self.card_modifier(card_to_serve))
return proto_utils.ToProto.agent_card(
conversions.to_compat_agent_card(card_to_serve)
)
async def DeleteTaskPushNotificationConfig(
self,
request: a2a_v0_3_pb2.DeleteTaskPushNotificationConfigRequest,
context: grpc.aio.ServicerContext,
) -> empty_pb2.Empty:
"""Handles the 'DeleteTaskPushNotificationConfig' gRPC method (v0.3)."""
async def _handler(
server_context: ServerCallContext,
) -> empty_pb2.Empty:
task_id, config_id = self._extract_task_and_config_id(request.name)
req_v03 = types_v03.DeleteTaskPushNotificationConfigRequest(
id=0,
params=types_v03.DeleteTaskPushNotificationConfigParams(
id=task_id, push_notification_config_id=config_id
),
)
await self.handler03.on_delete_task_push_notification_config(
req_v03, server_context
)
return empty_pb2.Empty()
return await self._handle_unary(context, _handler, empty_pb2.Empty())