forked from a2aproject/a2a-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjsonrpc_app.py
More file actions
489 lines (430 loc) · 17.2 KB
/
jsonrpc_app.py
File metadata and controls
489 lines (430 loc) · 17.2 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
import contextlib
import json
import logging
import traceback
from abc import ABC, abstractmethod
from collections.abc import AsyncGenerator
from typing import Any
from fastapi import FastAPI
from pydantic import ValidationError
from sse_starlette.sse import EventSourceResponse
from starlette.applications import Starlette
from starlette.authentication import BaseUser
from starlette.exceptions import HTTPException
from starlette.requests import Request
from starlette.responses import JSONResponse, Response
from starlette.status import HTTP_413_REQUEST_ENTITY_TOO_LARGE
from a2a.auth.user import UnauthenticatedUser
from a2a.auth.user import User as A2AUser
from a2a.extensions.common import HTTP_EXTENSION_HEADER
from a2a.server.context import ServerCallContext
from a2a.server.request_handlers.jsonrpc_handler import JSONRPCHandler
from a2a.server.request_handlers.request_handler import RequestHandler
from a2a.types import (
A2AError,
A2ARequest,
AgentCard,
CancelTaskRequest,
DeleteTaskPushNotificationConfigRequest,
GetTaskPushNotificationConfigRequest,
GetTaskRequest,
InternalError,
InvalidRequestError,
JSONParseError,
JSONRPCError,
JSONRPCErrorResponse,
JSONRPCResponse,
ListTaskPushNotificationConfigRequest,
SendMessageRequest,
SendStreamingMessageRequest,
SendStreamingMessageResponse,
SetTaskPushNotificationConfigRequest,
TaskResubscriptionRequest,
UnsupportedOperationError,
)
from a2a.utils.constants import (
AGENT_CARD_WELL_KNOWN_PATH,
DEFAULT_RPC_URL,
EXTENDED_AGENT_CARD_PATH,
)
from a2a.utils.errors import MethodNotImplementedError
logger = logging.getLogger(__name__)
class StarletteUserProxy(A2AUser):
"""Adapts the Starlette User class to the A2A user representation."""
def __init__(self, user: BaseUser):
self._user = user
@property
def is_authenticated(self) -> bool:
"""Returns whether the current user is authenticated."""
return self._user.is_authenticated
@property
def user_name(self) -> str:
"""Returns the user name of the current user."""
return self._user.display_name
class CallContextBuilder(ABC):
"""A class for building ServerCallContexts using the Starlette Request."""
@abstractmethod
def build(self, request: Request) -> ServerCallContext:
"""Builds a ServerCallContext from a Starlette Request."""
class DefaultCallContextBuilder(CallContextBuilder):
"""A default implementation of CallContextBuilder."""
def build(self, request: Request) -> ServerCallContext:
"""Builds a ServerCallContext from a Starlette Request.
Args:
request: The incoming Starlette Request object.
Returns:
A ServerCallContext instance populated with user and state
information from the request.
"""
user: A2AUser = UnauthenticatedUser()
state = {}
with contextlib.suppress(Exception):
user = StarletteUserProxy(request.user)
state['auth'] = request.auth
state['headers'] = dict(request.headers)
return ServerCallContext(
user=user,
state=state,
requested_extensions={
stripped
for h in request.headers.getlist(HTTP_EXTENSION_HEADER)
for ext in h.split(',')
if (stripped := ext.strip())
},
)
class JSONRPCApplication(ABC):
"""Base class for A2A JSONRPC applications.
Handles incoming JSON-RPC requests, routes them to the appropriate
handler methods, and manages response generation including Server-Sent Events
(SSE).
"""
def __init__(
self,
agent_card: AgentCard,
http_handler: RequestHandler,
extended_agent_card: AgentCard | None = None,
context_builder: CallContextBuilder | None = None,
) -> None:
"""Initializes the A2AStarletteApplication.
Args:
agent_card: The AgentCard describing the agent's capabilities.
http_handler: The handler instance responsible for processing A2A
requests via http.
extended_agent_card: An optional, distinct AgentCard to be served
at the authenticated extended card endpoint.
context_builder: The CallContextBuilder used to construct the
ServerCallContext passed to the http_handler. If None, no
ServerCallContext is passed.
"""
self.agent_card = agent_card
self.extended_agent_card = extended_agent_card
self.handler = JSONRPCHandler(
agent_card=agent_card, request_handler=http_handler
)
if (
self.agent_card.supportsAuthenticatedExtendedCard
and self.extended_agent_card is None
):
logger.error(
'AgentCard.supportsAuthenticatedExtendedCard is True, but no extended_agent_card was provided. The /agent/authenticatedExtendedCard endpoint will return 404.'
)
self._context_builder = context_builder or DefaultCallContextBuilder()
def _generate_error_response(
self, request_id: str | int | None, error: JSONRPCError | A2AError
) -> JSONResponse:
"""Creates a Starlette JSONResponse for a JSON-RPC error.
Logs the error based on its type.
Args:
request_id: The ID of the request that caused the error.
error: The `JSONRPCError` or `A2AError` object.
Returns:
A `JSONResponse` object formatted as a JSON-RPC error response.
"""
error_resp = JSONRPCErrorResponse(
id=request_id,
error=error if isinstance(error, JSONRPCError) else error.root,
)
log_level = (
logging.ERROR
if not isinstance(error, A2AError)
or isinstance(error.root, InternalError)
else logging.WARNING
)
logger.log(
log_level,
f'Request Error (ID: {request_id}): '
f"Code={error_resp.error.code}, Message='{error_resp.error.message}'"
f'{", Data=" + str(error_resp.error.data) if error_resp.error.data else ""}',
)
return JSONResponse(
error_resp.model_dump(mode='json', exclude_none=True),
status_code=200,
)
async def _handle_requests(self, request: Request) -> Response: # noqa: PLR0911
"""Handles incoming POST requests to the main A2A endpoint.
Parses the request body as JSON, validates it against A2A request types,
dispatches it to the appropriate handler method, and returns the response.
Handles JSON parsing errors, validation errors, and other exceptions,
returning appropriate JSON-RPC error responses.
Args:
request: The incoming Starlette Request object.
Returns:
A Starlette Response object (JSONResponse or EventSourceResponse).
Raises:
(Implicitly handled): Various exceptions are caught and converted
into JSON-RPC error responses by this method.
"""
request_id = None
body = None
try:
body = await request.json()
a2a_request = A2ARequest.model_validate(body)
call_context = self._context_builder.build(request)
request_id = a2a_request.root.id
request_obj = a2a_request.root
if isinstance(
request_obj,
TaskResubscriptionRequest | SendStreamingMessageRequest,
):
return await self._process_streaming_request(
request_id, a2a_request, call_context
)
return await self._process_non_streaming_request(
request_id, a2a_request, call_context
)
except MethodNotImplementedError:
traceback.print_exc()
return self._generate_error_response(
request_id, A2AError(root=UnsupportedOperationError())
)
except json.decoder.JSONDecodeError as e:
traceback.print_exc()
return self._generate_error_response(
None, A2AError(root=JSONParseError(message=str(e)))
)
except ValidationError as e:
traceback.print_exc()
return self._generate_error_response(
request_id,
A2AError(root=InvalidRequestError(data=json.loads(e.json()))),
)
except HTTPException as e:
if e.status_code == HTTP_413_REQUEST_ENTITY_TOO_LARGE:
return self._generate_error_response(
request_id,
A2AError(
root=InvalidRequestError(message='Payload too large')
),
)
raise e
except Exception as e:
logger.error(f'Unhandled exception: {e}')
traceback.print_exc()
return self._generate_error_response(
request_id, A2AError(root=InternalError(message=str(e)))
)
async def _process_streaming_request(
self,
request_id: str | int | None,
a2a_request: A2ARequest,
context: ServerCallContext,
) -> Response:
"""Processes streaming requests (message/stream or tasks/resubscribe).
Args:
request_id: The ID of the request.
a2a_request: The validated A2ARequest object.
context: The ServerCallContext for the request.
Returns:
An `EventSourceResponse` object to stream results to the client.
"""
request_obj = a2a_request.root
handler_result: Any = None
if isinstance(
request_obj,
SendStreamingMessageRequest,
):
handler_result = self.handler.on_message_send_stream(
request_obj, context
)
elif isinstance(request_obj, TaskResubscriptionRequest):
handler_result = self.handler.on_resubscribe_to_task(
request_obj, context
)
return self._create_response(context, handler_result)
async def _process_non_streaming_request(
self,
request_id: str | int | None,
a2a_request: A2ARequest,
context: ServerCallContext,
) -> Response:
"""Processes non-streaming requests (message/send, tasks/get, tasks/cancel, tasks/pushNotificationConfig/*).
Args:
request_id: The ID of the request.
a2a_request: The validated A2ARequest object.
context: The ServerCallContext for the request.
Returns:
A `JSONResponse` object containing the result or error.
"""
request_obj = a2a_request.root
handler_result: Any = None
match request_obj:
case SendMessageRequest():
handler_result = await self.handler.on_message_send(
request_obj, context
)
case CancelTaskRequest():
handler_result = await self.handler.on_cancel_task(
request_obj, context
)
case GetTaskRequest():
handler_result = await self.handler.on_get_task(
request_obj, context
)
case SetTaskPushNotificationConfigRequest():
handler_result = (
await self.handler.set_push_notification_config(
request_obj,
context,
)
)
case GetTaskPushNotificationConfigRequest():
handler_result = (
await self.handler.get_push_notification_config(
request_obj,
context,
)
)
case ListTaskPushNotificationConfigRequest():
handler_result = (
await self.handler.list_push_notification_config(
request_obj,
context,
)
)
case DeleteTaskPushNotificationConfigRequest():
handler_result = (
await self.handler.delete_push_notification_config(
request_obj,
context,
)
)
case _:
logger.error(
f'Unhandled validated request type: {type(request_obj)}'
)
error = UnsupportedOperationError(
message=f'Request type {type(request_obj).__name__} is unknown.'
)
handler_result = JSONRPCErrorResponse(
id=request_id, error=error
)
return self._create_response(context, handler_result)
def _create_response(
self,
context: ServerCallContext,
handler_result: (
AsyncGenerator[SendStreamingMessageResponse]
| JSONRPCErrorResponse
| JSONRPCResponse
),
) -> Response:
"""Creates a Starlette Response based on the result from the request handler.
Handles:
- AsyncGenerator for Server-Sent Events (SSE).
- JSONRPCErrorResponse for explicit errors returned by handlers.
- Pydantic RootModels (like GetTaskResponse) containing success or error
payloads.
Args:
context: The ServerCallContext provided to the request handler.
handler_result: The result from a request handler method. Can be an
async generator for streaming or a Pydantic model for non-streaming.
Returns:
A Starlette JSONResponse or EventSourceResponse.
"""
headers = {}
if exts := context.activated_extensions:
headers[HTTP_EXTENSION_HEADER] = ', '.join(exts)
if isinstance(handler_result, AsyncGenerator):
# Result is a stream of SendStreamingMessageResponse objects
async def event_generator(
stream: AsyncGenerator[SendStreamingMessageResponse],
) -> AsyncGenerator[dict[str, str]]:
async for item in stream:
yield {'data': item.root.model_dump_json(exclude_none=True)}
return EventSourceResponse(
event_generator(handler_result), headers=headers
)
if isinstance(handler_result, JSONRPCErrorResponse):
return JSONResponse(
handler_result.model_dump(
mode='json',
exclude_none=True,
),
headers=headers,
)
return JSONResponse(
handler_result.root.model_dump(mode='json', exclude_none=True),
headers=headers,
)
async def _handle_get_agent_card(self, request: Request) -> JSONResponse:
"""Handles GET requests for the agent card endpoint.
Args:
request: The incoming Starlette Request object.
Returns:
A JSONResponse containing the agent card data.
"""
# The public agent card is a direct serialization of the agent_card
# provided at initialization.
return JSONResponse(
self.agent_card.model_dump(
exclude_none=True,
by_alias=True,
)
)
async def _handle_get_authenticated_extended_agent_card(
self, request: Request
) -> JSONResponse:
"""Handles GET requests for the authenticated extended agent card."""
if not self.agent_card.supportsAuthenticatedExtendedCard:
return JSONResponse(
{'error': 'Extended agent card not supported or not enabled.'},
status_code=404,
)
# If an explicit extended_agent_card is provided, serve that.
if self.extended_agent_card:
return JSONResponse(
self.extended_agent_card.model_dump(
exclude_none=True,
by_alias=True,
)
)
# If supportsAuthenticatedExtendedCard is true, but no specific
# extended_agent_card was provided during server initialization,
# return a 404
return JSONResponse(
{
'error': 'Authenticated extended agent card is supported but not configured on the server.'
},
status_code=404,
)
@abstractmethod
def build(
self,
agent_card_url: str = AGENT_CARD_WELL_KNOWN_PATH,
rpc_url: str = DEFAULT_RPC_URL,
extended_agent_card_url: str = EXTENDED_AGENT_CARD_PATH,
**kwargs: Any,
) -> FastAPI | Starlette:
"""Builds and returns the JSONRPC application instance.
Args:
agent_card_url: The URL for the agent card endpoint.
rpc_url: The URL for the A2A JSON-RPC endpoint.
extended_agent_card_url: The URL for the authenticated extended
agent card endpoint.
**kwargs: Additional keyword arguments to pass to the FastAPI constructor.
Returns:
A configured JSONRPC application instance.
"""
raise NotImplementedError(
'Subclasses must implement the build method to create the application instance.'
)