|
| 1 | +from typing import TYPE_CHECKING, Any |
| 2 | + |
| 3 | +from a2a.server.routes.helpers._proto_schema import (REST_BODY_TYPES, |
| 4 | + message_schema) |
| 5 | +from a2a.server.routes.helpers.jsonrpc import \ |
| 6 | + DESCRIPTION as _JSONRPC_DESCRIPTION |
| 7 | +from a2a.server.routes.helpers.jsonrpc import \ |
| 8 | + envelope_schema as _jsonrpc_envelope_schema |
| 9 | +from a2a.utils.constants import PROTOCOL_VERSION_1_0, VERSION_HEADER |
| 10 | + |
| 11 | +if TYPE_CHECKING: |
| 12 | + from fastapi import FastAPI |
| 13 | + from starlette.routing import BaseRoute, Route |
| 14 | + |
| 15 | + _package_fastapi_installed = True |
| 16 | +else: |
| 17 | + try: |
| 18 | + from fastapi.routing import APIRoute |
| 19 | + from starlette.routing import Route, request_response |
| 20 | + |
| 21 | + class _A2ARoute(APIRoute): |
| 22 | + """APIRoute that uses Starlette's request_response to bypass FastAPI middleware scope requirements.""" |
| 23 | + |
| 24 | + def __init__(self, *args: Any, **kwargs: Any) -> None: |
| 25 | + super().__init__(*args, **kwargs) |
| 26 | + self.app = request_response(self.endpoint) |
| 27 | + |
| 28 | + _package_fastapi_installed = True |
| 29 | + except ImportError: |
| 30 | + Route = Any |
| 31 | + _A2ARoute = Any |
| 32 | + |
| 33 | + _package_fastapi_installed = False |
| 34 | + |
| 35 | + |
| 36 | +_AGENT_CARD_TAG = 'A2A: Agent Card' |
| 37 | +_JSONRPC_TAG = 'A2A: JSON-RPC' |
| 38 | +_REST_TAG = 'A2A: REST' |
| 39 | + |
| 40 | +_A2A_VERSION_HEADER = { |
| 41 | + 'in': 'header', |
| 42 | + 'name': VERSION_HEADER, |
| 43 | + 'required': True, |
| 44 | + 'schema': {'type': 'string', 'enum': [PROTOCOL_VERSION_1_0]}, |
| 45 | + 'example': PROTOCOL_VERSION_1_0, |
| 46 | +} |
| 47 | + |
| 48 | + |
| 49 | +def _request_body_extra( |
| 50 | + ref: dict[str, Any], description: str |
| 51 | +) -> dict[str, Any]: |
| 52 | + return { |
| 53 | + 'requestBody': { |
| 54 | + 'description': description, |
| 55 | + 'required': True, |
| 56 | + 'content': {'application/json': {'schema': ref}}, |
| 57 | + }, |
| 58 | + } |
| 59 | + |
| 60 | + |
| 61 | +def _rest_body_extra( |
| 62 | + route: 'Route', rest_bodies: dict[tuple[str, str], dict[str, Any]] |
| 63 | +) -> dict[str, Any] | None: |
| 64 | + methods = route.methods or set() |
| 65 | + for (suffix, method), extra in rest_bodies.items(): |
| 66 | + if method in methods and route.path.endswith(suffix): |
| 67 | + return extra |
| 68 | + return None |
| 69 | + |
| 70 | + |
| 71 | +def _attach_route( |
| 72 | + app: 'FastAPI', |
| 73 | + route: 'BaseRoute', |
| 74 | + tag: str, |
| 75 | + openapi_extra: dict[str, Any] | None, |
| 76 | + require_version_header: bool = False, |
| 77 | +) -> None: |
| 78 | + if not (isinstance(route, Route) and route.methods): |
| 79 | + app.routes.append(route) |
| 80 | + return |
| 81 | + # Drop HEAD: Starlette adds it alongside GET, but FastAPI registers duplicate operation IDs. |
| 82 | + methods = sorted(m for m in route.methods if m != 'HEAD') |
| 83 | + if require_version_header: |
| 84 | + extra = dict(openapi_extra or {}) |
| 85 | + extra.setdefault('parameters', [_A2A_VERSION_HEADER]) |
| 86 | + openapi_extra = extra |
| 87 | + app.routes.append( |
| 88 | + _A2ARoute( |
| 89 | + path=route.path, |
| 90 | + endpoint=route.endpoint, |
| 91 | + methods=methods, |
| 92 | + tags=[tag], |
| 93 | + openapi_extra=openapi_extra, |
| 94 | + ) |
| 95 | + ) |
| 96 | + |
| 97 | + |
| 98 | +def _install_components(app: 'FastAPI', schemas: dict[str, Any]) -> None: |
| 99 | + original_openapi = app.openapi |
| 100 | + |
| 101 | + def _openapi() -> dict[str, Any]: |
| 102 | + if app.openapi_schema: |
| 103 | + return app.openapi_schema |
| 104 | + schema = original_openapi() |
| 105 | + component_schemas = schema.setdefault('components', {}).setdefault( |
| 106 | + 'schemas', {} |
| 107 | + ) |
| 108 | + for name, sub_schema in schemas.items(): |
| 109 | + component_schemas.setdefault(name, sub_schema) |
| 110 | + return schema |
| 111 | + |
| 112 | + app.openapi = _openapi # type: ignore[method-assign] |
| 113 | + |
| 114 | + |
| 115 | +def add_a2a_routes_to_fastapi( |
| 116 | + app: 'FastAPI', |
| 117 | + *, |
| 118 | + agent_card_routes: 'list[BaseRoute] | None' = None, |
| 119 | + jsonrpc_routes: 'list[BaseRoute] | None' = None, |
| 120 | + rest_routes: 'list[BaseRoute] | None' = None, |
| 121 | +) -> None: |
| 122 | + """Mounts A2A routes on a FastAPI app and enriches them for ``/docs``. |
| 123 | +
|
| 124 | + Re-registers Starlette routes as ``APIRoute`` instances so they appear in |
| 125 | + the auto-generated OpenAPI schema, tagged and annotated with proto-derived |
| 126 | + request-body schemas. |
| 127 | +
|
| 128 | + Usage:: |
| 129 | +
|
| 130 | + app = FastAPI() |
| 131 | + add_a2a_routes_to_fastapi( |
| 132 | + app, |
| 133 | + agent_card_routes=create_agent_card_routes(agent_card), |
| 134 | + jsonrpc_routes=create_jsonrpc_routes(request_handler, rpc_url='/'), |
| 135 | + rest_routes=create_rest_routes(request_handler), |
| 136 | + ) |
| 137 | +
|
| 138 | + Args: |
| 139 | + app: The FastAPI application to mount the routes on. |
| 140 | + agent_card_routes: Routes returned by ``create_agent_card_routes``. |
| 141 | + jsonrpc_routes: Routes returned by ``create_jsonrpc_routes``. |
| 142 | + rest_routes: Routes returned by ``create_rest_routes``. |
| 143 | + """ |
| 144 | + if not _package_fastapi_installed: |
| 145 | + raise ImportError( |
| 146 | + 'The `fastapi` package is required to use ' |
| 147 | + '`add_a2a_routes_to_fastapi`. Install it alongside ' |
| 148 | + '`a2a-sdk[http-server]`.' |
| 149 | + ) |
| 150 | + |
| 151 | + components: dict[str, Any] = {} |
| 152 | + jsonrpc_extra = { |
| 153 | + 'summary': 'A2A JSON-RPC endpoint', |
| 154 | + 'description': _JSONRPC_DESCRIPTION, |
| 155 | + **_request_body_extra( |
| 156 | + _jsonrpc_envelope_schema(components), 'A2A JSON-RPC 2.0 request' |
| 157 | + ), |
| 158 | + } |
| 159 | + rest_extras = { |
| 160 | + key: _request_body_extra( |
| 161 | + message_schema(cls.DESCRIPTOR, components), |
| 162 | + f'A2A {cls.__name__}', |
| 163 | + ) |
| 164 | + for key, cls in REST_BODY_TYPES.items() |
| 165 | + } |
| 166 | + |
| 167 | + for route in agent_card_routes or (): |
| 168 | + _attach_route(app, route, _AGENT_CARD_TAG, openapi_extra=None) |
| 169 | + |
| 170 | + for route in jsonrpc_routes or (): |
| 171 | + extra = jsonrpc_extra if isinstance(route, Route) else None |
| 172 | + _attach_route(app, route, _JSONRPC_TAG, openapi_extra=extra, require_version_header=True) |
| 173 | + |
| 174 | + for route in rest_routes or (): |
| 175 | + extra = ( |
| 176 | + _rest_body_extra(route, rest_extras) |
| 177 | + if isinstance(route, Route) |
| 178 | + else None |
| 179 | + ) |
| 180 | + _attach_route(app, route, _REST_TAG, openapi_extra=extra, require_version_header=True) |
| 181 | + |
| 182 | + _install_components(app, components) |
0 commit comments