Skip to content

Commit 46b292b

Browse files
fix(server): improve Swagger /docs example annotations for A2A routes (a2aproject#1092)
## Summary - Uses `add_a2a_routes_to_fastapi()` in the sample instead of `app.routes.extend()` — the feature introduced in a2aproject#1024 was not reflected in the sample - Adds principled Swagger example annotations to the proto → JSON Schema generator (`_proto_schema.py`), driven by `google.api.field_behavior` proto annotations and proto type information rather than hardcoded field-name lists ### Schema example improvements | Field type | Before | After | |---|---|---| | Enum | no example → Swagger guesses (e.g. `"user"`) causing `-32602` | first non-`UNSPECIFIED` value (e.g. `ROLE_USER`) | | String, optional | no example → Swagger generates `"string"` causing task-lookup failures on `task_id` | `""` (proto3 empty = field unset) | | String, `REQUIRED` | no example → `"string"` causing validation failures on `message_id` | `field.name` (non-empty, self-describing) | | Bool | no example → Swagger picks `true` causing `return_immediately: true` → `SUBMITTED` | `false` | | Message, non-`REQUIRED` | expanded inline → optional config sub-fields fail required-field validation | `oneOf: [$ref, null]` with `example: null` | | Message, `REQUIRED` | — | unchanged `$ref` (not nullable) | | Repeated (array) | no array example → Swagger generates one item per `oneOf` branch | `[item_example]` (single pre-filled entry) | | oneOf schema | no example → all branches expanded in arrays | example using first variant only | Optionality is derived from `google.api.field_behavior = REQUIRED` annotations already present on the A2A proto fields — no hardcoded field-name exceptions. ## Checklist - [x] Follows [`CONTRIBUTING` Guide](https://github.com/a2aproject/a2a-python/blob/main/CONTRIBUTING.md) - [x] PR title follows Conventional Commits - [x] Tests pass — 95 passing (8 new tests covering the new example behaviour) - [x] `ruff format` and `ruff check` clean Continues a2aproject#1024 🦕 --------- Co-authored-by: Ivan Shymko <ishymko@google.com>
1 parent b264a6f commit 46b292b

3 files changed

Lines changed: 175 additions & 51 deletions

File tree

‎samples/hello_world_agent.py‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
from a2a.server.events.event_queue import EventQueue
1616
from a2a.server.request_handlers import DefaultRequestHandler, GrpcHandler
1717
from a2a.server.routes import (
18+
add_a2a_routes_to_fastapi,
1819
create_agent_card_routes,
1920
create_jsonrpc_routes,
2021
create_rest_routes,
@@ -220,9 +221,12 @@ async def serve(
220221
agent_card=agent_card,
221222
)
222223
app = FastAPI()
223-
app.routes.extend(jsonrpc_routes)
224-
app.routes.extend(agent_card_routes)
225-
app.routes.extend(rest_routes)
224+
add_a2a_routes_to_fastapi(
225+
app,
226+
agent_card_routes=agent_card_routes,
227+
jsonrpc_routes=jsonrpc_routes,
228+
rest_routes=rest_routes,
229+
)
226230

227231
grpc_server = grpc.aio.server()
228232
grpc_server.add_insecure_port(f'{host}:{grpc_port}')

‎src/a2a/server/routes/_proto_schema.py‎

Lines changed: 65 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from typing import Any
44

5+
from google.api import field_behavior_pb2 as fb
56
from google.protobuf.descriptor import Descriptor, FieldDescriptor
67
from google.protobuf.message import Message
78

@@ -33,6 +34,12 @@
3334
FieldDescriptor.TYPE_SINT64: {'type': 'string'},
3435
}
3536

37+
38+
def _is_required(field: FieldDescriptor) -> bool:
39+
"""Returns True if the field carries google.api.field_behavior = REQUIRED."""
40+
return fb.REQUIRED in field.GetOptions().Extensions[fb.field_behavior] # type: ignore[index] # ty: ignore[invalid-argument-type]
41+
42+
3643
_WELL_KNOWN_SCHEMAS: dict[str, dict[str, Any]] = {
3744
'google.protobuf.Timestamp': {'type': 'string', 'format': 'date-time'},
3845
'google.protobuf.Duration': {'type': 'string'},
@@ -57,16 +64,46 @@ def field_schema(
5764

5865
if field.type == FieldDescriptor.TYPE_MESSAGE:
5966
item = message_schema(field.message_type, components)
67+
# Well-known types return an inline schema (no $ref); don't wrap them as
68+
# nullable — they're already inlined as their JSON-Schema equivalent.
69+
# Repeated fields must not return early here — they fall through to the
70+
# array-wrapping block below.
71+
if not field.is_repeated and not _is_required(field) and '$ref' in item:
72+
return {'oneOf': [item, {'type': 'null'}], 'example': None}
6073
elif field.type == FieldDescriptor.TYPE_ENUM:
61-
item = {
62-
'type': 'string',
63-
'enum': [v.name for v in field.enum_type.values],
64-
}
74+
values = [v.name for v in field.enum_type.values]
75+
example = next(
76+
(
77+
v
78+
for v in values
79+
if 'UNSPECIFIED' not in v and 'UNKNOWN' not in v
80+
),
81+
values[0] if values else None,
82+
)
83+
item: dict[str, Any] = {'type': 'string', 'enum': values}
84+
if example:
85+
item['example'] = example
6586
else:
6687
item = dict(_PROTO_SCALAR_SCHEMAS.get(field.type, {'type': 'string'}))
88+
if field.type == FieldDescriptor.TYPE_STRING:
89+
# REQUIRED fields must be non-empty; use the field name as a
90+
# recognisable placeholder. All other strings default to "".
91+
item['example'] = field.name if _is_required(field) else ''
92+
elif field.type == FieldDescriptor.TYPE_BOOL:
93+
item['example'] = False
6794

6895
if field.is_repeated:
69-
return {'type': 'array', 'items': item}
96+
array_schema: dict[str, Any] = {'type': 'array', 'items': item}
97+
# Propagate the item example to the array so Swagger pre-fills one entry
98+
# instead of generating one entry per oneOf branch.
99+
item_example = (
100+
components.get(item['$ref'].split('/')[-1], {}).get('example')
101+
if '$ref' in item
102+
else item.get('example')
103+
)
104+
if item_example is not None:
105+
array_schema['example'] = [item_example]
106+
return array_schema
70107
return item
71108

72109

@@ -114,5 +151,27 @@ def message_schema(
114151
if base_properties:
115152
parts.append({'type': 'object', 'properties': base_properties})
116153
parts.extend(oneof_constraints)
117-
components[name] = parts[0] if len(parts) == 1 else {'allOf': parts}
154+
schema: dict[str, Any] = parts[0] if len(parts) == 1 else {'allOf': parts}
155+
# Provide a single concrete example using the first oneof variant so Swagger
156+
# doesn't expand every branch into separate array items.
157+
first_oneof_field = real_oneofs[0].fields[0]
158+
first_field_schema = field_schema(first_oneof_field, components)
159+
if 'example' in first_field_schema:
160+
first_example: Any = first_field_schema['example']
161+
elif '$ref' in first_field_schema:
162+
ref_name = first_field_schema['$ref'].split('/')[-1]
163+
first_example = components.get(ref_name, {}).get('example')
164+
else:
165+
_type_defaults: dict[str, Any] = {
166+
'integer': 0,
167+
'number': 0.0,
168+
'boolean': False,
169+
'array': [],
170+
'object': {},
171+
}
172+
first_example = _type_defaults.get(
173+
first_field_schema.get('type', 'string'), ''
174+
)
175+
schema['example'] = {first_oneof_field.name: first_example}
176+
components[name] = schema
118177
return ref

‎tests/server/routes/test_proto_schema.py‎

Lines changed: 103 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -59,48 +59,6 @@ def test_message_schema_oneof_variants_have_required():
5959
assert len(variant['required']) == 1
6060

6161

62-
def test_message_schema_multiple_oneofs_use_allof_not_cartesian_product():
63-
# Simulate a descriptor with two oneofs: verify allOf has one constraint
64-
# per oneof rather than a flat list of cross-product variants.
65-
from unittest.mock import MagicMock
66-
67-
def _make_field(name):
68-
f = MagicMock()
69-
f.name = name
70-
f.message_type = None
71-
f.type = 9 # TYPE_STRING
72-
f.is_repeated = False
73-
return f
74-
75-
def _make_oneof(fields):
76-
o = MagicMock()
77-
o.fields = fields
78-
return o
79-
80-
f_a, f_b = _make_field('a'), _make_field('b')
81-
f_x, f_y = _make_field('x'), _make_field('y')
82-
oneof1 = _make_oneof([f_a, f_b])
83-
oneof2 = _make_oneof([f_x, f_y])
84-
85-
descriptor = MagicMock()
86-
descriptor.full_name = 'test.MultiOneof'
87-
descriptor.name = 'MultiOneof'
88-
descriptor.oneofs = [oneof1, oneof2]
89-
descriptor.fields = [f_a, f_b, f_x, f_y]
90-
91-
components = {}
92-
message_schema(descriptor, components)
93-
schema = components['MultiOneof']
94-
95-
# Should be allOf with two oneOf constraints (one per oneof group),
96-
# NOT a flat oneOf with 2*2=4 Cartesian-product variants.
97-
assert 'allOf' in schema
98-
one_of_constraints = [p for p in schema['allOf'] if 'oneOf' in p]
99-
assert len(one_of_constraints) == 2
100-
assert len(one_of_constraints[0]['oneOf']) == 2
101-
assert len(one_of_constraints[1]['oneOf']) == 2
102-
103-
10462
def test_field_schema_repeated_wraps_in_array():
10563
components = {}
10664
msg_descriptor = SendMessageRequest.DESCRIPTOR.fields_by_name[
@@ -120,6 +78,92 @@ def test_field_schema_enum():
12078
assert 'ROLE_AGENT' in schema['enum']
12179

12280

81+
def test_field_schema_enum_example_skips_unspecified():
82+
role_field = Message.DESCRIPTOR.fields_by_name['role']
83+
schema = field_schema(role_field, {})
84+
assert schema['example'] == 'ROLE_USER'
85+
86+
87+
def test_field_schema_string_example_is_empty():
88+
context_id_field = Message.DESCRIPTOR.fields_by_name['context_id']
89+
schema = field_schema(context_id_field, {})
90+
assert schema['example'] == ''
91+
92+
93+
def test_field_schema_string_required_uses_field_name():
94+
# REQUIRED string fields must be non-empty; the field name is the placeholder.
95+
message_id_field = Message.DESCRIPTOR.fields_by_name['message_id']
96+
schema = field_schema(message_id_field, {})
97+
assert schema['example'] == 'message_id'
98+
99+
100+
def test_field_schema_bool_example_is_false():
101+
from a2a.types.a2a_pb2 import SendMessageConfiguration
102+
103+
field = SendMessageConfiguration.DESCRIPTOR.fields_by_name[
104+
'return_immediately'
105+
]
106+
schema = field_schema(field, {})
107+
assert schema['example'] is False
108+
109+
110+
def test_field_schema_optional_message_is_nullable():
111+
# Non-REQUIRED message fields default to null so Swagger doesn't pre-fill them
112+
# with empty sub-fields that trigger server-side required-field validation.
113+
from a2a.types.a2a_pb2 import SendMessageConfiguration
114+
115+
field = SendMessageConfiguration.DESCRIPTOR.fields_by_name[
116+
'task_push_notification_config'
117+
]
118+
schema = field_schema(field, {})
119+
assert schema['example'] is None
120+
assert any(v == {'type': 'null'} for v in schema['oneOf'])
121+
122+
123+
def test_field_schema_required_message_is_not_nullable():
124+
from a2a.types.a2a_pb2 import SendMessageRequest
125+
126+
field = SendMessageRequest.DESCRIPTOR.fields_by_name['message']
127+
schema = field_schema(field, {})
128+
assert '$ref' in schema
129+
assert 'oneOf' not in schema
130+
131+
132+
def test_field_schema_repeated_optional_message_is_array_not_nullable():
133+
# Repeated non-REQUIRED message fields must be wrapped as an array, not
134+
# returned early as a nullable oneOf — the is_repeated check must come
135+
# first. Task.history is a real repeated, non-required message field.
136+
from a2a.types.a2a_pb2 import Task
137+
138+
field = Task.DESCRIPTOR.fields_by_name['history']
139+
schema = field_schema(field, {})
140+
assert schema['type'] == 'array'
141+
assert 'oneOf' not in schema
142+
assert '$ref' in schema['items']
143+
144+
145+
def test_message_schema_oneof_example_uses_first_variant_only():
146+
components = {}
147+
message_schema(Part.DESCRIPTOR, components)
148+
example = components['Part']['example']
149+
assert example == {'text': ''}
150+
# base properties (metadata, filename, media_type) must not appear in the
151+
# example — they are objects/strings that would be wrong if sent as "".
152+
assert 'metadata' not in example
153+
assert 'filename' not in example
154+
155+
156+
def test_field_schema_repeated_ref_example_propagated():
157+
components = {}
158+
msg_descriptor = SendMessageRequest.DESCRIPTOR.fields_by_name[
159+
'message'
160+
].message_type
161+
parts_field = msg_descriptor.fields_by_name['parts']
162+
schema = field_schema(parts_field, components)
163+
assert schema['type'] == 'array'
164+
assert schema['example'] == [{'text': ''}]
165+
166+
123167
def test_field_schema_map_entry():
124168
metadata_field = SendMessageRequest.DESCRIPTOR.fields_by_name['metadata']
125169
schema = field_schema(metadata_field, {})
@@ -130,3 +174,20 @@ def test_rest_body_types_coverage():
130174
assert ('/message:send', 'POST') in REST_BODY_TYPES
131175
assert ('/message:stream', 'POST') in REST_BODY_TYPES
132176
assert ('/tasks/{id}/pushNotificationConfigs', 'POST') in REST_BODY_TYPES
177+
178+
179+
def test_full_schema_builds_for_all_rest_body_types():
180+
# Safety net: build the complete schema for every registered REST body
181+
# type into a shared components dict. Any proto field structure we don't
182+
# support (or stop supporting after a proto change) fails right here
183+
# rather than silently producing a broken Swagger document.
184+
components: dict = {}
185+
for msg in REST_BODY_TYPES.values():
186+
ref = message_schema(msg.DESCRIPTOR, components)
187+
assert ref['$ref'].startswith('#/components/schemas/')
188+
189+
# Every registered schema must be a non-empty object/composition (the
190+
# cyclic-type placeholder is filled in before the build returns).
191+
for name, schema in components.items():
192+
assert schema, f'{name} resolved to an empty schema'
193+
assert 'type' in schema or 'allOf' in schema or '$ref' in schema

0 commit comments

Comments
 (0)