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
458 lines (387 loc) · 16.1 KB
/
grpc_handler.py
File metadata and controls
458 lines (387 loc) · 16.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
# ruff: noqa: N802
import logging
from abc import ABC, abstractmethod
from collections.abc import AsyncIterable, Awaitable, Callable
from typing import TypeVar
try:
import grpc # type: ignore[reportMissingModuleSource]
import grpc.aio # type: ignore[reportMissingModuleSource]
from grpc_status import rpc_status
except ImportError as e:
raise ImportError(
'GrpcHandler requires grpcio, grpcio-tools, and grpcio-status to be installed. '
'Install with: '
"'pip install a2a-sdk[grpc]'"
) from e
from google.protobuf import any_pb2, empty_pb2, message
from google.rpc import error_details_pb2, status_pb2
import a2a.types.a2a_pb2_grpc as a2a_grpc
from a2a import types
from a2a.auth.user import UnauthenticatedUser, User
from a2a.extensions.common import (
HTTP_EXTENSION_HEADER,
get_requested_extensions,
)
from a2a.server.context import ServerCallContext
from a2a.server.request_handlers.request_handler import RequestHandler
from a2a.types import a2a_pb2
from a2a.types.a2a_pb2 import AgentCard
from a2a.utils import proto_utils
from a2a.utils.errors import A2A_ERROR_REASONS, A2AError, TaskNotFoundError
from a2a.utils.helpers import maybe_await, validate
from a2a.utils.proto_utils import validation_errors_to_bad_request
logger = logging.getLogger(__name__)
class GrpcContextBuilder(ABC):
"""Interface for building ServerCallContext from gRPC context."""
@abstractmethod
def build(self, context: grpc.aio.ServicerContext) -> ServerCallContext:
"""Builds a ServerCallContext from a gRPC ServicerContext."""
class DefaultGrpcContextBuilder(GrpcContextBuilder):
"""Default implementation of GrpcContextBuilder."""
def build(self, context: grpc.aio.ServicerContext) -> ServerCallContext:
"""Builds a ServerCallContext from a gRPC ServicerContext."""
state = {'grpc_context': context}
return ServerCallContext(
user=self.build_user(context),
state=state,
requested_extensions=get_requested_extensions(
_get_metadata_value(context, HTTP_EXTENSION_HEADER)
),
)
def build_user(self, context: grpc.aio.ServicerContext) -> User:
"""Builds a User from a gRPC ServicerContext."""
return UnauthenticatedUser()
def _get_metadata_value(
context: grpc.aio.ServicerContext, key: str
) -> list[str]:
md = context.invocation_metadata()
if md is None:
return []
lower_key = key.lower()
return [
e if isinstance(e, str) else e.decode('utf-8')
for k, e in md
if k.lower() == lower_key
]
_ERROR_CODE_MAP = {
types.InvalidRequestError: grpc.StatusCode.INVALID_ARGUMENT,
types.MethodNotFoundError: grpc.StatusCode.NOT_FOUND,
types.InvalidParamsError: grpc.StatusCode.INVALID_ARGUMENT,
types.InternalError: grpc.StatusCode.INTERNAL,
types.TaskNotFoundError: grpc.StatusCode.NOT_FOUND,
types.TaskNotCancelableError: grpc.StatusCode.FAILED_PRECONDITION,
types.PushNotificationNotSupportedError: grpc.StatusCode.UNIMPLEMENTED,
types.UnsupportedOperationError: grpc.StatusCode.UNIMPLEMENTED,
types.ContentTypeNotSupportedError: grpc.StatusCode.INVALID_ARGUMENT,
types.InvalidAgentResponseError: grpc.StatusCode.INTERNAL,
types.ExtendedAgentCardNotConfiguredError: grpc.StatusCode.FAILED_PRECONDITION,
types.ExtensionSupportRequiredError: grpc.StatusCode.FAILED_PRECONDITION,
types.VersionNotSupportedError: grpc.StatusCode.UNIMPLEMENTED,
}
TResponse = TypeVar('TResponse')
class GrpcHandler(a2a_grpc.A2AServiceServicer):
"""Maps incoming gRPC requests to the appropriate request handler method."""
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 GrpcHandler.
Args:
agent_card: The AgentCard describing the agent's capabilities.
request_handler: The underlying `RequestHandler` instance to
delegate requests to.
context_builder: The GrpcContextBuilder used to construct the
ServerCallContext passed to the request_handler. If None the
DefaultGrpcContextBuilder is used.
card_modifier: An optional callback to dynamically modify the public
agent card before it is served.
"""
self.agent_card = agent_card
self.request_handler = request_handler
self._context_builder = context_builder or DefaultGrpcContextBuilder()
self.card_modifier = card_modifier
async def _handle_unary(
self,
request: message.Message,
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._build_call_context(context, request)
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,
request: message.Message,
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._build_call_context(context, request)
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)
async def SendMessage(
self,
request: a2a_pb2.SendMessageRequest,
context: grpc.aio.ServicerContext,
) -> a2a_pb2.SendMessageResponse:
"""Handles the 'SendMessage' gRPC method."""
async def _handler(
server_context: ServerCallContext,
) -> a2a_pb2.SendMessageResponse:
task_or_message = await self.request_handler.on_message_send(
request, server_context
)
if isinstance(task_or_message, a2a_pb2.Task):
return a2a_pb2.SendMessageResponse(task=task_or_message)
return a2a_pb2.SendMessageResponse(message=task_or_message)
return await self._handle_unary(
request, context, _handler, a2a_pb2.SendMessageResponse()
)
async def SendStreamingMessage(
self,
request: a2a_pb2.SendMessageRequest,
context: grpc.aio.ServicerContext,
) -> AsyncIterable[a2a_pb2.StreamResponse]:
"""Handles the 'StreamMessage' gRPC method."""
@validate(
lambda _: self.agent_card.capabilities.streaming,
'Streaming is not supported by the agent',
)
async def _handler(
server_context: ServerCallContext,
) -> AsyncIterable[a2a_pb2.StreamResponse]:
async for event in self.request_handler.on_message_send_stream(
request, server_context
):
yield proto_utils.to_stream_response(event)
async for item in self._handle_stream(request, context, _handler):
yield item
async def CancelTask(
self,
request: a2a_pb2.CancelTaskRequest,
context: grpc.aio.ServicerContext,
) -> a2a_pb2.Task:
"""Handles the 'CancelTask' gRPC method."""
async def _handler(server_context: ServerCallContext) -> a2a_pb2.Task:
task = await self.request_handler.on_cancel_task(
request, server_context
)
if task:
return task
raise TaskNotFoundError
return await self._handle_unary(
request, context, _handler, a2a_pb2.Task()
)
async def SubscribeToTask(
self,
request: a2a_pb2.SubscribeToTaskRequest,
context: grpc.aio.ServicerContext,
) -> AsyncIterable[a2a_pb2.StreamResponse]:
"""Handles the 'SubscribeToTask' gRPC method."""
@validate(
lambda _: self.agent_card.capabilities.streaming,
'Streaming is not supported by the agent',
)
async def _handler(
server_context: ServerCallContext,
) -> AsyncIterable[a2a_pb2.StreamResponse]:
async for event in self.request_handler.on_subscribe_to_task(
request, server_context
):
yield proto_utils.to_stream_response(event)
async for item in self._handle_stream(request, context, _handler):
yield item
async def GetTaskPushNotificationConfig(
self,
request: a2a_pb2.GetTaskPushNotificationConfigRequest,
context: grpc.aio.ServicerContext,
) -> a2a_pb2.TaskPushNotificationConfig:
"""Handles the 'GetTaskPushNotificationConfig' gRPC method."""
async def _handler(
server_context: ServerCallContext,
) -> a2a_pb2.TaskPushNotificationConfig:
return (
await self.request_handler.on_get_task_push_notification_config(
request, server_context
)
)
return await self._handle_unary(
request, context, _handler, a2a_pb2.TaskPushNotificationConfig()
)
async def CreateTaskPushNotificationConfig(
self,
request: a2a_pb2.TaskPushNotificationConfig,
context: grpc.aio.ServicerContext,
) -> a2a_pb2.TaskPushNotificationConfig:
"""Handles the 'CreateTaskPushNotificationConfig' gRPC method."""
@validate(
lambda _: self.agent_card.capabilities.push_notifications,
'Push notifications are not supported by the agent',
)
async def _handler(
server_context: ServerCallContext,
) -> a2a_pb2.TaskPushNotificationConfig:
return await self.request_handler.on_create_task_push_notification_config(
request, server_context
)
return await self._handle_unary(
request, context, _handler, a2a_pb2.TaskPushNotificationConfig()
)
async def ListTaskPushNotificationConfigs(
self,
request: a2a_pb2.ListTaskPushNotificationConfigsRequest,
context: grpc.aio.ServicerContext,
) -> a2a_pb2.ListTaskPushNotificationConfigsResponse:
"""Handles the 'ListTaskPushNotificationConfig' gRPC method."""
async def _handler(
server_context: ServerCallContext,
) -> a2a_pb2.ListTaskPushNotificationConfigsResponse:
return await self.request_handler.on_list_task_push_notification_configs(
request, server_context
)
return await self._handle_unary(
request,
context,
_handler,
a2a_pb2.ListTaskPushNotificationConfigsResponse(),
)
async def DeleteTaskPushNotificationConfig(
self,
request: a2a_pb2.DeleteTaskPushNotificationConfigRequest,
context: grpc.aio.ServicerContext,
) -> empty_pb2.Empty:
"""Handles the 'DeleteTaskPushNotificationConfig' gRPC method."""
async def _handler(
server_context: ServerCallContext,
) -> empty_pb2.Empty:
await self.request_handler.on_delete_task_push_notification_config(
request, server_context
)
return empty_pb2.Empty()
return await self._handle_unary(
request, context, _handler, empty_pb2.Empty()
)
async def GetTask(
self,
request: a2a_pb2.GetTaskRequest,
context: grpc.aio.ServicerContext,
) -> a2a_pb2.Task:
"""Handles the 'GetTask' gRPC method."""
async def _handler(server_context: ServerCallContext) -> a2a_pb2.Task:
task = await self.request_handler.on_get_task(
request, server_context
)
if task:
return task
raise TaskNotFoundError
return await self._handle_unary(
request, context, _handler, a2a_pb2.Task()
)
async def ListTasks(
self,
request: a2a_pb2.ListTasksRequest,
context: grpc.aio.ServicerContext,
) -> a2a_pb2.ListTasksResponse:
"""Handles the 'ListTasks' gRPC method."""
async def _handler(
server_context: ServerCallContext,
) -> a2a_pb2.ListTasksResponse:
return await self.request_handler.on_list_tasks(
request, server_context
)
return await self._handle_unary(
request, context, _handler, a2a_pb2.ListTasksResponse()
)
async def GetExtendedAgentCard(
self,
request: a2a_pb2.GetExtendedAgentCardRequest,
context: grpc.aio.ServicerContext,
) -> a2a_pb2.AgentCard:
"""Get the extended agent card for the agent served."""
card_to_serve = self.agent_card
if self.card_modifier:
card_to_serve = await maybe_await(self.card_modifier(card_to_serve))
return card_to_serve
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:
reason = A2A_ERROR_REASONS.get(type(error), 'UNKNOWN_ERROR')
error_info = error_details_pb2.ErrorInfo(
reason=reason,
domain='a2a-protocol.org',
)
status_code = code.value[0]
error_msg = (
error.message if hasattr(error, 'message') else str(error)
)
# Create standard Status with ErrorInfo for all A2A errors
status = status_pb2.Status(code=status_code, message=error_msg)
error_info_detail = any_pb2.Any()
error_info_detail.Pack(error_info)
status.details.append(error_info_detail)
# Append structured field violations for validation errors
if (
isinstance(error, types.InvalidParamsError)
and error.data
and error.data.get('errors')
):
bad_request_detail = any_pb2.Any()
bad_request_detail.Pack(
validation_errors_to_bad_request(error.data['errors'])
)
status.details.append(bad_request_detail)
# Use grpc_status to safely generate standard trailing metadata
rich_status = rpc_status.to_status(status)
new_metadata: list[tuple[str, str | bytes]] = []
trailing = context.trailing_metadata()
if trailing:
for k, v in trailing:
new_metadata.append((str(k), v))
for k, v in rich_status.trailing_metadata:
new_metadata.append((str(k), v))
context.set_trailing_metadata(tuple(new_metadata))
await context.abort(rich_status.code, rich_status.details)
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)
]
)
def _build_call_context(
self,
context: grpc.aio.ServicerContext,
request: message.Message,
) -> ServerCallContext:
server_context = self._context_builder.build(context)
server_context.tenant = getattr(request, 'tenant', '')
return server_context