Python SDK Reference¶
This page contains SDK documentation for the a2a-sdk
Python package.
The A2A Python SDK.
client
¶
Client-side components for interacting with an A2A agent.
A2ACardResolver
¶
Agent Card resolver.
__init__(httpx_client, base_url, agent_card_path=AGENT_CARD_WELL_KNOWN_PATH)
¶
Initializes the A2ACardResolver.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
httpx_client
|
AsyncClient
|
An async HTTP client instance (e.g., httpx.AsyncClient). |
required |
base_url
|
str
|
The base URL of the agent's host. |
required |
agent_card_path
|
str
|
The path to the agent card endpoint, relative to the base URL. |
AGENT_CARD_WELL_KNOWN_PATH
|
get_agent_card(relative_card_path=None, http_kwargs=None)
async
¶
Fetches an agent card from a specified path relative to the base_url.
If relative_card_path is None, it defaults to the resolver's configured agent_card_path (for the public agent card).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
relative_card_path
|
str | None
|
Optional path to the agent card endpoint, relative to the base URL. If None, uses the default public agent card path. |
None
|
http_kwargs
|
dict[str, Any] | None
|
Optional dictionary of keyword arguments to pass to the underlying httpx.get request. |
None
|
Returns:
Type | Description |
---|---|
AgentCard
|
An |
Raises:
Type | Description |
---|---|
A2AClientHTTPError
|
If an HTTP error occurs during the request. |
A2AClientJSONError
|
If the response body cannot be decoded as JSON or validated against the AgentCard schema. |
A2AClient
¶
[DEPRECATED] Backwards compatibility wrapper for the JSON-RPC client.
cancel_task(request, *, http_kwargs=None, context=None)
async
¶
Requests the agent to cancel a specific task.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
CancelTaskRequest
|
The |
required |
http_kwargs
|
dict[str, Any] | None
|
Optional dictionary of keyword arguments to pass to the underlying httpx.post request. |
None
|
context
|
ClientCallContext | None
|
The client call context. |
None
|
Returns:
Type | Description |
---|---|
CancelTaskResponse
|
A |
Raises:
Type | Description |
---|---|
A2AClientHTTPError
|
If an HTTP error occurs during the request. |
A2AClientJSONError
|
If the response body cannot be decoded as JSON or validated. |
get_card(*, http_kwargs=None, context=None)
async
¶
Retrieves the authenticated card (if necessary) or the public one.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
http_kwargs
|
dict[str, Any] | None
|
Optional dictionary of keyword arguments to pass to the underlying httpx.post request. |
None
|
context
|
ClientCallContext | None
|
The client call context. |
None
|
Returns:
Type | Description |
---|---|
AgentCard
|
A |
Raises:
Type | Description |
---|---|
A2AClientHTTPError
|
If an HTTP error occurs during the request. |
A2AClientJSONError
|
If the response body cannot be decoded as JSON or validated. |
get_task(request, *, http_kwargs=None, context=None)
async
¶
Retrieves the current state and history of a specific task.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
GetTaskRequest
|
The |
required |
http_kwargs
|
dict[str, Any] | None
|
Optional dictionary of keyword arguments to pass to the underlying httpx.post request. |
None
|
context
|
ClientCallContext | None
|
The client call context. |
None
|
Returns:
Type | Description |
---|---|
GetTaskResponse
|
A |
Raises:
Type | Description |
---|---|
A2AClientHTTPError
|
If an HTTP error occurs during the request. |
A2AClientJSONError
|
If the response body cannot be decoded as JSON or validated. |
get_task_callback(request, *, http_kwargs=None, context=None)
async
¶
Retrieves the push notification configuration for a specific task.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
GetTaskPushNotificationConfigRequest
|
The |
required |
http_kwargs
|
dict[str, Any] | None
|
Optional dictionary of keyword arguments to pass to the underlying httpx.post request. |
None
|
context
|
ClientCallContext | None
|
The client call context. |
None
|
Returns:
Type | Description |
---|---|
GetTaskPushNotificationConfigResponse
|
A |
Raises:
Type | Description |
---|---|
A2AClientHTTPError
|
If an HTTP error occurs during the request. |
A2AClientJSONError
|
If the response body cannot be decoded as JSON or validated. |
resubscribe(request, *, http_kwargs=None, context=None)
async
¶
Reconnects to get task updates.
This method uses Server-Sent Events (SSE) to receive a stream of updates from the agent.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
TaskResubscriptionRequest
|
The |
required |
http_kwargs
|
dict[str, Any] | None
|
Optional dictionary of keyword arguments to pass to the
underlying httpx.post request. A default |
None
|
context
|
ClientCallContext | None
|
The client call context. |
None
|
Yields:
Type | Description |
---|---|
AsyncGenerator[SendStreamingMessageResponse, None]
|
|
AsyncGenerator[SendStreamingMessageResponse, None]
|
These can be Task, Message, TaskStatusUpdateEvent, or TaskArtifactUpdateEvent. |
Raises:
Type | Description |
---|---|
A2AClientHTTPError
|
If an HTTP or SSE protocol error occurs during the request. |
A2AClientJSONError
|
If an SSE event data cannot be decoded as JSON or validated. |
send_message(request, *, http_kwargs=None, context=None)
async
¶
Sends a non-streaming message request to the agent.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
SendMessageRequest
|
The |
required |
http_kwargs
|
dict[str, Any] | None
|
Optional dictionary of keyword arguments to pass to the underlying httpx.post request. |
None
|
context
|
ClientCallContext | None
|
The client call context. |
None
|
Returns:
Type | Description |
---|---|
SendMessageResponse
|
A |
Raises:
Type | Description |
---|---|
A2AClientHTTPError
|
If an HTTP error occurs during the request. |
A2AClientJSONError
|
If the response body cannot be decoded as JSON or validated. |
send_message_streaming(request, *, http_kwargs=None, context=None)
async
¶
Sends a streaming message request to the agent and yields responses as they arrive.
This method uses Server-Sent Events (SSE) to receive a stream of updates from the agent.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
SendStreamingMessageRequest
|
The |
required |
http_kwargs
|
dict[str, Any] | None
|
Optional dictionary of keyword arguments to pass to the
underlying httpx.post request. A default |
None
|
context
|
ClientCallContext | None
|
The client call context. |
None
|
Yields:
Type | Description |
---|---|
AsyncGenerator[SendStreamingMessageResponse, None]
|
|
AsyncGenerator[SendStreamingMessageResponse, None]
|
These can be Task, Message, TaskStatusUpdateEvent, or TaskArtifactUpdateEvent. |
Raises:
Type | Description |
---|---|
A2AClientHTTPError
|
If an HTTP or SSE protocol error occurs during the request. |
A2AClientJSONError
|
If an SSE event data cannot be decoded as JSON or validated. |
set_task_callback(request, *, http_kwargs=None, context=None)
async
¶
Sets or updates the push notification configuration for a specific task.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
SetTaskPushNotificationConfigRequest
|
The |
required |
http_kwargs
|
dict[str, Any] | None
|
Optional dictionary of keyword arguments to pass to the underlying httpx.post request. |
None
|
context
|
ClientCallContext | None
|
The client call context. |
None
|
Returns:
Type | Description |
---|---|
SetTaskPushNotificationConfigResponse
|
A |
Raises:
Type | Description |
---|---|
A2AClientHTTPError
|
If an HTTP error occurs during the request. |
A2AClientJSONError
|
If the response body cannot be decoded as JSON or validated. |
A2AClientError
¶
Bases: Exception
Base exception for A2A Client errors.
A2AClientHTTPError
¶
Bases: A2AClientError
Client exception for HTTP errors received from the server.
__init__(status_code, message)
¶
Initializes the A2AClientHTTPError.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
status_code
|
int
|
The HTTP status code of the response. |
required |
message
|
str
|
A descriptive error message. |
required |
A2AClientJSONError
¶
Bases: A2AClientError
Client exception for JSON errors during response parsing or validation.
__init__(message)
¶
Initializes the A2AClientJSONError.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
message
|
str
|
A descriptive error message. |
required |
A2AClientTimeoutError
¶
Bases: A2AClientError
Client exception for timeout errors during a request.
__init__(message)
¶
Initializes the A2AClientTimeoutError.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
message
|
str
|
A descriptive error message. |
required |
A2AGrpcClient
¶
Placeholder for A2AGrpcClient when dependencies are not installed.
AuthInterceptor
¶
Bases: ClientCallInterceptor
An interceptor that automatically adds authentication details to requests.
Based on the agent's security schemes.
intercept(method_name, request_payload, http_kwargs, agent_card, context)
async
¶
Applies authentication headers to the request if credentials are available.
Client
¶
Bases: ABC
Abstract base class defining the interface for an A2A client.
This class provides a standard set of methods for interacting with an A2A agent, regardless of the underlying transport protocol (e.g., gRPC, JSON-RPC). It supports sending messages, managing tasks, and handling event streams.
__init__(consumers=None, middleware=None)
¶
Initializes the client with consumers and middleware.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
consumers
|
list[Consumer] | None
|
A list of callables to process events from the agent. |
None
|
middleware
|
list[ClientCallInterceptor] | None
|
A list of interceptors to process requests and responses. |
None
|
add_event_consumer(consumer)
async
¶
Attaches additional consumers to the Client
.
add_request_middleware(middleware)
async
¶
Attaches additional middleware to the Client
.
cancel_task(request, *, context=None)
abstractmethod
async
¶
Requests the agent to cancel a specific task.
consume(event, card)
async
¶
Processes the event via all the registered Consumer
s.
get_card(*, context=None)
abstractmethod
async
¶
Retrieves the agent's card.
get_task(request, *, context=None)
abstractmethod
async
¶
Retrieves the current state and history of a specific task.
get_task_callback(request, *, context=None)
abstractmethod
async
¶
Retrieves the push notification configuration for a specific task.
resubscribe(request, *, context=None)
abstractmethod
async
¶
Resubscribes to a task's event stream.
send_message(request, *, context=None)
abstractmethod
async
¶
Sends a message to the server.
This will automatically use the streaming or non-streaming approach
as supported by the server and the client config. Client will
aggregate update events and return an iterator of (Task
,Update
)
pairs, or a Message
. Client will also send these values to any
configured Consumer
s in the client.
set_task_callback(request, *, context=None)
abstractmethod
async
¶
Sets or updates the push notification configuration for a specific task.
ClientCallContext
¶
Bases: BaseModel
A context passed with each client call, allowing for call-specific.
configuration and data passing. Such as authentication details or request deadlines.
ClientCallInterceptor
¶
Bases: ABC
An abstract base class for client-side call interceptors.
Interceptors can inspect and modify requests before they are sent, which is ideal for concerns like authentication, logging, or tracing.
intercept(method_name, request_payload, http_kwargs, agent_card, context)
abstractmethod
async
¶
Intercepts a client call before the request is sent.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
method_name
|
str
|
The name of the RPC method (e.g., 'message/send'). |
required |
request_payload
|
dict[str, Any]
|
The JSON RPC request payload dictionary. |
required |
http_kwargs
|
dict[str, Any]
|
The keyword arguments for the httpx request. |
required |
agent_card
|
AgentCard | None
|
The AgentCard associated with the client. |
required |
context
|
ClientCallContext | None
|
The ClientCallContext for this specific call. |
required |
Returns:
Type | Description |
---|---|
dict[str, Any]
|
A tuple containing the (potentially modified) request_payload |
dict[str, Any]
|
and http_kwargs. |
ClientConfig
dataclass
¶
Configuration class for the A2AClient Factory.
accepted_output_modes = dataclasses.field(default_factory=list)
class-attribute
instance-attribute
¶
The set of accepted output modes for the client.
grpc_channel_factory = None
class-attribute
instance-attribute
¶
Generates a grpc connection channel for a given url.
httpx_client = None
class-attribute
instance-attribute
¶
Http client to use to connect to agent.
polling = False
class-attribute
instance-attribute
¶
Whether client prefers to poll for updates from message:send. It is the callers job to check if the response is completed and if not run a polling loop.
push_notification_configs = dataclasses.field(default_factory=list)
class-attribute
instance-attribute
¶
Push notification callbacks to use for every request.
streaming = True
class-attribute
instance-attribute
¶
Whether client supports streaming
supported_transports = dataclasses.field(default_factory=list)
class-attribute
instance-attribute
¶
Ordered list of transports for connecting to agent (in order of preference). Empty implies JSONRPC only.
This is a string type to allow custom transports to exist in closed ecosystems.
use_client_preference = False
class-attribute
instance-attribute
¶
Whether to use client transport preferences over server preferences. Recommended to use server preferences in most situations.
ClientFactory
¶
ClientFactory is used to generate the appropriate client for the agent.
The factory is configured with a ClientConfig
and optionally a list of
Consumer
s to use for all generated Client
s. The expected use is:
factory = ClientFactory(config, consumers)
Optionally register custom client implementations¶
factory.register('my_customer_transport', NewCustomTransportClient)
Then with an agent card make a client with additional consumers and¶
interceptors¶
client = factory.create(card, additional_consumers, interceptors)
Now the client can be used the same regardless of transport and¶
aligns client config with server capabilities.¶
create(card, consumers=None, interceptors=None)
¶
Create a new Client
for the provided AgentCard
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
card
|
AgentCard
|
An |
required |
consumers
|
list[Consumer] | None
|
A list of |
None
|
interceptors
|
list[ClientCallInterceptor] | None
|
A list of interceptors to use for each request. These are used for things like attaching credentials or http headers to all outbound requests. |
None
|
Returns:
Type | Description |
---|---|
Client
|
A |
register(label, generator)
¶
Register a new transport producer for a given transport label.
CredentialService
¶
Bases: ABC
An abstract service for retrieving credentials.
get_credentials(security_scheme_name, context)
abstractmethod
async
¶
Retrieves a credential (e.g., token) for a security scheme.
InMemoryContextCredentialStore
¶
Bases: CredentialService
A simple in-memory store for session-keyed credentials.
This class uses the 'sessionId' from the ClientCallContext state to store and retrieve credentials...
get_credentials(security_scheme_name, context)
async
¶
Retrieves credentials from the in-memory store.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
security_scheme_name
|
str
|
The name of the security scheme. |
required |
context
|
ClientCallContext | None
|
The client call context. |
required |
Returns:
Type | Description |
---|---|
str | None
|
The credential string, or None if not found. |
set_credentials(session_id, security_scheme_name, credential)
async
¶
Method to populate the store.
create_text_message_object(role=Role.user, content='')
¶
Create a Message object containing a single TextPart.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
role
|
Role
|
The role of the message sender (user or agent). Defaults to Role.user. |
user
|
content
|
str
|
The text content of the message. Defaults to an empty string. |
''
|
Returns:
Type | Description |
---|---|
Message
|
A |
minimal_agent_card(url, transports=None)
¶
Generates a minimal card to simplify bootstrapping client creation.
This minimal card is not viable itself to interact with the remote agent. Instead this is a short hand way to take a known url and transport option and interact with the get card endpoint of the agent server to get the correct agent card. This pattern is necessary for gRPC based card access as typically these servers won't expose a well known path card.
auth
¶
Client-side authentication components for the A2A Python SDK.
AuthInterceptor
¶
Bases: ClientCallInterceptor
An interceptor that automatically adds authentication details to requests.
Based on the agent's security schemes.
intercept(method_name, request_payload, http_kwargs, agent_card, context)
async
¶
Applies authentication headers to the request if credentials are available.
CredentialService
¶
Bases: ABC
An abstract service for retrieving credentials.
get_credentials(security_scheme_name, context)
abstractmethod
async
¶
Retrieves a credential (e.g., token) for a security scheme.
InMemoryContextCredentialStore
¶
Bases: CredentialService
A simple in-memory store for session-keyed credentials.
This class uses the 'sessionId' from the ClientCallContext state to store and retrieve credentials...
get_credentials(security_scheme_name, context)
async
¶
Retrieves credentials from the in-memory store.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
security_scheme_name
|
str
|
The name of the security scheme. |
required |
context
|
ClientCallContext | None
|
The client call context. |
required |
Returns:
Type | Description |
---|---|
str | None
|
The credential string, or None if not found. |
set_credentials(session_id, security_scheme_name, credential)
async
¶
Method to populate the store.
credentials
¶
CredentialService
¶
Bases: ABC
An abstract service for retrieving credentials.
get_credentials(security_scheme_name, context)
abstractmethod
async
¶
Retrieves a credential (e.g., token) for a security scheme.
InMemoryContextCredentialStore
¶
Bases: CredentialService
A simple in-memory store for session-keyed credentials.
This class uses the 'sessionId' from the ClientCallContext state to store and retrieve credentials...
get_credentials(security_scheme_name, context)
async
¶
Retrieves credentials from the in-memory store.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
security_scheme_name
|
str
|
The name of the security scheme. |
required |
context
|
ClientCallContext | None
|
The client call context. |
required |
Returns:
Type | Description |
---|---|
str | None
|
The credential string, or None if not found. |
set_credentials(session_id, security_scheme_name, credential)
async
¶
Method to populate the store.
interceptor
¶
AuthInterceptor
¶
Bases: ClientCallInterceptor
An interceptor that automatically adds authentication details to requests.
Based on the agent's security schemes.
intercept(method_name, request_payload, http_kwargs, agent_card, context)
async
¶
Applies authentication headers to the request if credentials are available.
base_client
¶
BaseClient
¶
Bases: Client
Base implementation of the A2A client, containing transport-independent logic.
add_event_consumer(consumer)
async
¶
Attaches additional consumers to the Client
.
add_request_middleware(middleware)
async
¶
Attaches additional middleware to the Client
.
cancel_task(request, *, context=None)
async
¶
Requests the agent to cancel a specific task.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
TaskIdParams
|
The |
required |
context
|
ClientCallContext | None
|
The client call context. |
None
|
Returns:
Type | Description |
---|---|
Task
|
A |
close()
async
¶
Closes the underlying transport.
consume(event, card)
async
¶
Processes the event via all the registered Consumer
s.
get_card(*, context=None)
async
¶
Retrieves the agent's card.
This will fetch the authenticated card if necessary and update the client's internal state with the new card.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
context
|
ClientCallContext | None
|
The client call context. |
None
|
Returns:
Type | Description |
---|---|
AgentCard
|
The |
get_task(request, *, context=None)
async
¶
Retrieves the current state and history of a specific task.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
TaskQueryParams
|
The |
required |
context
|
ClientCallContext | None
|
The client call context. |
None
|
Returns:
Type | Description |
---|---|
Task
|
A |
get_task_callback(request, *, context=None)
async
¶
Retrieves the push notification configuration for a specific task.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
GetTaskPushNotificationConfigParams
|
The |
required |
context
|
ClientCallContext | None
|
The client call context. |
None
|
Returns:
Type | Description |
---|---|
TaskPushNotificationConfig
|
A |
resubscribe(request, *, context=None)
async
¶
Resubscribes to a task's event stream.
This is only available if both the client and server support streaming.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
TaskIdParams
|
Parameters to identify the task to resubscribe to. |
required |
context
|
ClientCallContext | None
|
The client call context. |
None
|
Yields:
Type | Description |
---|---|
AsyncIterator[ClientEvent]
|
An async iterator of |
Raises:
Type | Description |
---|---|
NotImplementedError
|
If streaming is not supported by the client or server. |
send_message(request, *, context=None)
async
¶
Sends a message to the agent.
This method handles both streaming and non-streaming (polling) interactions based on the client configuration and agent capabilities. It will yield events as they are received from the agent.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
Message
|
The message to send to the agent. |
required |
context
|
ClientCallContext | None
|
The client call context. |
None
|
Yields:
Type | Description |
---|---|
AsyncIterator[ClientEvent | Message]
|
An async iterator of |
set_task_callback(request, *, context=None)
async
¶
Sets or updates the push notification configuration for a specific task.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
TaskPushNotificationConfig
|
The |
required |
context
|
ClientCallContext | None
|
The client call context. |
None
|
Returns:
Type | Description |
---|---|
TaskPushNotificationConfig
|
The created or updated |
card_resolver
¶
A2ACardResolver
¶
Agent Card resolver.
__init__(httpx_client, base_url, agent_card_path=AGENT_CARD_WELL_KNOWN_PATH)
¶
Initializes the A2ACardResolver.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
httpx_client
|
AsyncClient
|
An async HTTP client instance (e.g., httpx.AsyncClient). |
required |
base_url
|
str
|
The base URL of the agent's host. |
required |
agent_card_path
|
str
|
The path to the agent card endpoint, relative to the base URL. |
AGENT_CARD_WELL_KNOWN_PATH
|
get_agent_card(relative_card_path=None, http_kwargs=None)
async
¶
Fetches an agent card from a specified path relative to the base_url.
If relative_card_path is None, it defaults to the resolver's configured agent_card_path (for the public agent card).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
relative_card_path
|
str | None
|
Optional path to the agent card endpoint, relative to the base URL. If None, uses the default public agent card path. |
None
|
http_kwargs
|
dict[str, Any] | None
|
Optional dictionary of keyword arguments to pass to the underlying httpx.get request. |
None
|
Returns:
Type | Description |
---|---|
AgentCard
|
An |
Raises:
Type | Description |
---|---|
A2AClientHTTPError
|
If an HTTP error occurs during the request. |
A2AClientJSONError
|
If the response body cannot be decoded as JSON or validated against the AgentCard schema. |
client
¶
Client
¶
Bases: ABC
Abstract base class defining the interface for an A2A client.
This class provides a standard set of methods for interacting with an A2A agent, regardless of the underlying transport protocol (e.g., gRPC, JSON-RPC). It supports sending messages, managing tasks, and handling event streams.
__init__(consumers=None, middleware=None)
¶
Initializes the client with consumers and middleware.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
consumers
|
list[Consumer] | None
|
A list of callables to process events from the agent. |
None
|
middleware
|
list[ClientCallInterceptor] | None
|
A list of interceptors to process requests and responses. |
None
|
add_event_consumer(consumer)
async
¶
Attaches additional consumers to the Client
.
add_request_middleware(middleware)
async
¶
Attaches additional middleware to the Client
.
cancel_task(request, *, context=None)
abstractmethod
async
¶
Requests the agent to cancel a specific task.
consume(event, card)
async
¶
Processes the event via all the registered Consumer
s.
get_card(*, context=None)
abstractmethod
async
¶
Retrieves the agent's card.
get_task(request, *, context=None)
abstractmethod
async
¶
Retrieves the current state and history of a specific task.
get_task_callback(request, *, context=None)
abstractmethod
async
¶
Retrieves the push notification configuration for a specific task.
resubscribe(request, *, context=None)
abstractmethod
async
¶
Resubscribes to a task's event stream.
send_message(request, *, context=None)
abstractmethod
async
¶
Sends a message to the server.
This will automatically use the streaming or non-streaming approach
as supported by the server and the client config. Client will
aggregate update events and return an iterator of (Task
,Update
)
pairs, or a Message
. Client will also send these values to any
configured Consumer
s in the client.
set_task_callback(request, *, context=None)
abstractmethod
async
¶
Sets or updates the push notification configuration for a specific task.
ClientConfig
dataclass
¶
Configuration class for the A2AClient Factory.
accepted_output_modes = dataclasses.field(default_factory=list)
class-attribute
instance-attribute
¶
The set of accepted output modes for the client.
grpc_channel_factory = None
class-attribute
instance-attribute
¶
Generates a grpc connection channel for a given url.
httpx_client = None
class-attribute
instance-attribute
¶
Http client to use to connect to agent.
polling = False
class-attribute
instance-attribute
¶
Whether client prefers to poll for updates from message:send. It is the callers job to check if the response is completed and if not run a polling loop.
push_notification_configs = dataclasses.field(default_factory=list)
class-attribute
instance-attribute
¶
Push notification callbacks to use for every request.
streaming = True
class-attribute
instance-attribute
¶
Whether client supports streaming
supported_transports = dataclasses.field(default_factory=list)
class-attribute
instance-attribute
¶
Ordered list of transports for connecting to agent (in order of preference). Empty implies JSONRPC only.
This is a string type to allow custom transports to exist in closed ecosystems.
use_client_preference = False
class-attribute
instance-attribute
¶
Whether to use client transport preferences over server preferences. Recommended to use server preferences in most situations.
client_factory
¶
ClientFactory
¶
ClientFactory is used to generate the appropriate client for the agent.
The factory is configured with a ClientConfig
and optionally a list of
Consumer
s to use for all generated Client
s. The expected use is:
factory = ClientFactory(config, consumers)
Optionally register custom client implementations¶
factory.register('my_customer_transport', NewCustomTransportClient)
Then with an agent card make a client with additional consumers and¶
interceptors¶
client = factory.create(card, additional_consumers, interceptors)
Now the client can be used the same regardless of transport and¶
aligns client config with server capabilities.¶
create(card, consumers=None, interceptors=None)
¶
Create a new Client
for the provided AgentCard
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
card
|
AgentCard
|
An |
required |
consumers
|
list[Consumer] | None
|
A list of |
None
|
interceptors
|
list[ClientCallInterceptor] | None
|
A list of interceptors to use for each request. These are used for things like attaching credentials or http headers to all outbound requests. |
None
|
Returns:
Type | Description |
---|---|
Client
|
A |
register(label, generator)
¶
Register a new transport producer for a given transport label.
minimal_agent_card(url, transports=None)
¶
Generates a minimal card to simplify bootstrapping client creation.
This minimal card is not viable itself to interact with the remote agent. Instead this is a short hand way to take a known url and transport option and interact with the get card endpoint of the agent server to get the correct agent card. This pattern is necessary for gRPC based card access as typically these servers won't expose a well known path card.
client_task_manager
¶
ClientTaskManager
¶
Helps manage a task's lifecycle during execution of a request.
Responsible for retrieving, saving, and updating the Task
object based on
events received from the agent.
__init__()
¶
Initializes the ClientTaskManager
.
get_task()
¶
Retrieves the current task object, either from memory.
If task_id
is set, it returns _current_task
otherwise None.
Returns:
Type | Description |
---|---|
Task | None
|
The |
get_task_or_raise()
¶
Retrieves the current task object.
Returns:
Type | Description |
---|---|
Task
|
The |
Raises:
Type | Description |
---|---|
A2AClientInvalidStateError
|
If there is no current known Task. |
process(event)
async
¶
Processes an event, updates the task state if applicable, stores it, and returns the event.
If the event is task-related (Task
, TaskStatusUpdateEvent
, TaskArtifactUpdateEvent
),
the internal task state is updated and persisted.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
event
|
Event
|
The event object received from the agent. |
required |
Returns:
Type | Description |
---|---|
Event
|
The same event object that was processed. |
save_task_event(event)
async
¶
Processes a task-related event (Task, Status, Artifact) and saves the updated task state.
Ensures task and context IDs match or are set from the event.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
event
|
Task | TaskStatusUpdateEvent | TaskArtifactUpdateEvent
|
The task-related event ( |
required |
Returns:
Type | Description |
---|---|
Task | None
|
The updated |
Raises:
Type | Description |
---|---|
ClientError
|
If the task ID in the event conflicts with the TaskManager's ID when the TaskManager's ID is already set. |
update_with_message(message, task)
¶
Updates a task object adding a new message to its history.
If the task has a message in its current status, that message is moved to the history first.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
message
|
Message
|
The new |
required |
task
|
Task
|
The |
required |
Returns:
Type | Description |
---|---|
Task
|
The updated |
errors
¶
Custom exceptions for the A2A client.
A2AClientError
¶
Bases: Exception
Base exception for A2A Client errors.
A2AClientHTTPError
¶
Bases: A2AClientError
Client exception for HTTP errors received from the server.
__init__(status_code, message)
¶
Initializes the A2AClientHTTPError.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
status_code
|
int
|
The HTTP status code of the response. |
required |
message
|
str
|
A descriptive error message. |
required |
A2AClientInvalidArgsError
¶
Bases: A2AClientError
Client exception for invalid arguments passed to a method.
__init__(message)
¶
Initializes the A2AClientInvalidArgsError.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
message
|
str
|
A descriptive error message. |
required |
A2AClientInvalidStateError
¶
Bases: A2AClientError
Client exception for an invalid client state.
__init__(message)
¶
Initializes the A2AClientInvalidStateError.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
message
|
str
|
A descriptive error message. |
required |
A2AClientJSONError
¶
Bases: A2AClientError
Client exception for JSON errors during response parsing or validation.
__init__(message)
¶
Initializes the A2AClientJSONError.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
message
|
str
|
A descriptive error message. |
required |
A2AClientJSONRPCError
¶
Bases: A2AClientError
Client exception for JSON-RPC errors returned by the server.
__init__(error)
¶
Initializes the A2AClientJsonRPCError.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
error
|
JSONRPCErrorResponse
|
The JSON-RPC error object. |
required |
A2AClientTimeoutError
¶
Bases: A2AClientError
Client exception for timeout errors during a request.
__init__(message)
¶
Initializes the A2AClientTimeoutError.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
message
|
str
|
A descriptive error message. |
required |
helpers
¶
Helper functions for the A2A client.
create_text_message_object(role=Role.user, content='')
¶
Create a Message object containing a single TextPart.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
role
|
Role
|
The role of the message sender (user or agent). Defaults to Role.user. |
user
|
content
|
str
|
The text content of the message. Defaults to an empty string. |
''
|
Returns:
Type | Description |
---|---|
Message
|
A |
legacy
¶
Backwards compatibility layer for legacy A2A clients.
A2AClient
¶
[DEPRECATED] Backwards compatibility wrapper for the JSON-RPC client.
cancel_task(request, *, http_kwargs=None, context=None)
async
¶
Requests the agent to cancel a specific task.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
CancelTaskRequest
|
The |
required |
http_kwargs
|
dict[str, Any] | None
|
Optional dictionary of keyword arguments to pass to the underlying httpx.post request. |
None
|
context
|
ClientCallContext | None
|
The client call context. |
None
|
Returns:
Type | Description |
---|---|
CancelTaskResponse
|
A |
Raises:
Type | Description |
---|---|
A2AClientHTTPError
|
If an HTTP error occurs during the request. |
A2AClientJSONError
|
If the response body cannot be decoded as JSON or validated. |
get_card(*, http_kwargs=None, context=None)
async
¶
Retrieves the authenticated card (if necessary) or the public one.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
http_kwargs
|
dict[str, Any] | None
|
Optional dictionary of keyword arguments to pass to the underlying httpx.post request. |
None
|
context
|
ClientCallContext | None
|
The client call context. |
None
|
Returns:
Type | Description |
---|---|
AgentCard
|
A |
Raises:
Type | Description |
---|---|
A2AClientHTTPError
|
If an HTTP error occurs during the request. |
A2AClientJSONError
|
If the response body cannot be decoded as JSON or validated. |
get_task(request, *, http_kwargs=None, context=None)
async
¶
Retrieves the current state and history of a specific task.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
GetTaskRequest
|
The |
required |
http_kwargs
|
dict[str, Any] | None
|
Optional dictionary of keyword arguments to pass to the underlying httpx.post request. |
None
|
context
|
ClientCallContext | None
|
The client call context. |
None
|
Returns:
Type | Description |
---|---|
GetTaskResponse
|
A |
Raises:
Type | Description |
---|---|
A2AClientHTTPError
|
If an HTTP error occurs during the request. |
A2AClientJSONError
|
If the response body cannot be decoded as JSON or validated. |
get_task_callback(request, *, http_kwargs=None, context=None)
async
¶
Retrieves the push notification configuration for a specific task.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
GetTaskPushNotificationConfigRequest
|
The |
required |
http_kwargs
|
dict[str, Any] | None
|
Optional dictionary of keyword arguments to pass to the underlying httpx.post request. |
None
|
context
|
ClientCallContext | None
|
The client call context. |
None
|
Returns:
Type | Description |
---|---|
GetTaskPushNotificationConfigResponse
|
A |
Raises:
Type | Description |
---|---|
A2AClientHTTPError
|
If an HTTP error occurs during the request. |
A2AClientJSONError
|
If the response body cannot be decoded as JSON or validated. |
resubscribe(request, *, http_kwargs=None, context=None)
async
¶
Reconnects to get task updates.
This method uses Server-Sent Events (SSE) to receive a stream of updates from the agent.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
TaskResubscriptionRequest
|
The |
required |
http_kwargs
|
dict[str, Any] | None
|
Optional dictionary of keyword arguments to pass to the
underlying httpx.post request. A default |
None
|
context
|
ClientCallContext | None
|
The client call context. |
None
|
Yields:
Type | Description |
---|---|
AsyncGenerator[SendStreamingMessageResponse, None]
|
|
AsyncGenerator[SendStreamingMessageResponse, None]
|
These can be Task, Message, TaskStatusUpdateEvent, or TaskArtifactUpdateEvent. |
Raises:
Type | Description |
---|---|
A2AClientHTTPError
|
If an HTTP or SSE protocol error occurs during the request. |
A2AClientJSONError
|
If an SSE event data cannot be decoded as JSON or validated. |
send_message(request, *, http_kwargs=None, context=None)
async
¶
Sends a non-streaming message request to the agent.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
SendMessageRequest
|
The |
required |
http_kwargs
|
dict[str, Any] | None
|
Optional dictionary of keyword arguments to pass to the underlying httpx.post request. |
None
|
context
|
ClientCallContext | None
|
The client call context. |
None
|
Returns:
Type | Description |
---|---|
SendMessageResponse
|
A |
Raises:
Type | Description |
---|---|
A2AClientHTTPError
|
If an HTTP error occurs during the request. |
A2AClientJSONError
|
If the response body cannot be decoded as JSON or validated. |
send_message_streaming(request, *, http_kwargs=None, context=None)
async
¶
Sends a streaming message request to the agent and yields responses as they arrive.
This method uses Server-Sent Events (SSE) to receive a stream of updates from the agent.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
SendStreamingMessageRequest
|
The |
required |
http_kwargs
|
dict[str, Any] | None
|
Optional dictionary of keyword arguments to pass to the
underlying httpx.post request. A default |
None
|
context
|
ClientCallContext | None
|
The client call context. |
None
|
Yields:
Type | Description |
---|---|
AsyncGenerator[SendStreamingMessageResponse, None]
|
|
AsyncGenerator[SendStreamingMessageResponse, None]
|
These can be Task, Message, TaskStatusUpdateEvent, or TaskArtifactUpdateEvent. |
Raises:
Type | Description |
---|---|
A2AClientHTTPError
|
If an HTTP or SSE protocol error occurs during the request. |
A2AClientJSONError
|
If an SSE event data cannot be decoded as JSON or validated. |
set_task_callback(request, *, http_kwargs=None, context=None)
async
¶
Sets or updates the push notification configuration for a specific task.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
SetTaskPushNotificationConfigRequest
|
The |
required |
http_kwargs
|
dict[str, Any] | None
|
Optional dictionary of keyword arguments to pass to the underlying httpx.post request. |
None
|
context
|
ClientCallContext | None
|
The client call context. |
None
|
Returns:
Type | Description |
---|---|
SetTaskPushNotificationConfigResponse
|
A |
Raises:
Type | Description |
---|---|
A2AClientHTTPError
|
If an HTTP error occurs during the request. |
A2AClientJSONError
|
If the response body cannot be decoded as JSON or validated. |
legacy_grpc
¶
Backwards compatibility layer for the legacy A2A gRPC client.
A2AGrpcClient
¶
Bases: GrpcTransport
[DEPRECATED] Backwards compatibility wrapper for the gRPC client.
cancel_task(request, *, context=None)
async
¶
Requests the agent to cancel a specific task.
close()
async
¶
Closes the gRPC channel.
create(card, url, config, interceptors)
classmethod
¶
Creates a gRPC transport for the A2A client.
get_card(*, context=None)
async
¶
Retrieves the agent's card.
get_task(request, *, context=None)
async
¶
Retrieves the current state and history of a specific task.
get_task_callback(request, *, context=None)
async
¶
Retrieves the push notification configuration for a specific task.
resubscribe(request, *, context=None)
async
¶
Reconnects to get task updates.
send_message(request, *, context=None)
async
¶
Sends a non-streaming message request to the agent.
send_message_streaming(request, *, context=None)
async
¶
Sends a streaming message request to the agent and yields responses as they arrive.
set_task_callback(request, *, context=None)
async
¶
Sets or updates the push notification configuration for a specific task.
middleware
¶
ClientCallContext
¶
Bases: BaseModel
A context passed with each client call, allowing for call-specific.
configuration and data passing. Such as authentication details or request deadlines.
ClientCallInterceptor
¶
Bases: ABC
An abstract base class for client-side call interceptors.
Interceptors can inspect and modify requests before they are sent, which is ideal for concerns like authentication, logging, or tracing.
intercept(method_name, request_payload, http_kwargs, agent_card, context)
abstractmethod
async
¶
Intercepts a client call before the request is sent.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
method_name
|
str
|
The name of the RPC method (e.g., 'message/send'). |
required |
request_payload
|
dict[str, Any]
|
The JSON RPC request payload dictionary. |
required |
http_kwargs
|
dict[str, Any]
|
The keyword arguments for the httpx request. |
required |
agent_card
|
AgentCard | None
|
The AgentCard associated with the client. |
required |
context
|
ClientCallContext | None
|
The ClientCallContext for this specific call. |
required |
Returns:
Type | Description |
---|---|
dict[str, Any]
|
A tuple containing the (potentially modified) request_payload |
dict[str, Any]
|
and http_kwargs. |
transports
¶
A2A Client Transports.
ClientTransport
¶
Bases: ABC
Abstract base class for a client transport.
cancel_task(request, *, context=None)
abstractmethod
async
¶
Requests the agent to cancel a specific task.
close()
abstractmethod
async
¶
Closes the transport.
get_card(*, context=None)
abstractmethod
async
¶
Retrieves the AgentCard.
get_task(request, *, context=None)
abstractmethod
async
¶
Retrieves the current state and history of a specific task.
get_task_callback(request, *, context=None)
abstractmethod
async
¶
Retrieves the push notification configuration for a specific task.
resubscribe(request, *, context=None)
abstractmethod
async
¶
Reconnects to get task updates.
send_message(request, *, context=None)
abstractmethod
async
¶
Sends a non-streaming message request to the agent.
send_message_streaming(request, *, context=None)
abstractmethod
async
¶
Sends a streaming message request to the agent and yields responses as they arrive.
set_task_callback(request, *, context=None)
abstractmethod
async
¶
Sets or updates the push notification configuration for a specific task.
GrpcTransport
¶
Bases: ClientTransport
A gRPC transport for the A2A client.
__init__(channel, agent_card)
¶
Initializes the GrpcTransport.
cancel_task(request, *, context=None)
async
¶
Requests the agent to cancel a specific task.
close()
async
¶
Closes the gRPC channel.
create(card, url, config, interceptors)
classmethod
¶
Creates a gRPC transport for the A2A client.
get_card(*, context=None)
async
¶
Retrieves the agent's card.
get_task(request, *, context=None)
async
¶
Retrieves the current state and history of a specific task.
get_task_callback(request, *, context=None)
async
¶
Retrieves the push notification configuration for a specific task.
resubscribe(request, *, context=None)
async
¶
Reconnects to get task updates.
send_message(request, *, context=None)
async
¶
Sends a non-streaming message request to the agent.
send_message_streaming(request, *, context=None)
async
¶
Sends a streaming message request to the agent and yields responses as they arrive.
set_task_callback(request, *, context=None)
async
¶
Sets or updates the push notification configuration for a specific task.
JsonRpcTransport
¶
Bases: ClientTransport
A JSON-RPC transport for the A2A client.
__init__(httpx_client, agent_card=None, url=None, interceptors=None)
¶
Initializes the JsonRpcTransport.
cancel_task(request, *, context=None)
async
¶
Requests the agent to cancel a specific task.
close()
async
¶
Closes the httpx client.
get_card(*, context=None)
async
¶
Retrieves the agent's card.
get_task(request, *, context=None)
async
¶
Retrieves the current state and history of a specific task.
get_task_callback(request, *, context=None)
async
¶
Retrieves the push notification configuration for a specific task.
resubscribe(request, *, context=None)
async
¶
Reconnects to get task updates.
send_message(request, *, context=None)
async
¶
Sends a non-streaming message request to the agent.
send_message_streaming(request, *, context=None)
async
¶
Sends a streaming message request to the agent and yields responses as they arrive.
set_task_callback(request, *, context=None)
async
¶
Sets or updates the push notification configuration for a specific task.
RestTransport
¶
Bases: ClientTransport
A REST transport for the A2A client.
__init__(httpx_client, agent_card=None, url=None, interceptors=None)
¶
Initializes the RestTransport.
cancel_task(request, *, context=None)
async
¶
Requests the agent to cancel a specific task.
close()
async
¶
Closes the httpx client.
get_card(*, context=None)
async
¶
Retrieves the agent's card.
get_task(request, *, context=None)
async
¶
Retrieves the current state and history of a specific task.
get_task_callback(request, *, context=None)
async
¶
Retrieves the push notification configuration for a specific task.
resubscribe(request, *, context=None)
async
¶
Reconnects to get task updates.
send_message(request, *, context=None)
async
¶
Sends a non-streaming message request to the agent.
send_message_streaming(request, *, context=None)
async
¶
Sends a streaming message request to the agent and yields responses as they arrive.
set_task_callback(request, *, context=None)
async
¶
Sets or updates the push notification configuration for a specific task.
base
¶
ClientTransport
¶
Bases: ABC
Abstract base class for a client transport.
cancel_task(request, *, context=None)
abstractmethod
async
¶
Requests the agent to cancel a specific task.
close()
abstractmethod
async
¶
Closes the transport.
get_card(*, context=None)
abstractmethod
async
¶
Retrieves the AgentCard.
get_task(request, *, context=None)
abstractmethod
async
¶
Retrieves the current state and history of a specific task.
get_task_callback(request, *, context=None)
abstractmethod
async
¶
Retrieves the push notification configuration for a specific task.
resubscribe(request, *, context=None)
abstractmethod
async
¶
Reconnects to get task updates.
send_message(request, *, context=None)
abstractmethod
async
¶
Sends a non-streaming message request to the agent.
send_message_streaming(request, *, context=None)
abstractmethod
async
¶
Sends a streaming message request to the agent and yields responses as they arrive.
set_task_callback(request, *, context=None)
abstractmethod
async
¶
Sets or updates the push notification configuration for a specific task.
grpc
¶
GrpcTransport
¶
Bases: ClientTransport
A gRPC transport for the A2A client.
__init__(channel, agent_card)
¶
Initializes the GrpcTransport.
cancel_task(request, *, context=None)
async
¶
Requests the agent to cancel a specific task.
close()
async
¶
Closes the gRPC channel.
create(card, url, config, interceptors)
classmethod
¶
Creates a gRPC transport for the A2A client.
get_card(*, context=None)
async
¶
Retrieves the agent's card.
get_task(request, *, context=None)
async
¶
Retrieves the current state and history of a specific task.
get_task_callback(request, *, context=None)
async
¶
Retrieves the push notification configuration for a specific task.
resubscribe(request, *, context=None)
async
¶
Reconnects to get task updates.
send_message(request, *, context=None)
async
¶
Sends a non-streaming message request to the agent.
send_message_streaming(request, *, context=None)
async
¶
Sends a streaming message request to the agent and yields responses as they arrive.
set_task_callback(request, *, context=None)
async
¶
Sets or updates the push notification configuration for a specific task.
jsonrpc
¶
JsonRpcTransport
¶
Bases: ClientTransport
A JSON-RPC transport for the A2A client.
__init__(httpx_client, agent_card=None, url=None, interceptors=None)
¶
Initializes the JsonRpcTransport.
cancel_task(request, *, context=None)
async
¶
Requests the agent to cancel a specific task.
close()
async
¶
Closes the httpx client.
get_card(*, context=None)
async
¶
Retrieves the agent's card.
get_task(request, *, context=None)
async
¶
Retrieves the current state and history of a specific task.
get_task_callback(request, *, context=None)
async
¶
Retrieves the push notification configuration for a specific task.
resubscribe(request, *, context=None)
async
¶
Reconnects to get task updates.
send_message(request, *, context=None)
async
¶
Sends a non-streaming message request to the agent.
send_message_streaming(request, *, context=None)
async
¶
Sends a streaming message request to the agent and yields responses as they arrive.
set_task_callback(request, *, context=None)
async
¶
Sets or updates the push notification configuration for a specific task.
rest
¶
RestTransport
¶
Bases: ClientTransport
A REST transport for the A2A client.
__init__(httpx_client, agent_card=None, url=None, interceptors=None)
¶
Initializes the RestTransport.
cancel_task(request, *, context=None)
async
¶
Requests the agent to cancel a specific task.
close()
async
¶
Closes the httpx client.
get_card(*, context=None)
async
¶
Retrieves the agent's card.
get_task(request, *, context=None)
async
¶
Retrieves the current state and history of a specific task.
get_task_callback(request, *, context=None)
async
¶
Retrieves the push notification configuration for a specific task.
resubscribe(request, *, context=None)
async
¶
Reconnects to get task updates.
send_message(request, *, context=None)
async
¶
Sends a non-streaming message request to the agent.
send_message_streaming(request, *, context=None)
async
¶
Sends a streaming message request to the agent and yields responses as they arrive.
set_task_callback(request, *, context=None)
async
¶
Sets or updates the push notification configuration for a specific task.
grpc
¶
a2a_pb2
¶
Generated protocol buffer code.
a2a_pb2_grpc
¶
Client and server classes corresponding to protobuf-defined services.
A2AService
¶
Bases: object
A2AService defines the gRPC version of the A2A protocol. This has a slightly different shape than the JSONRPC version to better conform to AIP-127, where appropriate. The nouns are AgentCard, Message, Task and TaskPushNotificationConfig. - Messages are not a standard resource so there is no get/delete/update/list interface, only a send and stream custom methods. - Tasks have a get interface and custom cancel and subscribe methods. - TaskPushNotificationConfig are a resource whose parent is a task. They have get, list and create methods. - AgentCard is a static resource with only a get method.
A2AServiceServicer
¶
Bases: object
A2AService defines the gRPC version of the A2A protocol. This has a slightly different shape than the JSONRPC version to better conform to AIP-127, where appropriate. The nouns are AgentCard, Message, Task and TaskPushNotificationConfig. - Messages are not a standard resource so there is no get/delete/update/list interface, only a send and stream custom methods. - Tasks have a get interface and custom cancel and subscribe methods. - TaskPushNotificationConfig are a resource whose parent is a task. They have get, list and create methods. - AgentCard is a static resource with only a get method.
CancelTask(request, context)
¶
Cancel a task from the agent. If supported one should expect no more task updates for the task.
CreateTaskPushNotificationConfig(request, context)
¶
Set a push notification config for a task.
DeleteTaskPushNotificationConfig(request, context)
¶
Delete a push notification config for a task.
GetAgentCard(request, context)
¶
GetAgentCard returns the agent card for the agent.
GetTask(request, context)
¶
Get the current state of a task from the agent.
GetTaskPushNotificationConfig(request, context)
¶
Get a push notification config for a task.
ListTaskPushNotificationConfig(request, context)
¶
Get a list of push notifications configured for a task.
SendMessage(request, context)
¶
Send a message to the agent. This is a blocking call that will return the task once it is completed, or a LRO if requested.
SendStreamingMessage(request, context)
¶
SendStreamingMessage is a streaming call that will return a stream of task update events until the Task is in an interrupted or terminal state.
TaskSubscription(request, context)
¶
TaskSubscription is a streaming call that will return a stream of task update events. This attaches the stream to an existing in process task. If the task is complete the stream will return the completed task (like GetTask) and close the stream.
A2AServiceStub
¶
Bases: object
A2AService defines the gRPC version of the A2A protocol. This has a slightly different shape than the JSONRPC version to better conform to AIP-127, where appropriate. The nouns are AgentCard, Message, Task and TaskPushNotificationConfig. - Messages are not a standard resource so there is no get/delete/update/list interface, only a send and stream custom methods. - Tasks have a get interface and custom cancel and subscribe methods. - TaskPushNotificationConfig are a resource whose parent is a task. They have get, list and create methods. - AgentCard is a static resource with only a get method.
__init__(channel)
¶
Constructor.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
channel
|
A grpc.Channel. |
required |
server
¶
Server-side components for implementing an A2A agent.
agent_execution
¶
Components for executing agent logic within the A2A server.
AgentExecutor
¶
Bases: ABC
Agent Executor interface.
Implementations of this interface contain the core logic of the agent, executing tasks based on requests and publishing updates to an event queue.
cancel(context, event_queue)
abstractmethod
async
¶
Request the agent to cancel an ongoing task.
The agent should attempt to stop the task identified by the task_id
in the context and publish a TaskStatusUpdateEvent
with state
TaskState.canceled
to the event_queue
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
context
|
RequestContext
|
The request context containing the task ID to cancel. |
required |
event_queue
|
EventQueue
|
The queue to publish the cancellation status update to. |
required |
execute(context, event_queue)
abstractmethod
async
¶
Execute the agent's logic for a given request context.
The agent should read necessary information from the context
and
publish Task
or Message
events, or TaskStatusUpdateEvent
/
TaskArtifactUpdateEvent
to the event_queue
. This method should
return once the agent's execution for this request is complete or
yields control (e.g., enters an input-required state).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
context
|
RequestContext
|
The request context containing the message, task ID, etc. |
required |
event_queue
|
EventQueue
|
The queue to publish events to. |
required |
RequestContext
¶
Request Context.
Holds information about the current request being processed by the server, including the incoming message, task and context identifiers, and related tasks.
call_context
property
¶
The server call context associated with this request.
configuration
property
¶
The MessageSendConfiguration
from the request, if available.
context_id
property
¶
The ID of the conversation context associated with this task.
current_task
property
writable
¶
The current Task
object being processed.
message
property
¶
The incoming Message
object from the request, if available.
metadata
property
¶
Metadata associated with the request, if available.
related_tasks
property
¶
A list of tasks related to the current request.
requested_extensions
property
¶
Extensions that the client requested to activate.
task_id
property
¶
The ID of the task associated with this context.
__init__(request=None, task_id=None, context_id=None, task=None, related_tasks=None, call_context=None)
¶
Initializes the RequestContext.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
MessageSendParams | None
|
The incoming |
None
|
task_id
|
str | None
|
The ID of the task explicitly provided in the request or path. |
None
|
context_id
|
str | None
|
The ID of the context explicitly provided in the request or path. |
None
|
task
|
Task | None
|
The existing |
None
|
related_tasks
|
list[Task] | None
|
A list of other tasks related to the current request (e.g., for tool use). |
None
|
call_context
|
ServerCallContext | None
|
The server call context associated with this request. |
None
|
add_activated_extension(uri)
¶
Add an extension to the set of activated extensions for this request.
This causes the extension to be indicated back to the client in the response.
attach_related_task(task)
¶
Attaches a related task to the context.
This is useful for scenarios like tool execution where a new task might be spawned.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
task
|
Task
|
The |
required |
get_user_input(delimiter='\n')
¶
Extracts text content from the user's message parts.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
delimiter
|
str
|
The string to use when joining multiple text parts. |
'\n'
|
Returns:
Type | Description |
---|---|
str
|
A single string containing all text content from the user message, |
str
|
joined by the specified delimiter. Returns an empty string if no |
str
|
user message is present or if it contains no text parts. |
RequestContextBuilder
¶
Bases: ABC
Builds request context to be supplied to agent executor.
SimpleRequestContextBuilder
¶
Bases: RequestContextBuilder
Builds request context and populates referred tasks.
__init__(should_populate_referred_tasks=False, task_store=None)
¶
Initializes the SimpleRequestContextBuilder.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
should_populate_referred_tasks
|
bool
|
If True, the builder will fetch tasks
referenced in |
False
|
task_store
|
TaskStore | None
|
The TaskStore instance to use for fetching referred tasks.
Required if |
None
|
build(params=None, task_id=None, context_id=None, task=None, context=None)
async
¶
Builds the request context for an agent execution.
This method assembles the RequestContext object. If the builder was
initialized with should_populate_referred_tasks=True
, it fetches all tasks
referenced in params.message.reference_task_ids
from the task_store
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
params
|
MessageSendParams | None
|
The parameters of the incoming message send request. |
None
|
task_id
|
str | None
|
The ID of the task being executed. |
None
|
context_id
|
str | None
|
The ID of the current execution context. |
None
|
task
|
Task | None
|
The primary task object associated with the request. |
None
|
context
|
ServerCallContext | None
|
The server call context, containing metadata about the call. |
None
|
Returns:
Type | Description |
---|---|
RequestContext
|
An instance of RequestContext populated with the provided information |
RequestContext
|
and potentially a list of related tasks. |
agent_executor
¶
AgentExecutor
¶
Bases: ABC
Agent Executor interface.
Implementations of this interface contain the core logic of the agent, executing tasks based on requests and publishing updates to an event queue.
cancel(context, event_queue)
abstractmethod
async
¶
Request the agent to cancel an ongoing task.
The agent should attempt to stop the task identified by the task_id
in the context and publish a TaskStatusUpdateEvent
with state
TaskState.canceled
to the event_queue
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
context
|
RequestContext
|
The request context containing the task ID to cancel. |
required |
event_queue
|
EventQueue
|
The queue to publish the cancellation status update to. |
required |
execute(context, event_queue)
abstractmethod
async
¶
Execute the agent's logic for a given request context.
The agent should read necessary information from the context
and
publish Task
or Message
events, or TaskStatusUpdateEvent
/
TaskArtifactUpdateEvent
to the event_queue
. This method should
return once the agent's execution for this request is complete or
yields control (e.g., enters an input-required state).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
context
|
RequestContext
|
The request context containing the message, task ID, etc. |
required |
event_queue
|
EventQueue
|
The queue to publish events to. |
required |
context
¶
RequestContext
¶
Request Context.
Holds information about the current request being processed by the server, including the incoming message, task and context identifiers, and related tasks.
call_context
property
¶
The server call context associated with this request.
configuration
property
¶
The MessageSendConfiguration
from the request, if available.
context_id
property
¶
The ID of the conversation context associated with this task.
current_task
property
writable
¶
The current Task
object being processed.
message
property
¶
The incoming Message
object from the request, if available.
metadata
property
¶
Metadata associated with the request, if available.
related_tasks
property
¶
A list of tasks related to the current request.
requested_extensions
property
¶
Extensions that the client requested to activate.
task_id
property
¶
The ID of the task associated with this context.
__init__(request=None, task_id=None, context_id=None, task=None, related_tasks=None, call_context=None)
¶
Initializes the RequestContext.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
MessageSendParams | None
|
The incoming |
None
|
task_id
|
str | None
|
The ID of the task explicitly provided in the request or path. |
None
|
context_id
|
str | None
|
The ID of the context explicitly provided in the request or path. |
None
|
task
|
Task | None
|
The existing |
None
|
related_tasks
|
list[Task] | None
|
A list of other tasks related to the current request (e.g., for tool use). |
None
|
call_context
|
ServerCallContext | None
|
The server call context associated with this request. |
None
|
add_activated_extension(uri)
¶
Add an extension to the set of activated extensions for this request.
This causes the extension to be indicated back to the client in the response.
attach_related_task(task)
¶
Attaches a related task to the context.
This is useful for scenarios like tool execution where a new task might be spawned.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
task
|
Task
|
The |
required |
get_user_input(delimiter='\n')
¶
Extracts text content from the user's message parts.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
delimiter
|
str
|
The string to use when joining multiple text parts. |
'\n'
|
Returns:
Type | Description |
---|---|
str
|
A single string containing all text content from the user message, |
str
|
joined by the specified delimiter. Returns an empty string if no |
str
|
user message is present or if it contains no text parts. |
request_context_builder
¶
RequestContextBuilder
¶
Bases: ABC
Builds request context to be supplied to agent executor.
simple_request_context_builder
¶
SimpleRequestContextBuilder
¶
Bases: RequestContextBuilder
Builds request context and populates referred tasks.
__init__(should_populate_referred_tasks=False, task_store=None)
¶
Initializes the SimpleRequestContextBuilder.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
should_populate_referred_tasks
|
bool
|
If True, the builder will fetch tasks
referenced in |
False
|
task_store
|
TaskStore | None
|
The TaskStore instance to use for fetching referred tasks.
Required if |
None
|
build(params=None, task_id=None, context_id=None, task=None, context=None)
async
¶
Builds the request context for an agent execution.
This method assembles the RequestContext object. If the builder was
initialized with should_populate_referred_tasks=True
, it fetches all tasks
referenced in params.message.reference_task_ids
from the task_store
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
params
|
MessageSendParams | None
|
The parameters of the incoming message send request. |
None
|
task_id
|
str | None
|
The ID of the task being executed. |
None
|
context_id
|
str | None
|
The ID of the current execution context. |
None
|
task
|
Task | None
|
The primary task object associated with the request. |
None
|
context
|
ServerCallContext | None
|
The server call context, containing metadata about the call. |
None
|
Returns:
Type | Description |
---|---|
RequestContext
|
An instance of RequestContext populated with the provided information |
RequestContext
|
and potentially a list of related tasks. |
apps
¶
HTTP application components for the A2A server.
A2AFastAPIApplication
¶
Bases: JSONRPCApplication
A FastAPI application implementing the A2A protocol server endpoints.
Handles incoming JSON-RPC requests, routes them to the appropriate handler methods, and manages response generation including Server-Sent Events (SSE).
__init__(agent_card, http_handler, extended_agent_card=None, context_builder=None, card_modifier=None, extended_card_modifier=None)
¶
Initializes the A2AFastAPIApplication.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
agent_card
|
AgentCard
|
The AgentCard describing the agent's capabilities. |
required |
http_handler
|
RequestHandler
|
The handler instance responsible for processing A2A requests via http. |
required |
extended_agent_card
|
AgentCard | None
|
An optional, distinct AgentCard to be served at the authenticated extended card endpoint. |
None
|
context_builder
|
CallContextBuilder | None
|
The CallContextBuilder used to construct the ServerCallContext passed to the http_handler. If None, no ServerCallContext is passed. |
None
|
card_modifier
|
Callable[[AgentCard], AgentCard] | None
|
An optional callback to dynamically modify the public agent card before it is served. |
None
|
extended_card_modifier
|
Callable[[AgentCard, ServerCallContext], AgentCard] | None
|
An optional callback to dynamically modify the extended agent card before it is served. It receives the call context. |
None
|
add_routes_to_app(app, agent_card_url=AGENT_CARD_WELL_KNOWN_PATH, rpc_url=DEFAULT_RPC_URL, extended_agent_card_url=EXTENDED_AGENT_CARD_PATH)
¶
Adds the routes to the FastAPI application.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
app
|
FastAPI
|
The FastAPI application to add the routes to. |
required |
agent_card_url
|
str
|
The URL for the agent card endpoint. |
AGENT_CARD_WELL_KNOWN_PATH
|
rpc_url
|
str
|
The URL for the A2A JSON-RPC endpoint. |
DEFAULT_RPC_URL
|
extended_agent_card_url
|
str
|
The URL for the authenticated extended agent card endpoint. |
EXTENDED_AGENT_CARD_PATH
|
build(agent_card_url=AGENT_CARD_WELL_KNOWN_PATH, rpc_url=DEFAULT_RPC_URL, extended_agent_card_url=EXTENDED_AGENT_CARD_PATH, **kwargs)
¶
Builds and returns the FastAPI application instance.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
agent_card_url
|
str
|
The URL for the agent card endpoint. |
AGENT_CARD_WELL_KNOWN_PATH
|
rpc_url
|
str
|
The URL for the A2A JSON-RPC endpoint. |
DEFAULT_RPC_URL
|
extended_agent_card_url
|
str
|
The URL for the authenticated extended agent card endpoint. |
EXTENDED_AGENT_CARD_PATH
|
**kwargs
|
Any
|
Additional keyword arguments to pass to the FastAPI constructor. |
{}
|
Returns:
Type | Description |
---|---|
FastAPI
|
A configured FastAPI application instance. |
A2ARESTFastAPIApplication
¶
A FastAPI application implementing the A2A protocol server REST endpoints.
Handles incoming REST requests, routes them to the appropriate handler methods, and manages response generation including Server-Sent Events (SSE).
__init__(agent_card, http_handler, extended_agent_card=None, context_builder=None, card_modifier=None, extended_card_modifier=None)
¶
Initializes the A2ARESTFastAPIApplication.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
agent_card
|
AgentCard
|
The AgentCard describing the agent's capabilities. |
required |
http_handler
|
RequestHandler
|
The handler instance responsible for processing A2A requests via http. |
required |
extended_agent_card
|
AgentCard | None
|
An optional, distinct AgentCard to be served at the authenticated extended card endpoint. |
None
|
context_builder
|
CallContextBuilder | None
|
The CallContextBuilder used to construct the ServerCallContext passed to the http_handler. If None, no ServerCallContext is passed. |
None
|
card_modifier
|
Callable[[AgentCard], AgentCard] | None
|
An optional callback to dynamically modify the public agent card before it is served. |
None
|
extended_card_modifier
|
Callable[[AgentCard, ServerCallContext], AgentCard] | None
|
An optional callback to dynamically modify the extended agent card before it is served. It receives the call context. |
None
|
build(agent_card_url=AGENT_CARD_WELL_KNOWN_PATH, rpc_url='', **kwargs)
¶
Builds and returns the FastAPI application instance.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
agent_card_url
|
str
|
The URL for the agent card endpoint. |
AGENT_CARD_WELL_KNOWN_PATH
|
rpc_url
|
str
|
The URL for the A2A JSON-RPC endpoint. |
''
|
extended_agent_card_url
|
The URL for the authenticated extended agent card endpoint. |
required | |
**kwargs
|
Any
|
Additional keyword arguments to pass to the FastAPI constructor. |
{}
|
Returns:
Type | Description |
---|---|
FastAPI
|
A configured FastAPI application instance. |
A2AStarletteApplication
¶
Bases: JSONRPCApplication
A Starlette application implementing the A2A protocol server endpoints.
Handles incoming JSON-RPC requests, routes them to the appropriate handler methods, and manages response generation including Server-Sent Events (SSE).
__init__(agent_card, http_handler, extended_agent_card=None, context_builder=None, card_modifier=None, extended_card_modifier=None)
¶
Initializes the A2AStarletteApplication.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
agent_card
|
AgentCard
|
The AgentCard describing the agent's capabilities. |
required |
http_handler
|
RequestHandler
|
The handler instance responsible for processing A2A requests via http. |
required |
extended_agent_card
|
AgentCard | None
|
An optional, distinct AgentCard to be served at the authenticated extended card endpoint. |
None
|
context_builder
|
CallContextBuilder | None
|
The CallContextBuilder used to construct the ServerCallContext passed to the http_handler. If None, no ServerCallContext is passed. |
None
|
card_modifier
|
Callable[[AgentCard], AgentCard] | None
|
An optional callback to dynamically modify the public agent card before it is served. |
None
|
extended_card_modifier
|
Callable[[AgentCard, ServerCallContext], AgentCard] | None
|
An optional callback to dynamically modify the extended agent card before it is served. It receives the call context. |
None
|
add_routes_to_app(app, agent_card_url=AGENT_CARD_WELL_KNOWN_PATH, rpc_url=DEFAULT_RPC_URL, extended_agent_card_url=EXTENDED_AGENT_CARD_PATH)
¶
Adds the routes to the Starlette application.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
app
|
Starlette
|
The Starlette application to add the routes to. |
required |
agent_card_url
|
str
|
The URL path for the agent card endpoint. |
AGENT_CARD_WELL_KNOWN_PATH
|
rpc_url
|
str
|
The URL path for the A2A JSON-RPC endpoint (POST requests). |
DEFAULT_RPC_URL
|
extended_agent_card_url
|
str
|
The URL for the authenticated extended agent card endpoint. |
EXTENDED_AGENT_CARD_PATH
|
build(agent_card_url=AGENT_CARD_WELL_KNOWN_PATH, rpc_url=DEFAULT_RPC_URL, extended_agent_card_url=EXTENDED_AGENT_CARD_PATH, **kwargs)
¶
Builds and returns the Starlette application instance.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
agent_card_url
|
str
|
The URL path for the agent card endpoint. |
AGENT_CARD_WELL_KNOWN_PATH
|
rpc_url
|
str
|
The URL path for the A2A JSON-RPC endpoint (POST requests). |
DEFAULT_RPC_URL
|
extended_agent_card_url
|
str
|
The URL for the authenticated extended agent card endpoint. |
EXTENDED_AGENT_CARD_PATH
|
**kwargs
|
Any
|
Additional keyword arguments to pass to the Starlette constructor. |
{}
|
Returns:
Type | Description |
---|---|
Starlette
|
A configured Starlette application instance. |
routes(agent_card_url=AGENT_CARD_WELL_KNOWN_PATH, rpc_url=DEFAULT_RPC_URL, extended_agent_card_url=EXTENDED_AGENT_CARD_PATH)
¶
Returns the Starlette Routes for handling A2A requests.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
agent_card_url
|
str
|
The URL path for the agent card endpoint. |
AGENT_CARD_WELL_KNOWN_PATH
|
rpc_url
|
str
|
The URL path for the A2A JSON-RPC endpoint (POST requests). |
DEFAULT_RPC_URL
|
extended_agent_card_url
|
str
|
The URL for the authenticated extended agent card endpoint. |
EXTENDED_AGENT_CARD_PATH
|
Returns:
Type | Description |
---|---|
list[Route]
|
A list of Starlette Route objects. |
CallContextBuilder
¶
Bases: ABC
A class for building ServerCallContexts using the Starlette Request.
build(request)
abstractmethod
¶
Builds a ServerCallContext from a Starlette Request.
JSONRPCApplication
¶
Bases: 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).
__init__(agent_card, http_handler, extended_agent_card=None, context_builder=None, card_modifier=None, extended_card_modifier=None)
¶
Initializes the JSONRPCApplication.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
agent_card
|
AgentCard
|
The AgentCard describing the agent's capabilities. |
required |
http_handler
|
RequestHandler
|
The handler instance responsible for processing A2A requests via http. |
required |
extended_agent_card
|
AgentCard | None
|
An optional, distinct AgentCard to be served at the authenticated extended card endpoint. |
None
|
context_builder
|
CallContextBuilder | None
|
The CallContextBuilder used to construct the ServerCallContext passed to the http_handler. If None, no ServerCallContext is passed. |
None
|
card_modifier
|
Callable[[AgentCard], AgentCard] | None
|
An optional callback to dynamically modify the public agent card before it is served. |
None
|
extended_card_modifier
|
Callable[[AgentCard, ServerCallContext], AgentCard] | None
|
An optional callback to dynamically modify the extended agent card before it is served. It receives the call context. |
None
|
build(agent_card_url=AGENT_CARD_WELL_KNOWN_PATH, rpc_url=DEFAULT_RPC_URL, extended_agent_card_url=EXTENDED_AGENT_CARD_PATH, **kwargs)
abstractmethod
¶
Builds and returns the JSONRPC application instance.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
agent_card_url
|
str
|
The URL for the agent card endpoint. |
AGENT_CARD_WELL_KNOWN_PATH
|
rpc_url
|
str
|
The URL for the A2A JSON-RPC endpoint. |
DEFAULT_RPC_URL
|
extended_agent_card_url
|
str
|
The URL for the authenticated extended agent card endpoint. |
EXTENDED_AGENT_CARD_PATH
|
**kwargs
|
Any
|
Additional keyword arguments to pass to the FastAPI constructor. |
{}
|
Returns:
Type | Description |
---|---|
FastAPI | Starlette
|
A configured JSONRPC application instance. |
jsonrpc
¶
A2A JSON-RPC Applications.
A2AFastAPIApplication
¶
Bases: JSONRPCApplication
A FastAPI application implementing the A2A protocol server endpoints.
Handles incoming JSON-RPC requests, routes them to the appropriate handler methods, and manages response generation including Server-Sent Events (SSE).
__init__(agent_card, http_handler, extended_agent_card=None, context_builder=None, card_modifier=None, extended_card_modifier=None)
¶
Initializes the A2AFastAPIApplication.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
agent_card
|
AgentCard
|
The AgentCard describing the agent's capabilities. |
required |
http_handler
|
RequestHandler
|
The handler instance responsible for processing A2A requests via http. |
required |
extended_agent_card
|
AgentCard | None
|
An optional, distinct AgentCard to be served at the authenticated extended card endpoint. |
None
|
context_builder
|
CallContextBuilder | None
|
The CallContextBuilder used to construct the ServerCallContext passed to the http_handler. If None, no ServerCallContext is passed. |
None
|
card_modifier
|
Callable[[AgentCard], AgentCard] | None
|
An optional callback to dynamically modify the public agent card before it is served. |
None
|
extended_card_modifier
|
Callable[[AgentCard, ServerCallContext], AgentCard] | None
|
An optional callback to dynamically modify the extended agent card before it is served. It receives the call context. |
None
|
add_routes_to_app(app, agent_card_url=AGENT_CARD_WELL_KNOWN_PATH, rpc_url=DEFAULT_RPC_URL, extended_agent_card_url=EXTENDED_AGENT_CARD_PATH)
¶
Adds the routes to the FastAPI application.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
app
|
FastAPI
|
The FastAPI application to add the routes to. |
required |
agent_card_url
|
str
|
The URL for the agent card endpoint. |
AGENT_CARD_WELL_KNOWN_PATH
|
rpc_url
|
str
|
The URL for the A2A JSON-RPC endpoint. |
DEFAULT_RPC_URL
|
extended_agent_card_url
|
str
|
The URL for the authenticated extended agent card endpoint. |
EXTENDED_AGENT_CARD_PATH
|
build(agent_card_url=AGENT_CARD_WELL_KNOWN_PATH, rpc_url=DEFAULT_RPC_URL, extended_agent_card_url=EXTENDED_AGENT_CARD_PATH, **kwargs)
¶
Builds and returns the FastAPI application instance.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
agent_card_url
|
str
|
The URL for the agent card endpoint. |
AGENT_CARD_WELL_KNOWN_PATH
|
rpc_url
|
str
|
The URL for the A2A JSON-RPC endpoint. |
DEFAULT_RPC_URL
|
extended_agent_card_url
|
str
|
The URL for the authenticated extended agent card endpoint. |
EXTENDED_AGENT_CARD_PATH
|
**kwargs
|
Any
|
Additional keyword arguments to pass to the FastAPI constructor. |
{}
|
Returns:
Type | Description |
---|---|
FastAPI
|
A configured FastAPI application instance. |
A2AStarletteApplication
¶
Bases: JSONRPCApplication
A Starlette application implementing the A2A protocol server endpoints.
Handles incoming JSON-RPC requests, routes them to the appropriate handler methods, and manages response generation including Server-Sent Events (SSE).
__init__(agent_card, http_handler, extended_agent_card=None, context_builder=None, card_modifier=None, extended_card_modifier=None)
¶
Initializes the A2AStarletteApplication.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
agent_card
|
AgentCard
|
The AgentCard describing the agent's capabilities. |
required |
http_handler
|
RequestHandler
|
The handler instance responsible for processing A2A requests via http. |
required |
extended_agent_card
|
AgentCard | None
|
An optional, distinct AgentCard to be served at the authenticated extended card endpoint. |
None
|
context_builder
|
CallContextBuilder | None
|
The CallContextBuilder used to construct the ServerCallContext passed to the http_handler. If None, no ServerCallContext is passed. |
None
|
card_modifier
|
Callable[[AgentCard], AgentCard] | None
|
An optional callback to dynamically modify the public agent card before it is served. |
None
|
extended_card_modifier
|
Callable[[AgentCard, ServerCallContext], AgentCard] | None
|
An optional callback to dynamically modify the extended agent card before it is served. It receives the call context. |
None
|
add_routes_to_app(app, agent_card_url=AGENT_CARD_WELL_KNOWN_PATH, rpc_url=DEFAULT_RPC_URL, extended_agent_card_url=EXTENDED_AGENT_CARD_PATH)
¶
Adds the routes to the Starlette application.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
app
|
Starlette
|
The Starlette application to add the routes to. |
required |
agent_card_url
|
str
|
The URL path for the agent card endpoint. |
AGENT_CARD_WELL_KNOWN_PATH
|
rpc_url
|
str
|
The URL path for the A2A JSON-RPC endpoint (POST requests). |
DEFAULT_RPC_URL
|
extended_agent_card_url
|
str
|
The URL for the authenticated extended agent card endpoint. |
EXTENDED_AGENT_CARD_PATH
|
build(agent_card_url=AGENT_CARD_WELL_KNOWN_PATH, rpc_url=DEFAULT_RPC_URL, extended_agent_card_url=EXTENDED_AGENT_CARD_PATH, **kwargs)
¶
Builds and returns the Starlette application instance.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
agent_card_url
|
str
|
The URL path for the agent card endpoint. |
AGENT_CARD_WELL_KNOWN_PATH
|
rpc_url
|
str
|
The URL path for the A2A JSON-RPC endpoint (POST requests). |
DEFAULT_RPC_URL
|
extended_agent_card_url
|
str
|
The URL for the authenticated extended agent card endpoint. |
EXTENDED_AGENT_CARD_PATH
|
**kwargs
|
Any
|
Additional keyword arguments to pass to the Starlette constructor. |
{}
|
Returns:
Type | Description |
---|---|
Starlette
|
A configured Starlette application instance. |
routes(agent_card_url=AGENT_CARD_WELL_KNOWN_PATH, rpc_url=DEFAULT_RPC_URL, extended_agent_card_url=EXTENDED_AGENT_CARD_PATH)
¶
Returns the Starlette Routes for handling A2A requests.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
agent_card_url
|
str
|
The URL path for the agent card endpoint. |
AGENT_CARD_WELL_KNOWN_PATH
|
rpc_url
|
str
|
The URL path for the A2A JSON-RPC endpoint (POST requests). |
DEFAULT_RPC_URL
|
extended_agent_card_url
|
str
|
The URL for the authenticated extended agent card endpoint. |
EXTENDED_AGENT_CARD_PATH
|
Returns:
Type | Description |
---|---|
list[Route]
|
A list of Starlette Route objects. |
CallContextBuilder
¶
Bases: ABC
A class for building ServerCallContexts using the Starlette Request.
build(request)
abstractmethod
¶
Builds a ServerCallContext from a Starlette Request.
DefaultCallContextBuilder
¶
Bases: CallContextBuilder
A default implementation of CallContextBuilder.
build(request)
¶
Builds a ServerCallContext from a Starlette Request.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
Request
|
The incoming Starlette Request object. |
required |
Returns:
Type | Description |
---|---|
ServerCallContext
|
A ServerCallContext instance populated with user and state |
ServerCallContext
|
information from the request. |
JSONRPCApplication
¶
Bases: 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).
__init__(agent_card, http_handler, extended_agent_card=None, context_builder=None, card_modifier=None, extended_card_modifier=None)
¶
Initializes the JSONRPCApplication.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
agent_card
|
AgentCard
|
The AgentCard describing the agent's capabilities. |
required |
http_handler
|
RequestHandler
|
The handler instance responsible for processing A2A requests via http. |
required |
extended_agent_card
|
AgentCard | None
|
An optional, distinct AgentCard to be served at the authenticated extended card endpoint. |
None
|
context_builder
|
CallContextBuilder | None
|
The CallContextBuilder used to construct the ServerCallContext passed to the http_handler. If None, no ServerCallContext is passed. |
None
|
card_modifier
|
Callable[[AgentCard], AgentCard] | None
|
An optional callback to dynamically modify the public agent card before it is served. |
None
|
extended_card_modifier
|
Callable[[AgentCard, ServerCallContext], AgentCard] | None
|
An optional callback to dynamically modify the extended agent card before it is served. It receives the call context. |
None
|
build(agent_card_url=AGENT_CARD_WELL_KNOWN_PATH, rpc_url=DEFAULT_RPC_URL, extended_agent_card_url=EXTENDED_AGENT_CARD_PATH, **kwargs)
abstractmethod
¶
Builds and returns the JSONRPC application instance.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
agent_card_url
|
str
|
The URL for the agent card endpoint. |
AGENT_CARD_WELL_KNOWN_PATH
|
rpc_url
|
str
|
The URL for the A2A JSON-RPC endpoint. |
DEFAULT_RPC_URL
|
extended_agent_card_url
|
str
|
The URL for the authenticated extended agent card endpoint. |
EXTENDED_AGENT_CARD_PATH
|
**kwargs
|
Any
|
Additional keyword arguments to pass to the FastAPI constructor. |
{}
|
Returns:
Type | Description |
---|---|
FastAPI | Starlette
|
A configured JSONRPC application instance. |
StarletteUserProxy
¶
fastapi_app
¶
A2AFastAPI
¶
Bases: FastAPI
A FastAPI application that adds A2A-specific OpenAPI components.
openapi()
¶Generates the OpenAPI schema for the application.
A2AFastAPIApplication
¶
Bases: JSONRPCApplication
A FastAPI application implementing the A2A protocol server endpoints.
Handles incoming JSON-RPC requests, routes them to the appropriate handler methods, and manages response generation including Server-Sent Events (SSE).
__init__(agent_card, http_handler, extended_agent_card=None, context_builder=None, card_modifier=None, extended_card_modifier=None)
¶Initializes the A2AFastAPIApplication.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
agent_card
|
AgentCard
|
The AgentCard describing the agent's capabilities. |
required |
http_handler
|
RequestHandler
|
The handler instance responsible for processing A2A requests via http. |
required |
extended_agent_card
|
AgentCard | None
|
An optional, distinct AgentCard to be served at the authenticated extended card endpoint. |
None
|
context_builder
|
CallContextBuilder | None
|
The CallContextBuilder used to construct the ServerCallContext passed to the http_handler. If None, no ServerCallContext is passed. |
None
|
card_modifier
|
Callable[[AgentCard], AgentCard] | None
|
An optional callback to dynamically modify the public agent card before it is served. |
None
|
extended_card_modifier
|
Callable[[AgentCard, ServerCallContext], AgentCard] | None
|
An optional callback to dynamically modify the extended agent card before it is served. It receives the call context. |
None
|
add_routes_to_app(app, agent_card_url=AGENT_CARD_WELL_KNOWN_PATH, rpc_url=DEFAULT_RPC_URL, extended_agent_card_url=EXTENDED_AGENT_CARD_PATH)
¶Adds the routes to the FastAPI application.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
app
|
FastAPI
|
The FastAPI application to add the routes to. |
required |
agent_card_url
|
str
|
The URL for the agent card endpoint. |
AGENT_CARD_WELL_KNOWN_PATH
|
rpc_url
|
str
|
The URL for the A2A JSON-RPC endpoint. |
DEFAULT_RPC_URL
|
extended_agent_card_url
|
str
|
The URL for the authenticated extended agent card endpoint. |
EXTENDED_AGENT_CARD_PATH
|
build(agent_card_url=AGENT_CARD_WELL_KNOWN_PATH, rpc_url=DEFAULT_RPC_URL, extended_agent_card_url=EXTENDED_AGENT_CARD_PATH, **kwargs)
¶Builds and returns the FastAPI application instance.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
agent_card_url
|
str
|
The URL for the agent card endpoint. |
AGENT_CARD_WELL_KNOWN_PATH
|
rpc_url
|
str
|
The URL for the A2A JSON-RPC endpoint. |
DEFAULT_RPC_URL
|
extended_agent_card_url
|
str
|
The URL for the authenticated extended agent card endpoint. |
EXTENDED_AGENT_CARD_PATH
|
**kwargs
|
Any
|
Additional keyword arguments to pass to the FastAPI constructor. |
{}
|
Returns:
Type | Description |
---|---|
FastAPI
|
A configured FastAPI application instance. |
jsonrpc_app
¶
CallContextBuilder
¶
Bases: ABC
A class for building ServerCallContexts using the Starlette Request.
build(request)
abstractmethod
¶Builds a ServerCallContext from a Starlette Request.
DefaultCallContextBuilder
¶
Bases: CallContextBuilder
A default implementation of CallContextBuilder.
build(request)
¶Builds a ServerCallContext from a Starlette Request.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
Request
|
The incoming Starlette Request object. |
required |
Returns:
Type | Description |
---|---|
ServerCallContext
|
A ServerCallContext instance populated with user and state |
ServerCallContext
|
information from the request. |
JSONRPCApplication
¶
Bases: 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).
__init__(agent_card, http_handler, extended_agent_card=None, context_builder=None, card_modifier=None, extended_card_modifier=None)
¶Initializes the JSONRPCApplication.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
agent_card
|
AgentCard
|
The AgentCard describing the agent's capabilities. |
required |
http_handler
|
RequestHandler
|
The handler instance responsible for processing A2A requests via http. |
required |
extended_agent_card
|
AgentCard | None
|
An optional, distinct AgentCard to be served at the authenticated extended card endpoint. |
None
|
context_builder
|
CallContextBuilder | None
|
The CallContextBuilder used to construct the ServerCallContext passed to the http_handler. If None, no ServerCallContext is passed. |
None
|
card_modifier
|
Callable[[AgentCard], AgentCard] | None
|
An optional callback to dynamically modify the public agent card before it is served. |
None
|
extended_card_modifier
|
Callable[[AgentCard, ServerCallContext], AgentCard] | None
|
An optional callback to dynamically modify the extended agent card before it is served. It receives the call context. |
None
|
build(agent_card_url=AGENT_CARD_WELL_KNOWN_PATH, rpc_url=DEFAULT_RPC_URL, extended_agent_card_url=EXTENDED_AGENT_CARD_PATH, **kwargs)
abstractmethod
¶Builds and returns the JSONRPC application instance.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
agent_card_url
|
str
|
The URL for the agent card endpoint. |
AGENT_CARD_WELL_KNOWN_PATH
|
rpc_url
|
str
|
The URL for the A2A JSON-RPC endpoint. |
DEFAULT_RPC_URL
|
extended_agent_card_url
|
str
|
The URL for the authenticated extended agent card endpoint. |
EXTENDED_AGENT_CARD_PATH
|
**kwargs
|
Any
|
Additional keyword arguments to pass to the FastAPI constructor. |
{}
|
Returns:
Type | Description |
---|---|
FastAPI | Starlette
|
A configured JSONRPC application instance. |
starlette_app
¶
A2AStarletteApplication
¶
Bases: JSONRPCApplication
A Starlette application implementing the A2A protocol server endpoints.
Handles incoming JSON-RPC requests, routes them to the appropriate handler methods, and manages response generation including Server-Sent Events (SSE).
__init__(agent_card, http_handler, extended_agent_card=None, context_builder=None, card_modifier=None, extended_card_modifier=None)
¶Initializes the A2AStarletteApplication.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
agent_card
|
AgentCard
|
The AgentCard describing the agent's capabilities. |
required |
http_handler
|
RequestHandler
|
The handler instance responsible for processing A2A requests via http. |
required |
extended_agent_card
|
AgentCard | None
|
An optional, distinct AgentCard to be served at the authenticated extended card endpoint. |
None
|
context_builder
|
CallContextBuilder | None
|
The CallContextBuilder used to construct the ServerCallContext passed to the http_handler. If None, no ServerCallContext is passed. |
None
|
card_modifier
|
Callable[[AgentCard], AgentCard] | None
|
An optional callback to dynamically modify the public agent card before it is served. |
None
|
extended_card_modifier
|
Callable[[AgentCard, ServerCallContext], AgentCard] | None
|
An optional callback to dynamically modify the extended agent card before it is served. It receives the call context. |
None
|
add_routes_to_app(app, agent_card_url=AGENT_CARD_WELL_KNOWN_PATH, rpc_url=DEFAULT_RPC_URL, extended_agent_card_url=EXTENDED_AGENT_CARD_PATH)
¶Adds the routes to the Starlette application.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
app
|
Starlette
|
The Starlette application to add the routes to. |
required |
agent_card_url
|
str
|
The URL path for the agent card endpoint. |
AGENT_CARD_WELL_KNOWN_PATH
|
rpc_url
|
str
|
The URL path for the A2A JSON-RPC endpoint (POST requests). |
DEFAULT_RPC_URL
|
extended_agent_card_url
|
str
|
The URL for the authenticated extended agent card endpoint. |
EXTENDED_AGENT_CARD_PATH
|
build(agent_card_url=AGENT_CARD_WELL_KNOWN_PATH, rpc_url=DEFAULT_RPC_URL, extended_agent_card_url=EXTENDED_AGENT_CARD_PATH, **kwargs)
¶Builds and returns the Starlette application instance.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
agent_card_url
|
str
|
The URL path for the agent card endpoint. |
AGENT_CARD_WELL_KNOWN_PATH
|
rpc_url
|
str
|
The URL path for the A2A JSON-RPC endpoint (POST requests). |
DEFAULT_RPC_URL
|
extended_agent_card_url
|
str
|
The URL for the authenticated extended agent card endpoint. |
EXTENDED_AGENT_CARD_PATH
|
**kwargs
|
Any
|
Additional keyword arguments to pass to the Starlette constructor. |
{}
|
Returns:
Type | Description |
---|---|
Starlette
|
A configured Starlette application instance. |
routes(agent_card_url=AGENT_CARD_WELL_KNOWN_PATH, rpc_url=DEFAULT_RPC_URL, extended_agent_card_url=EXTENDED_AGENT_CARD_PATH)
¶Returns the Starlette Routes for handling A2A requests.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
agent_card_url
|
str
|
The URL path for the agent card endpoint. |
AGENT_CARD_WELL_KNOWN_PATH
|
rpc_url
|
str
|
The URL path for the A2A JSON-RPC endpoint (POST requests). |
DEFAULT_RPC_URL
|
extended_agent_card_url
|
str
|
The URL for the authenticated extended agent card endpoint. |
EXTENDED_AGENT_CARD_PATH
|
Returns:
Type | Description |
---|---|
list[Route]
|
A list of Starlette Route objects. |
rest
¶
A2A REST Applications.
A2ARESTFastAPIApplication
¶
A FastAPI application implementing the A2A protocol server REST endpoints.
Handles incoming REST requests, routes them to the appropriate handler methods, and manages response generation including Server-Sent Events (SSE).
__init__(agent_card, http_handler, extended_agent_card=None, context_builder=None, card_modifier=None, extended_card_modifier=None)
¶
Initializes the A2ARESTFastAPIApplication.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
agent_card
|
AgentCard
|
The AgentCard describing the agent's capabilities. |
required |
http_handler
|
RequestHandler
|
The handler instance responsible for processing A2A requests via http. |
required |
extended_agent_card
|
AgentCard | None
|
An optional, distinct AgentCard to be served at the authenticated extended card endpoint. |
None
|
context_builder
|
CallContextBuilder | None
|
The CallContextBuilder used to construct the ServerCallContext passed to the http_handler. If None, no ServerCallContext is passed. |
None
|
card_modifier
|
Callable[[AgentCard], AgentCard] | None
|
An optional callback to dynamically modify the public agent card before it is served. |
None
|
extended_card_modifier
|
Callable[[AgentCard, ServerCallContext], AgentCard] | None
|
An optional callback to dynamically modify the extended agent card before it is served. It receives the call context. |
None
|
build(agent_card_url=AGENT_CARD_WELL_KNOWN_PATH, rpc_url='', **kwargs)
¶
Builds and returns the FastAPI application instance.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
agent_card_url
|
str
|
The URL for the agent card endpoint. |
AGENT_CARD_WELL_KNOWN_PATH
|
rpc_url
|
str
|
The URL for the A2A JSON-RPC endpoint. |
''
|
extended_agent_card_url
|
The URL for the authenticated extended agent card endpoint. |
required | |
**kwargs
|
Any
|
Additional keyword arguments to pass to the FastAPI constructor. |
{}
|
Returns:
Type | Description |
---|---|
FastAPI
|
A configured FastAPI application instance. |
fastapi_app
¶
A2ARESTFastAPIApplication
¶
A FastAPI application implementing the A2A protocol server REST endpoints.
Handles incoming REST requests, routes them to the appropriate handler methods, and manages response generation including Server-Sent Events (SSE).
__init__(agent_card, http_handler, extended_agent_card=None, context_builder=None, card_modifier=None, extended_card_modifier=None)
¶Initializes the A2ARESTFastAPIApplication.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
agent_card
|
AgentCard
|
The AgentCard describing the agent's capabilities. |
required |
http_handler
|
RequestHandler
|
The handler instance responsible for processing A2A requests via http. |
required |
extended_agent_card
|
AgentCard | None
|
An optional, distinct AgentCard to be served at the authenticated extended card endpoint. |
None
|
context_builder
|
CallContextBuilder | None
|
The CallContextBuilder used to construct the ServerCallContext passed to the http_handler. If None, no ServerCallContext is passed. |
None
|
card_modifier
|
Callable[[AgentCard], AgentCard] | None
|
An optional callback to dynamically modify the public agent card before it is served. |
None
|
extended_card_modifier
|
Callable[[AgentCard, ServerCallContext], AgentCard] | None
|
An optional callback to dynamically modify the extended agent card before it is served. It receives the call context. |
None
|
build(agent_card_url=AGENT_CARD_WELL_KNOWN_PATH, rpc_url='', **kwargs)
¶Builds and returns the FastAPI application instance.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
agent_card_url
|
str
|
The URL for the agent card endpoint. |
AGENT_CARD_WELL_KNOWN_PATH
|
rpc_url
|
str
|
The URL for the A2A JSON-RPC endpoint. |
''
|
extended_agent_card_url
|
The URL for the authenticated extended agent card endpoint. |
required | |
**kwargs
|
Any
|
Additional keyword arguments to pass to the FastAPI constructor. |
{}
|
Returns:
Type | Description |
---|---|
FastAPI
|
A configured FastAPI application instance. |
rest_adapter
¶
RESTAdapter
¶
Adapter to make RequestHandler work with RESTful API.
Defines REST requests processors and the routes to attach them too, as well as manages response generation including Server-Sent Events (SSE).
__init__(agent_card, http_handler, extended_agent_card=None, context_builder=None, card_modifier=None, extended_card_modifier=None)
¶Initializes the RESTApplication.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
agent_card
|
AgentCard
|
The AgentCard describing the agent's capabilities. |
required |
http_handler
|
RequestHandler
|
The handler instance responsible for processing A2A requests via http. |
required |
extended_agent_card
|
AgentCard | None
|
An optional, distinct AgentCard to be served at the authenticated extended card endpoint. |
None
|
context_builder
|
CallContextBuilder | None
|
The CallContextBuilder used to construct the ServerCallContext passed to the http_handler. If None, no ServerCallContext is passed. |
None
|
card_modifier
|
Callable[[AgentCard], AgentCard] | None
|
An optional callback to dynamically modify the public agent card before it is served. |
None
|
extended_card_modifier
|
Callable[[AgentCard, ServerCallContext], AgentCard] | None
|
An optional callback to dynamically modify the extended agent card before it is served. It receives the call context. |
None
|
handle_authenticated_agent_card(request, call_context=None)
async
¶Hook for per credential agent card response.
If a dynamic card is needed based on the credentials provided in the request override this method and return the customized content.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
Request
|
The incoming Starlette Request object. |
required |
call_context
|
ServerCallContext | None
|
ServerCallContext |
None
|
Returns:
Type | Description |
---|---|
dict[str, Any]
|
A JSONResponse containing the authenticated card. |
handle_get_agent_card(request, call_context=None)
async
¶Handles GET requests for the agent card endpoint.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
Request
|
The incoming Starlette Request object. |
required |
call_context
|
ServerCallContext | None
|
ServerCallContext |
None
|
Returns:
Type | Description |
---|---|
dict[str, Any]
|
A JSONResponse containing the agent card data. |
routes()
¶Constructs a dictionary of API routes and their corresponding handlers.
This method maps URL paths and HTTP methods to the appropriate handler functions from the RESTHandler. It can be used by a web framework (like Starlette or FastAPI) to set up the application's endpoints.
Returns:
Type | Description |
---|---|
dict[tuple[str, str], Callable[[Request], Any]]
|
A dictionary where each key is a tuple of (path, http_method) and |
dict[tuple[str, str], Callable[[Request], Any]]
|
the value is the callable handler for that route. |
context
¶
Defines the ServerCallContext class.
ServerCallContext
¶
Bases: BaseModel
A context passed when calling a server method.
This class allows storing arbitrary user data in the state attribute.
events
¶
Event handling components for the A2A server.
Event = Message | Task | TaskStatusUpdateEvent | TaskArtifactUpdateEvent
module-attribute
¶
Type alias for events that can be enqueued.
EventConsumer
¶
Consumer to read events from the agent event queue.
__init__(queue)
¶
Initializes the EventConsumer.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
queue
|
EventQueue
|
The |
required |
agent_task_callback(agent_task)
¶
Callback to handle exceptions from the agent's execution task.
If the agent's asyncio task raises an exception, this callback is invoked, and the exception is stored to be re-raised by the consumer loop.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
agent_task
|
Task[None]
|
The asyncio.Task that completed. |
required |
consume_all()
async
¶
Consume all the generated streaming events from the agent.
This method yields events as they become available from the queue
until a final event is received or the queue is closed. It also
monitors for exceptions set by the agent_task_callback
.
Yields:
Type | Description |
---|---|
AsyncGenerator[Event]
|
Events dequeued from the queue. |
Raises:
Type | Description |
---|---|
BaseException
|
If an exception was set by the |
consume_one()
async
¶
Consume one event from the agent event queue non-blocking.
Returns:
Type | Description |
---|---|
Event
|
The next event from the queue. |
Raises:
Type | Description |
---|---|
ServerError
|
If the queue is empty when attempting to dequeue immediately. |
EventQueue
¶
Event queue for A2A responses from agent.
Acts as a buffer between the agent's asynchronous execution and the server's response handling (e.g., streaming via SSE). Supports tapping to create child queues that receive the same events.
__init__(max_queue_size=DEFAULT_MAX_QUEUE_SIZE)
¶
Initializes the EventQueue.
clear_events(clear_child_queues=True)
async
¶
Clears all events from the current queue and optionally all child queues.
This method removes all pending events from the queue without processing them. Child queues can be optionally cleared based on the clear_child_queues parameter.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
clear_child_queues
|
bool
|
If True (default), clear all child queues as well. If False, only clear the current queue, leaving child queues untouched. |
True
|
close(immediate=False)
async
¶
Closes the queue for future push events and also closes all child queues.
Once closed, no new events can be enqueued. For Python 3.13+, this will trigger
asyncio.QueueShutDown
when the queue is empty and a consumer tries to dequeue.
For lower versions, the queue will be marked as closed and optionally cleared.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
immediate
|
bool
|
|
False
|
dequeue_event(no_wait=False)
async
¶
Dequeues an event from the queue.
This implementation expects that dequeue to raise an exception when the queue has been closed. In python 3.13+ this is naturally provided by the QueueShutDown exception generated when the queue has closed and the user is awaiting the queue.get method. Python<=3.12 this needs to manage this lifecycle itself. The current implementation can lead to blocking if the dequeue_event is called before the EventQueue has been closed but when there are no events on the queue. Two ways to avoid this are to call this with no_wait = True which won't block, but is the callers responsibility to retry as appropriate. Alternatively, one can use a async Task management solution to cancel the get task if the queue has closed or some other condition is met. The implementation of the EventConsumer uses an async.wait with a timeout to abort the dequeue_event call and retry, when it will return with a closed error.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
no_wait
|
bool
|
If True, retrieve an event immediately or raise |
False
|
Returns:
Type | Description |
---|---|
Event
|
The next event from the queue. |
Raises:
Type | Description |
---|---|
QueueEmpty
|
If |
QueueShutDown
|
If the queue has been closed and is empty. |
enqueue_event(event)
async
¶
Enqueues an event to this queue and all its children.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
event
|
Event
|
The event object to enqueue. |
required |
is_closed()
¶
Checks if the queue is closed.
tap()
¶
Taps the event queue to create a new child queue that receives all future events.
Returns:
Type | Description |
---|---|
EventQueue
|
A new |
EventQueue
|
to this parent queue from this point forward. |
task_done()
¶
Signals that a formerly enqueued task is complete.
Used in conjunction with dequeue_event
to track processed items.
InMemoryQueueManager
¶
Bases: QueueManager
InMemoryQueueManager is used for a single binary management.
This implements the QueueManager
interface using in-memory storage for event
queues. It requires all incoming interactions for a given task ID to hit the
same binary instance.
This implementation is suitable for single-instance deployments but needs a distributed approach for scalable deployments.
__init__()
¶
Initializes the InMemoryQueueManager.
add(task_id, queue)
async
¶
Adds a new event queue for a task ID.
Raises:
Type | Description |
---|---|
TaskQueueExists
|
If a queue for the given |
close(task_id)
async
¶
Closes and removes the event queue for a task ID.
Raises:
Type | Description |
---|---|
NoTaskQueue
|
If no queue exists for the given |
create_or_tap(task_id)
async
¶
Creates a new event queue for a task ID if one doesn't exist, otherwise taps the existing one.
Returns:
Type | Description |
---|---|
EventQueue
|
A new or child |
get(task_id)
async
¶
Retrieves the event queue for a task ID.
Returns:
Type | Description |
---|---|
EventQueue | None
|
The |
tap(task_id)
async
¶
Taps the event queue for a task ID to create a child queue.
Returns:
Type | Description |
---|---|
EventQueue | None
|
A new child |
NoTaskQueue
¶
Bases: Exception
Exception raised when attempting to access or close a queue for a task ID that does not exist.
QueueManager
¶
Bases: ABC
Interface for managing the event queue lifecycles per task.
add(task_id, queue)
abstractmethod
async
¶
Adds a new event queue associated with a task ID.
close(task_id)
abstractmethod
async
¶
Closes and removes the event queue for a task ID.
create_or_tap(task_id)
abstractmethod
async
¶
Creates a queue if one doesn't exist, otherwise taps the existing one.
get(task_id)
abstractmethod
async
¶
Retrieves the event queue for a task ID.
tap(task_id)
abstractmethod
async
¶
Creates a child event queue (tap) for an existing task ID.
TaskQueueExists
¶
Bases: Exception
Exception raised when attempting to add a queue for a task ID that already exists.
event_consumer
¶
EventConsumer
¶
Consumer to read events from the agent event queue.
__init__(queue)
¶
Initializes the EventConsumer.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
queue
|
EventQueue
|
The |
required |
agent_task_callback(agent_task)
¶
Callback to handle exceptions from the agent's execution task.
If the agent's asyncio task raises an exception, this callback is invoked, and the exception is stored to be re-raised by the consumer loop.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
agent_task
|
Task[None]
|
The asyncio.Task that completed. |
required |
consume_all()
async
¶
Consume all the generated streaming events from the agent.
This method yields events as they become available from the queue
until a final event is received or the queue is closed. It also
monitors for exceptions set by the agent_task_callback
.
Yields:
Type | Description |
---|---|
AsyncGenerator[Event]
|
Events dequeued from the queue. |
Raises:
Type | Description |
---|---|
BaseException
|
If an exception was set by the |
consume_one()
async
¶
Consume one event from the agent event queue non-blocking.
Returns:
Type | Description |
---|---|
Event
|
The next event from the queue. |
Raises:
Type | Description |
---|---|
ServerError
|
If the queue is empty when attempting to dequeue immediately. |
event_queue
¶
Event = Message | Task | TaskStatusUpdateEvent | TaskArtifactUpdateEvent
module-attribute
¶
Type alias for events that can be enqueued.
EventQueue
¶
Event queue for A2A responses from agent.
Acts as a buffer between the agent's asynchronous execution and the server's response handling (e.g., streaming via SSE). Supports tapping to create child queues that receive the same events.
__init__(max_queue_size=DEFAULT_MAX_QUEUE_SIZE)
¶
Initializes the EventQueue.
clear_events(clear_child_queues=True)
async
¶
Clears all events from the current queue and optionally all child queues.
This method removes all pending events from the queue without processing them. Child queues can be optionally cleared based on the clear_child_queues parameter.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
clear_child_queues
|
bool
|
If True (default), clear all child queues as well. If False, only clear the current queue, leaving child queues untouched. |
True
|
close(immediate=False)
async
¶
Closes the queue for future push events and also closes all child queues.
Once closed, no new events can be enqueued. For Python 3.13+, this will trigger
asyncio.QueueShutDown
when the queue is empty and a consumer tries to dequeue.
For lower versions, the queue will be marked as closed and optionally cleared.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
immediate
|
bool
|
|
False
|
dequeue_event(no_wait=False)
async
¶
Dequeues an event from the queue.
This implementation expects that dequeue to raise an exception when the queue has been closed. In python 3.13+ this is naturally provided by the QueueShutDown exception generated when the queue has closed and the user is awaiting the queue.get method. Python<=3.12 this needs to manage this lifecycle itself. The current implementation can lead to blocking if the dequeue_event is called before the EventQueue has been closed but when there are no events on the queue. Two ways to avoid this are to call this with no_wait = True which won't block, but is the callers responsibility to retry as appropriate. Alternatively, one can use a async Task management solution to cancel the get task if the queue has closed or some other condition is met. The implementation of the EventConsumer uses an async.wait with a timeout to abort the dequeue_event call and retry, when it will return with a closed error.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
no_wait
|
bool
|
If True, retrieve an event immediately or raise |
False
|
Returns:
Type | Description |
---|---|
Event
|
The next event from the queue. |
Raises:
Type | Description |
---|---|
QueueEmpty
|
If |
QueueShutDown
|
If the queue has been closed and is empty. |
enqueue_event(event)
async
¶
Enqueues an event to this queue and all its children.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
event
|
Event
|
The event object to enqueue. |
required |
is_closed()
¶
Checks if the queue is closed.
tap()
¶
Taps the event queue to create a new child queue that receives all future events.
Returns:
Type | Description |
---|---|
EventQueue
|
A new |
EventQueue
|
to this parent queue from this point forward. |
task_done()
¶
Signals that a formerly enqueued task is complete.
Used in conjunction with dequeue_event
to track processed items.
in_memory_queue_manager
¶
InMemoryQueueManager
¶
Bases: QueueManager
InMemoryQueueManager is used for a single binary management.
This implements the QueueManager
interface using in-memory storage for event
queues. It requires all incoming interactions for a given task ID to hit the
same binary instance.
This implementation is suitable for single-instance deployments but needs a distributed approach for scalable deployments.
__init__()
¶
Initializes the InMemoryQueueManager.
add(task_id, queue)
async
¶
Adds a new event queue for a task ID.
Raises:
Type | Description |
---|---|
TaskQueueExists
|
If a queue for the given |
close(task_id)
async
¶
Closes and removes the event queue for a task ID.
Raises:
Type | Description |
---|---|
NoTaskQueue
|
If no queue exists for the given |
create_or_tap(task_id)
async
¶
Creates a new event queue for a task ID if one doesn't exist, otherwise taps the existing one.
Returns:
Type | Description |
---|---|
EventQueue
|
A new or child |
get(task_id)
async
¶
Retrieves the event queue for a task ID.
Returns:
Type | Description |
---|---|
EventQueue | None
|
The |
tap(task_id)
async
¶
Taps the event queue for a task ID to create a child queue.
Returns:
Type | Description |
---|---|
EventQueue | None
|
A new child |
queue_manager
¶
NoTaskQueue
¶
Bases: Exception
Exception raised when attempting to access or close a queue for a task ID that does not exist.
QueueManager
¶
Bases: ABC
Interface for managing the event queue lifecycles per task.
add(task_id, queue)
abstractmethod
async
¶
Adds a new event queue associated with a task ID.
close(task_id)
abstractmethod
async
¶
Closes and removes the event queue for a task ID.
create_or_tap(task_id)
abstractmethod
async
¶
Creates a queue if one doesn't exist, otherwise taps the existing one.
get(task_id)
abstractmethod
async
¶
Retrieves the event queue for a task ID.
tap(task_id)
abstractmethod
async
¶
Creates a child event queue (tap) for an existing task ID.
TaskQueueExists
¶
Bases: Exception
Exception raised when attempting to add a queue for a task ID that already exists.
models
¶
Base
¶
Bases: DeclarativeBase
Base class for declarative models in A2A SDK.
PushNotificationConfigMixin
¶
Mixin providing standard push notification config columns.
__repr__()
¶
Return a string representation of the push notification config.
PushNotificationConfigModel
¶
Bases: PushNotificationConfigMixin
, Base
Default push notification config model with standard table name.
__repr__()
¶
Return a string representation of the push notification config.
PydanticListType
¶
Bases: TypeDecorator
, Generic[T]
SQLAlchemy type that handles lists of Pydantic models.
__init__(pydantic_type, **kwargs)
¶
Initialize the PydanticListType.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
pydantic_type
|
type[T]
|
The Pydantic model type for items in the list. |
required |
**kwargs
|
dict[str, Any]
|
Additional arguments for TypeDecorator. |
{}
|
process_bind_param(value, dialect)
¶
Convert a list of Pydantic models to a JSON-serializable list for the DB.
process_result_value(value, dialect)
¶
Convert a JSON-like list from the DB back to a list of Pydantic models.
PydanticType
¶
Bases: TypeDecorator[T]
, Generic[T]
SQLAlchemy type that handles Pydantic model serialization.
__init__(pydantic_type, **kwargs)
¶
Initialize the PydanticType.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
pydantic_type
|
type[T]
|
The Pydantic model type to handle. |
required |
**kwargs
|
dict[str, Any]
|
Additional arguments for TypeDecorator. |
{}
|
process_bind_param(value, dialect)
¶
Convert Pydantic model to a JSON-serializable dictionary for the database.
process_result_value(value, dialect)
¶
Convert a JSON-like dictionary from the database back to a Pydantic model.
TaskMixin
¶
TaskModel
¶
create_push_notification_config_model(table_name='push_notification_configs', base=Base)
¶
Create a PushNotificationConfigModel class with a configurable table name.
create_task_model(table_name='tasks', base=Base)
¶
Create a TaskModel class with a configurable table name.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
table_name
|
str
|
Name of the database table. Defaults to 'tasks'. |
'tasks'
|
base
|
type[DeclarativeBase]
|
Base declarative class to use. Defaults to the SDK's Base class. |
Base
|
Returns:
Type | Description |
---|---|
type
|
TaskModel class with the specified table name. |
request_handlers
¶
Request handler components for the A2A server.
DefaultRequestHandler
¶
Bases: RequestHandler
Default request handler for all incoming requests.
This handler provides default implementations for all A2A JSON-RPC methods,
coordinating between the AgentExecutor
, TaskStore
, QueueManager
,
and optional PushNotifier
.
__init__(agent_executor, task_store, queue_manager=None, push_config_store=None, push_sender=None, request_context_builder=None)
¶
Initializes the DefaultRequestHandler.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
agent_executor
|
AgentExecutor
|
The |
required |
task_store
|
TaskStore
|
The |
required |
queue_manager
|
QueueManager | None
|
The |
None
|
push_config_store
|
PushNotificationConfigStore | None
|
The |
None
|
push_sender
|
PushNotificationSender | None
|
The |
None
|
request_context_builder
|
RequestContextBuilder | None
|
The |
None
|
on_cancel_task(params, context=None)
async
¶
Default handler for 'tasks/cancel'.
Attempts to cancel the task managed by the AgentExecutor
.
on_delete_task_push_notification_config(params, context=None)
async
¶
Default handler for 'tasks/pushNotificationConfig/delete'.
Requires a PushConfigStore
to be configured.
on_get_task(params, context=None)
async
¶
Default handler for 'tasks/get'.
on_get_task_push_notification_config(params, context=None)
async
¶
Default handler for 'tasks/pushNotificationConfig/get'.
Requires a PushConfigStore
to be configured.
on_list_task_push_notification_config(params, context=None)
async
¶
Default handler for 'tasks/pushNotificationConfig/list'.
Requires a PushConfigStore
to be configured.
on_message_send(params, context=None)
async
¶
Default handler for 'message/send' interface (non-streaming).
Starts the agent execution for the message and waits for the final result (Task or Message).
on_message_send_stream(params, context=None)
async
¶
Default handler for 'message/stream' (streaming).
Starts the agent execution and yields events as they are produced by the agent.
on_resubscribe_to_task(params, context=None)
async
¶
Default handler for 'tasks/resubscribe'.
Allows a client to re-attach to a running streaming task's event stream. Requires the task and its queue to still be active.
on_set_task_push_notification_config(params, context=None)
async
¶
Default handler for 'tasks/pushNotificationConfig/set'.
Requires a PushNotifier
to be configured.
GrpcHandler
¶
Placeholder for GrpcHandler when dependencies are not installed.
JSONRPCHandler
¶
Maps incoming JSON-RPC requests to the appropriate request handler method and formats responses.
__init__(agent_card, request_handler, extended_agent_card=None, extended_card_modifier=None, card_modifier=None)
¶
Initializes the JSONRPCHandler.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
agent_card
|
AgentCard
|
The AgentCard describing the agent's capabilities. |
required |
request_handler
|
RequestHandler
|
The underlying |
required |
extended_agent_card
|
AgentCard | None
|
An optional, distinct Extended AgentCard to be served |
None
|
extended_card_modifier
|
Callable[[AgentCard, ServerCallContext], AgentCard] | None
|
An optional callback to dynamically modify the extended agent card before it is served. It receives the call context. |
None
|
card_modifier
|
Callable[[AgentCard], AgentCard] | None
|
An optional callback to dynamically modify the public agent card before it is served. |
None
|
delete_push_notification_config(request, context=None)
async
¶
Handles the 'tasks/pushNotificationConfig/list' JSON-RPC method.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
DeleteTaskPushNotificationConfigRequest
|
The incoming |
required |
context
|
ServerCallContext | None
|
Context provided by the server. |
None
|
Returns:
Type | Description |
---|---|
DeleteTaskPushNotificationConfigResponse
|
A |
get_authenticated_extended_card(request, context=None)
async
¶
Handles the 'agent/authenticatedExtendedCard' JSON-RPC method.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
GetAuthenticatedExtendedCardRequest
|
The incoming |
required |
context
|
ServerCallContext | None
|
Context provided by the server. |
None
|
Returns:
Type | Description |
---|---|
GetAuthenticatedExtendedCardResponse
|
A |
get_push_notification_config(request, context=None)
async
¶
Handles the 'tasks/pushNotificationConfig/get' JSON-RPC method.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
GetTaskPushNotificationConfigRequest
|
The incoming |
required |
context
|
ServerCallContext | None
|
Context provided by the server. |
None
|
Returns:
Type | Description |
---|---|
GetTaskPushNotificationConfigResponse
|
A |
list_push_notification_config(request, context=None)
async
¶
Handles the 'tasks/pushNotificationConfig/list' JSON-RPC method.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
ListTaskPushNotificationConfigRequest
|
The incoming |
required |
context
|
ServerCallContext | None
|
Context provided by the server. |
None
|
Returns:
Type | Description |
---|---|
ListTaskPushNotificationConfigResponse
|
A |
on_cancel_task(request, context=None)
async
¶
Handles the 'tasks/cancel' JSON-RPC method.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
CancelTaskRequest
|
The incoming |
required |
context
|
ServerCallContext | None
|
Context provided by the server. |
None
|
Returns:
Type | Description |
---|---|
CancelTaskResponse
|
A |
on_get_task(request, context=None)
async
¶
Handles the 'tasks/get' JSON-RPC method.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
GetTaskRequest
|
The incoming |
required |
context
|
ServerCallContext | None
|
Context provided by the server. |
None
|
Returns:
Type | Description |
---|---|
GetTaskResponse
|
A |
on_message_send(request, context=None)
async
¶
Handles the 'message/send' JSON-RPC method.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
SendMessageRequest
|
The incoming |
required |
context
|
ServerCallContext | None
|
Context provided by the server. |
None
|
Returns:
Type | Description |
---|---|
SendMessageResponse
|
A |
SendMessageResponse
|
or a JSON-RPC error response if a |
on_message_send_stream(request, context=None)
async
¶
Handles the 'message/stream' JSON-RPC method.
Yields response objects as they are produced by the underlying handler's stream.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
SendStreamingMessageRequest
|
The incoming |
required |
context
|
ServerCallContext | None
|
Context provided by the server. |
None
|
Yields:
Type | Description |
---|---|
AsyncIterable[SendStreamingMessageResponse]
|
|
AsyncIterable[SendStreamingMessageResponse]
|
(Task, Message, TaskStatusUpdateEvent, TaskArtifactUpdateEvent) |
AsyncIterable[SendStreamingMessageResponse]
|
or JSON-RPC error responses if a |
on_resubscribe_to_task(request, context=None)
async
¶
Handles the 'tasks/resubscribe' JSON-RPC method.
Yields response objects as they are produced by the underlying handler's stream.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
TaskResubscriptionRequest
|
The incoming |
required |
context
|
ServerCallContext | None
|
Context provided by the server. |
None
|
Yields:
Type | Description |
---|---|
AsyncIterable[SendStreamingMessageResponse]
|
|
AsyncIterable[SendStreamingMessageResponse]
|
or JSON-RPC error responses if a |
set_push_notification_config(request, context=None)
async
¶
Handles the 'tasks/pushNotificationConfig/set' JSON-RPC method.
Requires the agent to support push notifications.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
SetTaskPushNotificationConfigRequest
|
The incoming |
required |
context
|
ServerCallContext | None
|
Context provided by the server. |
None
|
Returns:
Type | Description |
---|---|
SetTaskPushNotificationConfigResponse
|
A |
Raises:
Type | Description |
---|---|
ServerError
|
If push notifications are not supported by the agent
(due to the |
RESTHandler
¶
Maps incoming REST-like (JSON+HTTP) requests to the appropriate request handler method and formats responses.
This uses the protobuf definitions of the gRPC service as the source of truth. By doing this, it ensures that this implementation and the gRPC transcoding (via Envoy) are equivalent. This handler should be used if using the gRPC handler with Envoy is not feasible for a given deployment solution. Use this handler and a related application if you desire to ONLY server the RESTful API.
__init__(agent_card, request_handler)
¶
Initializes the RESTHandler.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
agent_card
|
AgentCard
|
The AgentCard describing the agent's capabilities. |
required |
request_handler
|
RequestHandler
|
The underlying |
required |
get_push_notification(request, context)
async
¶
Handles the 'tasks/pushNotificationConfig/get' REST method.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
Request
|
The incoming |
required |
context
|
ServerCallContext
|
Context provided by the server. |
required |
Returns:
Type | Description |
---|---|
dict[str, Any]
|
A |
list_push_notifications(request, context)
async
¶
Handles the 'tasks/pushNotificationConfig/list' REST method.
This method is currently not implemented.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
Request
|
The incoming |
required |
context
|
ServerCallContext
|
Context provided by the server. |
required |
Returns:
Type | Description |
---|---|
dict[str, Any]
|
A list of |
Raises:
Type | Description |
---|---|
NotImplementedError
|
This method is not yet implemented. |
list_tasks(request, context)
async
¶
Handles the 'tasks/list' REST method.
This method is currently not implemented.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
Request
|
The incoming |
required |
context
|
ServerCallContext
|
Context provided by the server. |
required |
Returns:
Type | Description |
---|---|
dict[str, Any]
|
A list of dict representing the |
Raises:
Type | Description |
---|---|
NotImplementedError
|
This method is not yet implemented. |
on_cancel_task(request, context)
async
¶
Handles the 'tasks/cancel' REST method.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
Request
|
The incoming |
required |
context
|
ServerCallContext
|
Context provided by the server. |
required |
Returns:
Type | Description |
---|---|
dict[str, Any]
|
A |
on_get_task(request, context)
async
¶
Handles the 'v1/tasks/{id}' REST method.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
Request
|
The incoming |
required |
context
|
ServerCallContext
|
Context provided by the server. |
required |
Returns:
Type | Description |
---|---|
dict[str, Any]
|
A |
on_message_send(request, context)
async
¶
Handles the 'message/send' REST method.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
Request
|
The incoming |
required |
context
|
ServerCallContext
|
Context provided by the server. |
required |
Returns:
Type | Description |
---|---|
dict[str, Any]
|
A |
on_message_send_stream(request, context)
async
¶
Handles the 'message/stream' REST method.
Yields response objects as they are produced by the underlying handler's stream.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
Request
|
The incoming |
required |
context
|
ServerCallContext
|
Context provided by the server. |
required |
Yields:
Type | Description |
---|---|
AsyncIterator[str]
|
JSON serialized objects containing streaming events |
AsyncIterator[str]
|
(Task, Message, TaskStatusUpdateEvent, TaskArtifactUpdateEvent) as JSON |
on_resubscribe_to_task(request, context)
async
¶
Handles the 'tasks/resubscribe' REST method.
Yields response objects as they are produced by the underlying handler's stream.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
Request
|
The incoming |
required |
context
|
ServerCallContext
|
Context provided by the server. |
required |
Yields:
Type | Description |
---|---|
AsyncIterable[str]
|
JSON serialized objects containing streaming events |
set_push_notification(request, context)
async
¶
Handles the 'tasks/pushNotificationConfig/set' REST method.
Requires the agent to support push notifications.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
Request
|
The incoming |
required |
context
|
ServerCallContext
|
Context provided by the server. |
required |
Returns:
Type | Description |
---|---|
dict[str, Any]
|
A |
Raises:
Type | Description |
---|---|
ServerError
|
If push notifications are not supported by the agent
(due to the |
RequestHandler
¶
Bases: ABC
A2A request handler interface.
This interface defines the methods that an A2A server implementation must provide to handle incoming JSON-RPC requests.
on_cancel_task(params, context=None)
abstractmethod
async
¶
Handles the 'tasks/cancel' method.
Requests the agent to cancel an ongoing task.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
params
|
TaskIdParams
|
Parameters specifying the task ID. |
required |
context
|
ServerCallContext | None
|
Context provided by the server. |
None
|
Returns:
Type | Description |
---|---|
Task | None
|
The |
on_delete_task_push_notification_config(params, context=None)
abstractmethod
async
¶
Handles the 'tasks/pushNotificationConfig/delete' method.
Deletes a push notification configuration associated with a task.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
params
|
DeleteTaskPushNotificationConfigParams
|
Parameters including the task ID. |
required |
context
|
ServerCallContext | None
|
Context provided by the server. |
None
|
Returns:
Type | Description |
---|---|
None
|
None |
on_get_task(params, context=None)
abstractmethod
async
¶
Handles the 'tasks/get' method.
Retrieves the state and history of a specific task.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
params
|
TaskQueryParams
|
Parameters specifying the task ID and optionally history length. |
required |
context
|
ServerCallContext | None
|
Context provided by the server. |
None
|
Returns:
Type | Description |
---|---|
Task | None
|
The |
on_get_task_push_notification_config(params, context=None)
abstractmethod
async
¶
Handles the 'tasks/pushNotificationConfig/get' method.
Retrieves the current push notification configuration for a task.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
params
|
TaskIdParams | GetTaskPushNotificationConfigParams
|
Parameters including the task ID. |
required |
context
|
ServerCallContext | None
|
Context provided by the server. |
None
|
Returns:
Type | Description |
---|---|
TaskPushNotificationConfig
|
The |
on_list_task_push_notification_config(params, context=None)
abstractmethod
async
¶
Handles the 'tasks/pushNotificationConfig/list' method.
Retrieves the current push notification configurations for a task.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
params
|
ListTaskPushNotificationConfigParams
|
Parameters including the task ID. |
required |
context
|
ServerCallContext | None
|
Context provided by the server. |
None
|
Returns:
Type | Description |
---|---|
list[TaskPushNotificationConfig]
|
The |
on_message_send(params, context=None)
abstractmethod
async
¶
Handles the 'message/send' method (non-streaming).
Sends a message to the agent to create, continue, or restart a task, and waits for the final result (Task or Message).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
params
|
MessageSendParams
|
Parameters including the message and configuration. |
required |
context
|
ServerCallContext | None
|
Context provided by the server. |
None
|
Returns:
Type | Description |
---|---|
Task | Message
|
The final |
on_message_send_stream(params, context=None)
abstractmethod
async
¶
Handles the 'message/stream' method (streaming).
Sends a message to the agent and yields stream events as they are produced (Task updates, Message chunks, Artifact updates).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
params
|
MessageSendParams
|
Parameters including the message and configuration. |
required |
context
|
ServerCallContext | None
|
Context provided by the server. |
None
|
Yields:
Type | Description |
---|---|
AsyncGenerator[Event]
|
|
Raises:
Type | Description |
---|---|
ServerError(UnsupportedOperationError)
|
By default, if not implemented. |
on_resubscribe_to_task(params, context=None)
abstractmethod
async
¶
Handles the 'tasks/resubscribe' method.
Allows a client to re-subscribe to a running streaming task's event stream.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
params
|
TaskIdParams
|
Parameters including the task ID. |
required |
context
|
ServerCallContext | None
|
Context provided by the server. |
None
|
Yields:
Type | Description |
---|---|
AsyncGenerator[Event]
|
|
Raises:
Type | Description |
---|---|
ServerError(UnsupportedOperationError)
|
By default, if not implemented. |
on_set_task_push_notification_config(params, context=None)
abstractmethod
async
¶
Handles the 'tasks/pushNotificationConfig/set' method.
Sets or updates the push notification configuration for a task.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
params
|
TaskPushNotificationConfig
|
Parameters including the task ID and push notification configuration. |
required |
context
|
ServerCallContext | None
|
Context provided by the server. |
None
|
Returns:
Type | Description |
---|---|
TaskPushNotificationConfig
|
The provided |
build_error_response(request_id, error, response_wrapper_type)
¶
Helper method to build a JSONRPCErrorResponse wrapped in the appropriate response type.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request_id
|
str | int | None
|
The ID of the request that caused the error. |
required |
error
|
A2AError | JSONRPCError
|
The A2AError or JSONRPCError object. |
required |
response_wrapper_type
|
type[RT]
|
The Pydantic RootModel type that wraps the response
for the specific RPC method (e.g., |
required |
Returns:
Type | Description |
---|---|
RT
|
A Pydantic model representing the JSON-RPC error response, |
RT
|
wrapped in the specified response type. |
prepare_response_object(request_id, response, success_response_types, success_payload_type, response_type)
¶
Helper method to build appropriate JSONRPCResponse object for RPC methods.
Based on the type of the response
object received from the handler,
it constructs either a success response wrapped in the appropriate payload type
or an error response.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request_id
|
str | int | None
|
The ID of the request. |
required |
response
|
EventTypes
|
The object received from the request handler. |
required |
success_response_types
|
tuple[type, ...]
|
A tuple of expected Pydantic model types for a successful result. |
required |
success_payload_type
|
type[SPT]
|
The Pydantic model type for the success payload
(e.g., |
required |
response_type
|
type[RT]
|
The Pydantic RootModel type that wraps the final response
(e.g., |
required |
Returns:
Type | Description |
---|---|
RT
|
A Pydantic model representing the final JSON-RPC response (success or error). |
default_request_handler
¶
DefaultRequestHandler
¶
Bases: RequestHandler
Default request handler for all incoming requests.
This handler provides default implementations for all A2A JSON-RPC methods,
coordinating between the AgentExecutor
, TaskStore
, QueueManager
,
and optional PushNotifier
.
__init__(agent_executor, task_store, queue_manager=None, push_config_store=None, push_sender=None, request_context_builder=None)
¶
Initializes the DefaultRequestHandler.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
agent_executor
|
AgentExecutor
|
The |
required |
task_store
|
TaskStore
|
The |
required |
queue_manager
|
QueueManager | None
|
The |
None
|
push_config_store
|
PushNotificationConfigStore | None
|
The |
None
|
push_sender
|
PushNotificationSender | None
|
The |
None
|
request_context_builder
|
RequestContextBuilder | None
|
The |
None
|
on_cancel_task(params, context=None)
async
¶
Default handler for 'tasks/cancel'.
Attempts to cancel the task managed by the AgentExecutor
.
on_delete_task_push_notification_config(params, context=None)
async
¶
Default handler for 'tasks/pushNotificationConfig/delete'.
Requires a PushConfigStore
to be configured.
on_get_task(params, context=None)
async
¶
Default handler for 'tasks/get'.
on_get_task_push_notification_config(params, context=None)
async
¶
Default handler for 'tasks/pushNotificationConfig/get'.
Requires a PushConfigStore
to be configured.
on_list_task_push_notification_config(params, context=None)
async
¶
Default handler for 'tasks/pushNotificationConfig/list'.
Requires a PushConfigStore
to be configured.
on_message_send(params, context=None)
async
¶
Default handler for 'message/send' interface (non-streaming).
Starts the agent execution for the message and waits for the final result (Task or Message).
on_message_send_stream(params, context=None)
async
¶
Default handler for 'message/stream' (streaming).
Starts the agent execution and yields events as they are produced by the agent.
on_resubscribe_to_task(params, context=None)
async
¶
Default handler for 'tasks/resubscribe'.
Allows a client to re-attach to a running streaming task's event stream. Requires the task and its queue to still be active.
on_set_task_push_notification_config(params, context=None)
async
¶
Default handler for 'tasks/pushNotificationConfig/set'.
Requires a PushNotifier
to be configured.
grpc_handler
¶
CallContextBuilder
¶
Bases: ABC
A class for building ServerCallContexts using the Starlette Request.
build(context)
abstractmethod
¶
Builds a ServerCallContext from a gRPC Request.
DefaultCallContextBuilder
¶
Bases: CallContextBuilder
A default implementation of CallContextBuilder.
build(context)
¶
Builds the ServerCallContext.
GrpcHandler
¶
Bases: A2AServiceServicer
Maps incoming gRPC requests to the appropriate request handler method.
CancelTask(request, context)
async
¶
Handles the 'CancelTask' gRPC method.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
CancelTaskRequest
|
The incoming |
required |
context
|
ServicerContext
|
Context provided by the server. |
required |
Returns:
Type | Description |
---|---|
Task
|
A |
CreateTaskPushNotificationConfig(request, context)
async
¶
Handles the 'CreateTaskPushNotificationConfig' gRPC method.
Requires the agent to support push notifications.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
CreateTaskPushNotificationConfigRequest
|
The incoming |
required |
context
|
ServicerContext
|
Context provided by the server. |
required |
Returns:
Type | Description |
---|---|
TaskPushNotificationConfig
|
A |
Raises:
Type | Description |
---|---|
ServerError
|
If push notifications are not supported by the agent
(due to the |
DeleteTaskPushNotificationConfig(request, context)
¶
Delete a push notification config for a task.
GetAgentCard(request, context)
async
¶
Get the agent card for the agent served.
GetTask(request, context)
async
¶
Handles the 'GetTask' gRPC method.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
GetTaskRequest
|
The incoming |
required |
context
|
ServicerContext
|
Context provided by the server. |
required |
Returns:
Type | Description |
---|---|
Task
|
A |
GetTaskPushNotificationConfig(request, context)
async
¶
Handles the 'GetTaskPushNotificationConfig' gRPC method.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
GetTaskPushNotificationConfigRequest
|
The incoming |
required |
context
|
ServicerContext
|
Context provided by the server. |
required |
Returns:
Type | Description |
---|---|
TaskPushNotificationConfig
|
A |
ListTaskPushNotificationConfig(request, context)
¶
Get a list of push notifications configured for a task.
SendMessage(request, context)
async
¶
Handles the 'SendMessage' gRPC method.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
SendMessageRequest
|
The incoming |
required |
context
|
ServicerContext
|
Context provided by the server. |
required |
Returns:
Type | Description |
---|---|
SendMessageResponse
|
A |
SendMessageResponse
|
Message) or throws an error response if a |
SendMessageResponse
|
by the handler. |
SendStreamingMessage(request, context)
async
¶
Handles the 'StreamMessage' gRPC method.
Yields response objects as they are produced by the underlying handler's stream.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
SendMessageRequest
|
The incoming |
required |
context
|
ServicerContext
|
Context provided by the server. |
required |
Yields:
Type | Description |
---|---|
AsyncIterable[StreamResponse]
|
|
AsyncIterable[StreamResponse]
|
(Task, Message, TaskStatusUpdateEvent, TaskArtifactUpdateEvent) |
AsyncIterable[StreamResponse]
|
or gRPC error responses if a |
TaskSubscription(request, context)
async
¶
Handles the 'TaskSubscription' gRPC method.
Yields response objects as they are produced by the underlying handler's stream.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
TaskSubscriptionRequest
|
The incoming |
required |
context
|
ServicerContext
|
Context provided by the server. |
required |
Yields:
Type | Description |
---|---|
AsyncIterable[StreamResponse]
|
|
__init__(agent_card, request_handler, context_builder=None, card_modifier=None)
¶
Initializes the GrpcHandler.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
agent_card
|
AgentCard
|
The AgentCard describing the agent's capabilities. |
required |
request_handler
|
RequestHandler
|
The underlying |
required |
context_builder
|
CallContextBuilder | None
|
The CallContextBuilder object. If none the DefaultCallContextBuilder is used. |
None
|
card_modifier
|
Callable[[AgentCard], AgentCard] | None
|
An optional callback to dynamically modify the public agent card before it is served. |
None
|
abort_context(error, context)
async
¶
Sets the grpc errors appropriately in the context.
jsonrpc_handler
¶
JSONRPCHandler
¶
Maps incoming JSON-RPC requests to the appropriate request handler method and formats responses.
__init__(agent_card, request_handler, extended_agent_card=None, extended_card_modifier=None, card_modifier=None)
¶
Initializes the JSONRPCHandler.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
agent_card
|
AgentCard
|
The AgentCard describing the agent's capabilities. |
required |
request_handler
|
RequestHandler
|
The underlying |
required |
extended_agent_card
|
AgentCard | None
|
An optional, distinct Extended AgentCard to be served |
None
|
extended_card_modifier
|
Callable[[AgentCard, ServerCallContext], AgentCard] | None
|
An optional callback to dynamically modify the extended agent card before it is served. It receives the call context. |
None
|
card_modifier
|
Callable[[AgentCard], AgentCard] | None
|
An optional callback to dynamically modify the public agent card before it is served. |
None
|
delete_push_notification_config(request, context=None)
async
¶
Handles the 'tasks/pushNotificationConfig/list' JSON-RPC method.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
DeleteTaskPushNotificationConfigRequest
|
The incoming |
required |
context
|
ServerCallContext | None
|
Context provided by the server. |
None
|
Returns:
Type | Description |
---|---|
DeleteTaskPushNotificationConfigResponse
|
A |
get_authenticated_extended_card(request, context=None)
async
¶
Handles the 'agent/authenticatedExtendedCard' JSON-RPC method.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
GetAuthenticatedExtendedCardRequest
|
The incoming |
required |
context
|
ServerCallContext | None
|
Context provided by the server. |
None
|
Returns:
Type | Description |
---|---|
GetAuthenticatedExtendedCardResponse
|
A |
get_push_notification_config(request, context=None)
async
¶
Handles the 'tasks/pushNotificationConfig/get' JSON-RPC method.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
GetTaskPushNotificationConfigRequest
|
The incoming |
required |
context
|
ServerCallContext | None
|
Context provided by the server. |
None
|
Returns:
Type | Description |
---|---|
GetTaskPushNotificationConfigResponse
|
A |
list_push_notification_config(request, context=None)
async
¶
Handles the 'tasks/pushNotificationConfig/list' JSON-RPC method.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
ListTaskPushNotificationConfigRequest
|
The incoming |
required |
context
|
ServerCallContext | None
|
Context provided by the server. |
None
|
Returns:
Type | Description |
---|---|
ListTaskPushNotificationConfigResponse
|
A |
on_cancel_task(request, context=None)
async
¶
Handles the 'tasks/cancel' JSON-RPC method.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
CancelTaskRequest
|
The incoming |
required |
context
|
ServerCallContext | None
|
Context provided by the server. |
None
|
Returns:
Type | Description |
---|---|
CancelTaskResponse
|
A |
on_get_task(request, context=None)
async
¶
Handles the 'tasks/get' JSON-RPC method.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
GetTaskRequest
|
The incoming |
required |
context
|
ServerCallContext | None
|
Context provided by the server. |
None
|
Returns:
Type | Description |
---|---|
GetTaskResponse
|
A |
on_message_send(request, context=None)
async
¶
Handles the 'message/send' JSON-RPC method.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
SendMessageRequest
|
The incoming |
required |
context
|
ServerCallContext | None
|
Context provided by the server. |
None
|
Returns:
Type | Description |
---|---|
SendMessageResponse
|
A |
SendMessageResponse
|
or a JSON-RPC error response if a |
on_message_send_stream(request, context=None)
async
¶
Handles the 'message/stream' JSON-RPC method.
Yields response objects as they are produced by the underlying handler's stream.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
SendStreamingMessageRequest
|
The incoming |
required |
context
|
ServerCallContext | None
|
Context provided by the server. |
None
|
Yields:
Type | Description |
---|---|
AsyncIterable[SendStreamingMessageResponse]
|
|
AsyncIterable[SendStreamingMessageResponse]
|
(Task, Message, TaskStatusUpdateEvent, TaskArtifactUpdateEvent) |
AsyncIterable[SendStreamingMessageResponse]
|
or JSON-RPC error responses if a |
on_resubscribe_to_task(request, context=None)
async
¶
Handles the 'tasks/resubscribe' JSON-RPC method.
Yields response objects as they are produced by the underlying handler's stream.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
TaskResubscriptionRequest
|
The incoming |
required |
context
|
ServerCallContext | None
|
Context provided by the server. |
None
|
Yields:
Type | Description |
---|---|
AsyncIterable[SendStreamingMessageResponse]
|
|
AsyncIterable[SendStreamingMessageResponse]
|
or JSON-RPC error responses if a |
set_push_notification_config(request, context=None)
async
¶
Handles the 'tasks/pushNotificationConfig/set' JSON-RPC method.
Requires the agent to support push notifications.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
SetTaskPushNotificationConfigRequest
|
The incoming |
required |
context
|
ServerCallContext | None
|
Context provided by the server. |
None
|
Returns:
Type | Description |
---|---|
SetTaskPushNotificationConfigResponse
|
A |
Raises:
Type | Description |
---|---|
ServerError
|
If push notifications are not supported by the agent
(due to the |
request_handler
¶
RequestHandler
¶
Bases: ABC
A2A request handler interface.
This interface defines the methods that an A2A server implementation must provide to handle incoming JSON-RPC requests.
on_cancel_task(params, context=None)
abstractmethod
async
¶
Handles the 'tasks/cancel' method.
Requests the agent to cancel an ongoing task.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
params
|
TaskIdParams
|
Parameters specifying the task ID. |
required |
context
|
ServerCallContext | None
|
Context provided by the server. |
None
|
Returns:
Type | Description |
---|---|
Task | None
|
The |
on_delete_task_push_notification_config(params, context=None)
abstractmethod
async
¶
Handles the 'tasks/pushNotificationConfig/delete' method.
Deletes a push notification configuration associated with a task.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
params
|
DeleteTaskPushNotificationConfigParams
|
Parameters including the task ID. |
required |
context
|
ServerCallContext | None
|
Context provided by the server. |
None
|
Returns:
Type | Description |
---|---|
None
|
None |
on_get_task(params, context=None)
abstractmethod
async
¶
Handles the 'tasks/get' method.
Retrieves the state and history of a specific task.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
params
|
TaskQueryParams
|
Parameters specifying the task ID and optionally history length. |
required |
context
|
ServerCallContext | None
|
Context provided by the server. |
None
|
Returns:
Type | Description |
---|---|
Task | None
|
The |
on_get_task_push_notification_config(params, context=None)
abstractmethod
async
¶
Handles the 'tasks/pushNotificationConfig/get' method.
Retrieves the current push notification configuration for a task.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
params
|
TaskIdParams | GetTaskPushNotificationConfigParams
|
Parameters including the task ID. |
required |
context
|
ServerCallContext | None
|
Context provided by the server. |
None
|
Returns:
Type | Description |
---|---|
TaskPushNotificationConfig
|
The |
on_list_task_push_notification_config(params, context=None)
abstractmethod
async
¶
Handles the 'tasks/pushNotificationConfig/list' method.
Retrieves the current push notification configurations for a task.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
params
|
ListTaskPushNotificationConfigParams
|
Parameters including the task ID. |
required |
context
|
ServerCallContext | None
|
Context provided by the server. |
None
|
Returns:
Type | Description |
---|---|
list[TaskPushNotificationConfig]
|
The |
on_message_send(params, context=None)
abstractmethod
async
¶
Handles the 'message/send' method (non-streaming).
Sends a message to the agent to create, continue, or restart a task, and waits for the final result (Task or Message).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
params
|
MessageSendParams
|
Parameters including the message and configuration. |
required |
context
|
ServerCallContext | None
|
Context provided by the server. |
None
|
Returns:
Type | Description |
---|---|
Task | Message
|
The final |
on_message_send_stream(params, context=None)
abstractmethod
async
¶
Handles the 'message/stream' method (streaming).
Sends a message to the agent and yields stream events as they are produced (Task updates, Message chunks, Artifact updates).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
params
|
MessageSendParams
|
Parameters including the message and configuration. |
required |
context
|
ServerCallContext | None
|
Context provided by the server. |
None
|
Yields:
Type | Description |
---|---|
AsyncGenerator[Event]
|
|
Raises:
Type | Description |
---|---|
ServerError(UnsupportedOperationError)
|
By default, if not implemented. |
on_resubscribe_to_task(params, context=None)
abstractmethod
async
¶
Handles the 'tasks/resubscribe' method.
Allows a client to re-subscribe to a running streaming task's event stream.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
params
|
TaskIdParams
|
Parameters including the task ID. |
required |
context
|
ServerCallContext | None
|
Context provided by the server. |
None
|
Yields:
Type | Description |
---|---|
AsyncGenerator[Event]
|
|
Raises:
Type | Description |
---|---|
ServerError(UnsupportedOperationError)
|
By default, if not implemented. |
on_set_task_push_notification_config(params, context=None)
abstractmethod
async
¶
Handles the 'tasks/pushNotificationConfig/set' method.
Sets or updates the push notification configuration for a task.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
params
|
TaskPushNotificationConfig
|
Parameters including the task ID and push notification configuration. |
required |
context
|
ServerCallContext | None
|
Context provided by the server. |
None
|
Returns:
Type | Description |
---|---|
TaskPushNotificationConfig
|
The provided |
response_helpers
¶
Helper functions for building A2A JSON-RPC responses.
EventTypes = Task | Message | TaskArtifactUpdateEvent | TaskStatusUpdateEvent | TaskPushNotificationConfig | A2AError | JSONRPCError | list[TaskPushNotificationConfig]
module-attribute
¶
Type alias for possible event types produced by handlers.
RT = TypeVar('RT', GetTaskResponse, CancelTaskResponse, SendMessageResponse, SetTaskPushNotificationConfigResponse, GetTaskPushNotificationConfigResponse, SendStreamingMessageResponse, ListTaskPushNotificationConfigResponse, DeleteTaskPushNotificationConfigResponse)
module-attribute
¶
Type variable for RootModel response types.
SPT = TypeVar('SPT', GetTaskSuccessResponse, CancelTaskSuccessResponse, SendMessageSuccessResponse, SetTaskPushNotificationConfigSuccessResponse, GetTaskPushNotificationConfigSuccessResponse, SendStreamingMessageSuccessResponse, ListTaskPushNotificationConfigSuccessResponse, DeleteTaskPushNotificationConfigSuccessResponse)
module-attribute
¶
Type variable for SuccessResponse types.
build_error_response(request_id, error, response_wrapper_type)
¶
Helper method to build a JSONRPCErrorResponse wrapped in the appropriate response type.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request_id
|
str | int | None
|
The ID of the request that caused the error. |
required |
error
|
A2AError | JSONRPCError
|
The A2AError or JSONRPCError object. |
required |
response_wrapper_type
|
type[RT]
|
The Pydantic RootModel type that wraps the response
for the specific RPC method (e.g., |
required |
Returns:
Type | Description |
---|---|
RT
|
A Pydantic model representing the JSON-RPC error response, |
RT
|
wrapped in the specified response type. |
prepare_response_object(request_id, response, success_response_types, success_payload_type, response_type)
¶
Helper method to build appropriate JSONRPCResponse object for RPC methods.
Based on the type of the response
object received from the handler,
it constructs either a success response wrapped in the appropriate payload type
or an error response.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request_id
|
str | int | None
|
The ID of the request. |
required |
response
|
EventTypes
|
The object received from the request handler. |
required |
success_response_types
|
tuple[type, ...]
|
A tuple of expected Pydantic model types for a successful result. |
required |
success_payload_type
|
type[SPT]
|
The Pydantic model type for the success payload
(e.g., |
required |
response_type
|
type[RT]
|
The Pydantic RootModel type that wraps the final response
(e.g., |
required |
Returns:
Type | Description |
---|---|
RT
|
A Pydantic model representing the final JSON-RPC response (success or error). |
rest_handler
¶
RESTHandler
¶
Maps incoming REST-like (JSON+HTTP) requests to the appropriate request handler method and formats responses.
This uses the protobuf definitions of the gRPC service as the source of truth. By doing this, it ensures that this implementation and the gRPC transcoding (via Envoy) are equivalent. This handler should be used if using the gRPC handler with Envoy is not feasible for a given deployment solution. Use this handler and a related application if you desire to ONLY server the RESTful API.
__init__(agent_card, request_handler)
¶
Initializes the RESTHandler.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
agent_card
|
AgentCard
|
The AgentCard describing the agent's capabilities. |
required |
request_handler
|
RequestHandler
|
The underlying |
required |
get_push_notification(request, context)
async
¶
Handles the 'tasks/pushNotificationConfig/get' REST method.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
Request
|
The incoming |
required |
context
|
ServerCallContext
|
Context provided by the server. |
required |
Returns:
Type | Description |
---|---|
dict[str, Any]
|
A |
list_push_notifications(request, context)
async
¶
Handles the 'tasks/pushNotificationConfig/list' REST method.
This method is currently not implemented.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
Request
|
The incoming |
required |
context
|
ServerCallContext
|
Context provided by the server. |
required |
Returns:
Type | Description |
---|---|
dict[str, Any]
|
A list of |
Raises:
Type | Description |
---|---|
NotImplementedError
|
This method is not yet implemented. |
list_tasks(request, context)
async
¶
Handles the 'tasks/list' REST method.
This method is currently not implemented.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
Request
|
The incoming |
required |
context
|
ServerCallContext
|
Context provided by the server. |
required |
Returns:
Type | Description |
---|---|
dict[str, Any]
|
A list of dict representing the |
Raises:
Type | Description |
---|---|
NotImplementedError
|
This method is not yet implemented. |
on_cancel_task(request, context)
async
¶
Handles the 'tasks/cancel' REST method.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
Request
|
The incoming |
required |
context
|
ServerCallContext
|
Context provided by the server. |
required |
Returns:
Type | Description |
---|---|
dict[str, Any]
|
A |
on_get_task(request, context)
async
¶
Handles the 'v1/tasks/{id}' REST method.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
Request
|
The incoming |
required |
context
|
ServerCallContext
|
Context provided by the server. |
required |
Returns:
Type | Description |
---|---|
dict[str, Any]
|
A |
on_message_send(request, context)
async
¶
Handles the 'message/send' REST method.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
Request
|
The incoming |
required |
context
|
ServerCallContext
|
Context provided by the server. |
required |
Returns:
Type | Description |
---|---|
dict[str, Any]
|
A |
on_message_send_stream(request, context)
async
¶
Handles the 'message/stream' REST method.
Yields response objects as they are produced by the underlying handler's stream.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
Request
|
The incoming |
required |
context
|
ServerCallContext
|
Context provided by the server. |
required |
Yields:
Type | Description |
---|---|
AsyncIterator[str]
|
JSON serialized objects containing streaming events |
AsyncIterator[str]
|
(Task, Message, TaskStatusUpdateEvent, TaskArtifactUpdateEvent) as JSON |
on_resubscribe_to_task(request, context)
async
¶
Handles the 'tasks/resubscribe' REST method.
Yields response objects as they are produced by the underlying handler's stream.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
Request
|
The incoming |
required |
context
|
ServerCallContext
|
Context provided by the server. |
required |
Yields:
Type | Description |
---|---|
AsyncIterable[str]
|
JSON serialized objects containing streaming events |
set_push_notification(request, context)
async
¶
Handles the 'tasks/pushNotificationConfig/set' REST method.
Requires the agent to support push notifications.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
Request
|
The incoming |
required |
context
|
ServerCallContext
|
Context provided by the server. |
required |
Returns:
Type | Description |
---|---|
dict[str, Any]
|
A |
Raises:
Type | Description |
---|---|
ServerError
|
If push notifications are not supported by the agent
(due to the |
tasks
¶
Components for managing tasks within the A2A server.
BasePushNotificationSender
¶
Bases: PushNotificationSender
Base implementation of PushNotificationSender interface.
__init__(httpx_client, config_store)
¶
Initializes the BasePushNotificationSender.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
httpx_client
|
AsyncClient
|
An async HTTP client instance to send notifications. |
required |
config_store
|
PushNotificationConfigStore
|
A PushNotificationConfigStore instance to retrieve configurations. |
required |
send_notification(task)
async
¶
Sends a push notification for a task if configuration exists.
DatabasePushNotificationConfigStore
¶
Placeholder for DatabasePushNotificationConfigStore when dependencies are not installed.
DatabaseTaskStore
¶
Placeholder for DatabaseTaskStore when dependencies are not installed.
InMemoryPushNotificationConfigStore
¶
Bases: PushNotificationConfigStore
In-memory implementation of PushNotificationConfigStore interface.
Stores push notification configurations in memory
__init__()
¶
Initializes the InMemoryPushNotificationConfigStore.
delete_info(task_id, config_id=None)
async
¶
Deletes the push notification configuration for a task from memory.
get_info(task_id)
async
¶
Retrieves the push notification configuration for a task from memory.
set_info(task_id, notification_config)
async
¶
Sets or updates the push notification configuration for a task in memory.
InMemoryTaskStore
¶
Bases: TaskStore
In-memory implementation of TaskStore.
Stores task objects in a dictionary in memory. Task data is lost when the server process stops.
PushNotificationConfigStore
¶
Bases: ABC
Interface for storing and retrieving push notification configurations for tasks.
delete_info(task_id, config_id=None)
abstractmethod
async
¶
Deletes the push notification configuration for a task.
get_info(task_id)
abstractmethod
async
¶
Retrieves the push notification configuration for a task.
set_info(task_id, notification_config)
abstractmethod
async
¶
Sets or updates the push notification configuration for a task.
PushNotificationSender
¶
Bases: ABC
Interface for sending push notifications for tasks.
send_notification(task)
abstractmethod
async
¶
Sends a push notification containing the latest task state.
ResultAggregator
¶
ResultAggregator is used to process the event streams from an AgentExecutor.
There are three main ways to use the ResultAggregator: 1) As part of a processing pipe. consume_and_emit will construct the updated task as the events arrive, and re-emit those events for another consumer 2) As part of a blocking call. consume_all will process the entire stream and return the final Task or Message object 3) As part of a push solution where the latest Task is emitted after processing an event. consume_and_emit_task will consume the Event stream, process the events to the current Task object and emit that Task object.
current_result
async
property
¶
Returns the current aggregated result (Task or Message).
This is the latest state processed from the event stream.
Returns:
Type | Description |
---|---|
Task | Message | None
|
The current |
Task | Message | None
|
|
__init__(task_manager)
¶
Initializes the ResultAggregator.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
task_manager
|
TaskManager
|
The |
required |
consume_all(consumer)
async
¶
Processes the entire event stream from the consumer and returns the final result.
Blocks until the event stream ends (queue is closed after final event or exception).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
consumer
|
EventConsumer
|
The |
required |
Returns:
Type | Description |
---|---|
Task | Message | None
|
The final |
Task | Message | None
|
Returns |
Raises:
Type | Description |
---|---|
BaseException
|
If the |
consume_and_break_on_interrupt(consumer, blocking=True, event_callback=None)
async
¶
Processes the event stream until completion or an interruptable state is encountered.
If blocking
is False, it returns after the first event that creates a Task or Message.
If blocking
is True, it waits for completion unless an auth_required
state is encountered, which is always an interruption.
If interrupted, consumption continues in a background task.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
consumer
|
EventConsumer
|
The |
required |
blocking
|
bool
|
If |
True
|
event_callback
|
Callable[[], Awaitable[None]] | None
|
Optional async callback function to be called after each event is processed in the background continuation. Mainly used for push notifications currently. |
None
|
Returns:
Type | Description |
---|---|
Task | Message | None
|
A tuple containing: |
bool
|
|
tuple[Task | Message | None, bool]
|
|
Raises:
Type | Description |
---|---|
BaseException
|
If the |
consume_and_emit(consumer)
async
¶
Processes the event stream from the consumer, updates the task state, and re-emits the same events.
Useful for streaming scenarios where the server needs to observe and process events (e.g., save task state, send push notifications) while forwarding them to the client.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
consumer
|
EventConsumer
|
The |
required |
Yields:
Type | Description |
---|---|
AsyncGenerator[Event]
|
The |
TaskManager
¶
Helps manage a task's lifecycle during execution of a request.
Responsible for retrieving, saving, and updating the Task
object based on
events received from the agent.
__init__(task_id, context_id, task_store, initial_message, context=None)
¶
Initializes the TaskManager.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
task_id
|
str | None
|
The ID of the task, if known from the request. |
required |
context_id
|
str | None
|
The ID of the context, if known from the request. |
required |
task_store
|
TaskStore
|
The |
required |
initial_message
|
Message | None
|
The |
required |
context
|
ServerCallContext | None
|
The |
None
|
ensure_task(event)
async
¶
Ensures a Task object exists in memory, loading from store or creating new if needed.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
event
|
TaskStatusUpdateEvent | TaskArtifactUpdateEvent
|
The task-related event triggering the need for a Task object. |
required |
Returns:
Type | Description |
---|---|
Task
|
An existing or newly created |
get_task()
async
¶
Retrieves the current task object, either from memory or the store.
If task_id
is set, it first checks the in-memory _current_task
,
then attempts to load it from the task_store
.
Returns:
Type | Description |
---|---|
Task | None
|
The |
process(event)
async
¶
Processes an event, updates the task state if applicable, stores it, and returns the event.
If the event is task-related (Task
, TaskStatusUpdateEvent
, TaskArtifactUpdateEvent
),
the internal task state is updated and persisted.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
event
|
Event
|
The event object received from the agent. |
required |
Returns:
Type | Description |
---|---|
Event
|
The same event object that was processed. |
save_task_event(event)
async
¶
Processes a task-related event (Task, Status, Artifact) and saves the updated task state.
Ensures task and context IDs match or are set from the event.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
event
|
Task | TaskStatusUpdateEvent | TaskArtifactUpdateEvent
|
The task-related event ( |
required |
Returns:
Type | Description |
---|---|
Task | None
|
The updated |
Raises:
Type | Description |
---|---|
ServerError
|
If the task ID in the event conflicts with the TaskManager's ID when the TaskManager's ID is already set. |
update_with_message(message, task)
¶
Updates a task object in memory by adding a new message to its history.
If the task has a message in its current status, that message is moved to the history first.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
message
|
Message
|
The new |
required |
task
|
Task
|
The |
required |
Returns:
Type | Description |
---|---|
Task
|
The updated |
TaskStore
¶
Bases: ABC
Agent Task Store interface.
Defines the methods for persisting and retrieving Task
objects.
TaskUpdater
¶
Helper class for agents to publish updates to a task's event queue.
Simplifies the process of creating and enqueueing standard task events.
__init__(event_queue, task_id, context_id)
¶
Initializes the TaskUpdater.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
event_queue
|
EventQueue
|
The |
required |
task_id
|
str
|
The ID of the task. |
required |
context_id
|
str
|
The context ID of the task. |
required |
add_artifact(parts, artifact_id=None, name=None, metadata=None, append=None, last_chunk=None, extensions=None)
async
¶
Adds an artifact chunk to the task and publishes a TaskArtifactUpdateEvent
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
parts
|
list[Part]
|
A list of |
required |
artifact_id
|
str | None
|
The ID of the artifact. A new UUID is generated if not provided. |
None
|
name
|
str | None
|
Optional name for the artifact. |
None
|
metadata
|
dict[str, Any] | None
|
Optional metadata for the artifact. |
None
|
append
|
bool | None
|
Optional boolean indicating if this chunk appends to a previous one. |
None
|
last_chunk
|
bool | None
|
Optional boolean indicating if this is the last chunk. |
None
|
extensions
|
list[str] | None
|
Optional list of extensions for the artifact. |
None
|
cancel(message=None)
async
¶
Marks the task as cancelled and publishes a finalstatus update.
complete(message=None)
async
¶
Marks the task as completed and publishes a final status update.
failed(message=None)
async
¶
Marks the task as failed and publishes a final status update.
new_agent_message(parts, metadata=None)
¶
Creates a new message object sent by the agent for this task/context.
This method only creates the message object. It does not
automatically enqueue it.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
parts
|
list[Part]
|
A list of |
required |
metadata
|
dict[str, Any] | None
|
Optional metadata for the message. |
None
|
Returns:
Type | Description |
---|---|
Message
|
A new |
reject(message=None)
async
¶
Marks the task as rejected and publishes a final status update.
requires_auth(message=None, final=False)
async
¶
Marks the task as auth required and publishes a status update.
requires_input(message=None, final=False)
async
¶
Marks the task as input required and publishes a status update.
start_work(message=None)
async
¶
Marks the task as working and publishes a status update.
submit(message=None)
async
¶
Marks the task as submitted and publishes a status update.
update_status(state, message=None, final=False, timestamp=None, metadata=None)
async
¶
Updates the status of the task and publishes a TaskStatusUpdateEvent
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
state
|
TaskState
|
The new state of the task. |
required |
message
|
Message | None
|
An optional message associated with the status update. |
None
|
final
|
bool
|
If True, indicates this is the final status update for the task. |
False
|
timestamp
|
str | None
|
Optional ISO 8601 datetime string. Defaults to current time. |
None
|
metadata
|
dict[str, Any] | None
|
Optional metadata for extensions. |
None
|
base_push_notification_sender
¶
BasePushNotificationSender
¶
Bases: PushNotificationSender
Base implementation of PushNotificationSender interface.
__init__(httpx_client, config_store)
¶
Initializes the BasePushNotificationSender.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
httpx_client
|
AsyncClient
|
An async HTTP client instance to send notifications. |
required |
config_store
|
PushNotificationConfigStore
|
A PushNotificationConfigStore instance to retrieve configurations. |
required |
send_notification(task)
async
¶
Sends a push notification for a task if configuration exists.
database_push_notification_config_store
¶
DatabasePushNotificationConfigStore
¶
Bases: PushNotificationConfigStore
SQLAlchemy-based implementation of PushNotificationConfigStore.
Stores push notification configurations in a database supported by SQLAlchemy.
__init__(engine, create_table=True, table_name='push_notification_configs', encryption_key=None)
¶
Initializes the DatabasePushNotificationConfigStore.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
engine
|
AsyncEngine
|
An existing SQLAlchemy AsyncEngine to be used by the store. |
required |
create_table
|
bool
|
If true, create the table on initialization. |
True
|
table_name
|
str
|
Name of the database table. Defaults to 'push_notification_configs'. |
'push_notification_configs'
|
encryption_key
|
str | bytes | None
|
A key for encrypting sensitive configuration data.
If provided, |
None
|
delete_info(task_id, config_id=None)
async
¶
Deletes push notification configurations for a task.
If config_id is provided, only that specific configuration is deleted. If config_id is None, all configurations for the task are deleted.
get_info(task_id)
async
¶
Retrieves all push notification configurations for a task.
initialize()
async
¶
Initialize the database and create the table if needed.
set_info(task_id, notification_config)
async
¶
Sets or updates the push notification configuration for a task.
database_task_store
¶
DatabaseTaskStore
¶
Bases: TaskStore
SQLAlchemy-based implementation of TaskStore.
Stores task objects in a database supported by SQLAlchemy.
__init__(engine, create_table=True, table_name='tasks')
¶
Initializes the DatabaseTaskStore.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
engine
|
AsyncEngine
|
An existing SQLAlchemy AsyncEngine to be used by Task Store |
required |
create_table
|
bool
|
If true, create tasks table on initialization. |
True
|
table_name
|
str
|
Name of the database table. Defaults to 'tasks'. |
'tasks'
|
delete(task_id, context=None)
async
¶
Deletes a task from the database by ID.
get(task_id, context=None)
async
¶
Retrieves a task from the database by ID.
initialize()
async
¶
Initialize the database and create the table if needed.
save(task, context=None)
async
¶
Saves or updates a task in the database.
inmemory_push_notification_config_store
¶
InMemoryPushNotificationConfigStore
¶
Bases: PushNotificationConfigStore
In-memory implementation of PushNotificationConfigStore interface.
Stores push notification configurations in memory
__init__()
¶
Initializes the InMemoryPushNotificationConfigStore.
delete_info(task_id, config_id=None)
async
¶
Deletes the push notification configuration for a task from memory.
get_info(task_id)
async
¶
Retrieves the push notification configuration for a task from memory.
set_info(task_id, notification_config)
async
¶
Sets or updates the push notification configuration for a task in memory.
inmemory_task_store
¶
push_notification_config_store
¶
PushNotificationConfigStore
¶
Bases: ABC
Interface for storing and retrieving push notification configurations for tasks.
delete_info(task_id, config_id=None)
abstractmethod
async
¶
Deletes the push notification configuration for a task.
get_info(task_id)
abstractmethod
async
¶
Retrieves the push notification configuration for a task.
set_info(task_id, notification_config)
abstractmethod
async
¶
Sets or updates the push notification configuration for a task.
push_notification_sender
¶
result_aggregator
¶
ResultAggregator
¶
ResultAggregator is used to process the event streams from an AgentExecutor.
There are three main ways to use the ResultAggregator: 1) As part of a processing pipe. consume_and_emit will construct the updated task as the events arrive, and re-emit those events for another consumer 2) As part of a blocking call. consume_all will process the entire stream and return the final Task or Message object 3) As part of a push solution where the latest Task is emitted after processing an event. consume_and_emit_task will consume the Event stream, process the events to the current Task object and emit that Task object.
current_result
async
property
¶
Returns the current aggregated result (Task or Message).
This is the latest state processed from the event stream.
Returns:
Type | Description |
---|---|
Task | Message | None
|
The current |
Task | Message | None
|
|
__init__(task_manager)
¶
Initializes the ResultAggregator.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
task_manager
|
TaskManager
|
The |
required |
consume_all(consumer)
async
¶
Processes the entire event stream from the consumer and returns the final result.
Blocks until the event stream ends (queue is closed after final event or exception).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
consumer
|
EventConsumer
|
The |
required |
Returns:
Type | Description |
---|---|
Task | Message | None
|
The final |
Task | Message | None
|
Returns |
Raises:
Type | Description |
---|---|
BaseException
|
If the |
consume_and_break_on_interrupt(consumer, blocking=True, event_callback=None)
async
¶
Processes the event stream until completion or an interruptable state is encountered.
If blocking
is False, it returns after the first event that creates a Task or Message.
If blocking
is True, it waits for completion unless an auth_required
state is encountered, which is always an interruption.
If interrupted, consumption continues in a background task.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
consumer
|
EventConsumer
|
The |
required |
blocking
|
bool
|
If |
True
|
event_callback
|
Callable[[], Awaitable[None]] | None
|
Optional async callback function to be called after each event is processed in the background continuation. Mainly used for push notifications currently. |
None
|
Returns:
Type | Description |
---|---|
Task | Message | None
|
A tuple containing: |
bool
|
|
tuple[Task | Message | None, bool]
|
|
Raises:
Type | Description |
---|---|
BaseException
|
If the |
consume_and_emit(consumer)
async
¶
Processes the event stream from the consumer, updates the task state, and re-emits the same events.
Useful for streaming scenarios where the server needs to observe and process events (e.g., save task state, send push notifications) while forwarding them to the client.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
consumer
|
EventConsumer
|
The |
required |
Yields:
Type | Description |
---|---|
AsyncGenerator[Event]
|
The |
task_manager
¶
TaskManager
¶
Helps manage a task's lifecycle during execution of a request.
Responsible for retrieving, saving, and updating the Task
object based on
events received from the agent.
__init__(task_id, context_id, task_store, initial_message, context=None)
¶
Initializes the TaskManager.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
task_id
|
str | None
|
The ID of the task, if known from the request. |
required |
context_id
|
str | None
|
The ID of the context, if known from the request. |
required |
task_store
|
TaskStore
|
The |
required |
initial_message
|
Message | None
|
The |
required |
context
|
ServerCallContext | None
|
The |
None
|
ensure_task(event)
async
¶
Ensures a Task object exists in memory, loading from store or creating new if needed.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
event
|
TaskStatusUpdateEvent | TaskArtifactUpdateEvent
|
The task-related event triggering the need for a Task object. |
required |
Returns:
Type | Description |
---|---|
Task
|
An existing or newly created |
get_task()
async
¶
Retrieves the current task object, either from memory or the store.
If task_id
is set, it first checks the in-memory _current_task
,
then attempts to load it from the task_store
.
Returns:
Type | Description |
---|---|
Task | None
|
The |
process(event)
async
¶
Processes an event, updates the task state if applicable, stores it, and returns the event.
If the event is task-related (Task
, TaskStatusUpdateEvent
, TaskArtifactUpdateEvent
),
the internal task state is updated and persisted.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
event
|
Event
|
The event object received from the agent. |
required |
Returns:
Type | Description |
---|---|
Event
|
The same event object that was processed. |
save_task_event(event)
async
¶
Processes a task-related event (Task, Status, Artifact) and saves the updated task state.
Ensures task and context IDs match or are set from the event.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
event
|
Task | TaskStatusUpdateEvent | TaskArtifactUpdateEvent
|
The task-related event ( |
required |
Returns:
Type | Description |
---|---|
Task | None
|
The updated |
Raises:
Type | Description |
---|---|
ServerError
|
If the task ID in the event conflicts with the TaskManager's ID when the TaskManager's ID is already set. |
update_with_message(message, task)
¶
Updates a task object in memory by adding a new message to its history.
If the task has a message in its current status, that message is moved to the history first.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
message
|
Message
|
The new |
required |
task
|
Task
|
The |
required |
Returns:
Type | Description |
---|---|
Task
|
The updated |
task_store
¶
TaskStore
¶
Bases: ABC
Agent Task Store interface.
Defines the methods for persisting and retrieving Task
objects.
task_updater
¶
TaskUpdater
¶
Helper class for agents to publish updates to a task's event queue.
Simplifies the process of creating and enqueueing standard task events.
__init__(event_queue, task_id, context_id)
¶
Initializes the TaskUpdater.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
event_queue
|
EventQueue
|
The |
required |
task_id
|
str
|
The ID of the task. |
required |
context_id
|
str
|
The context ID of the task. |
required |
add_artifact(parts, artifact_id=None, name=None, metadata=None, append=None, last_chunk=None, extensions=None)
async
¶
Adds an artifact chunk to the task and publishes a TaskArtifactUpdateEvent
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
parts
|
list[Part]
|
A list of |
required |
artifact_id
|
str | None
|
The ID of the artifact. A new UUID is generated if not provided. |
None
|
name
|
str | None
|
Optional name for the artifact. |
None
|
metadata
|
dict[str, Any] | None
|
Optional metadata for the artifact. |
None
|
append
|
bool | None
|
Optional boolean indicating if this chunk appends to a previous one. |
None
|
last_chunk
|
bool | None
|
Optional boolean indicating if this is the last chunk. |
None
|
extensions
|
list[str] | None
|
Optional list of extensions for the artifact. |
None
|
cancel(message=None)
async
¶
Marks the task as cancelled and publishes a finalstatus update.
complete(message=None)
async
¶
Marks the task as completed and publishes a final status update.
failed(message=None)
async
¶
Marks the task as failed and publishes a final status update.
new_agent_message(parts, metadata=None)
¶
Creates a new message object sent by the agent for this task/context.
This method only creates the message object. It does not
automatically enqueue it.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
parts
|
list[Part]
|
A list of |
required |
metadata
|
dict[str, Any] | None
|
Optional metadata for the message. |
None
|
Returns:
Type | Description |
---|---|
Message
|
A new |
reject(message=None)
async
¶
Marks the task as rejected and publishes a final status update.
requires_auth(message=None, final=False)
async
¶
Marks the task as auth required and publishes a status update.
requires_input(message=None, final=False)
async
¶
Marks the task as input required and publishes a status update.
start_work(message=None)
async
¶
Marks the task as working and publishes a status update.
submit(message=None)
async
¶
Marks the task as submitted and publishes a status update.
update_status(state, message=None, final=False, timestamp=None, metadata=None)
async
¶
Updates the status of the task and publishes a TaskStatusUpdateEvent
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
state
|
TaskState
|
The new state of the task. |
required |
message
|
Message | None
|
An optional message associated with the status update. |
None
|
final
|
bool
|
If True, indicates this is the final status update for the task. |
False
|
timestamp
|
str | None
|
Optional ISO 8601 datetime string. Defaults to current time. |
None
|
metadata
|
dict[str, Any] | None
|
Optional metadata for extensions. |
None
|
types
¶
A2AError
¶
Bases: RootModel[JSONParseError | InvalidRequestError | MethodNotFoundError | InvalidParamsError | InternalError | TaskNotFoundError | TaskNotCancelableError | PushNotificationNotSupportedError | UnsupportedOperationError | ContentTypeNotSupportedError | InvalidAgentResponseError | AuthenticatedExtendedCardNotConfiguredError]
root
instance-attribute
¶
A discriminated union of all standard JSON-RPC and A2A-specific error types.
A2ARequest
¶
Bases: RootModel[SendMessageRequest | SendStreamingMessageRequest | GetTaskRequest | CancelTaskRequest | SetTaskPushNotificationConfigRequest | GetTaskPushNotificationConfigRequest | TaskResubscriptionRequest | ListTaskPushNotificationConfigRequest | DeleteTaskPushNotificationConfigRequest | GetAuthenticatedExtendedCardRequest]
root
instance-attribute
¶
A discriminated union representing all possible JSON-RPC 2.0 requests supported by the A2A specification.
APIKeySecurityScheme
¶
Bases: A2ABaseModel
Defines a security scheme using an API key.
description = None
class-attribute
instance-attribute
¶
An optional description for the security scheme.
in_
instance-attribute
¶
The location of the API key.
name
instance-attribute
¶
The name of the header, query, or cookie parameter to be used.
type = 'apiKey'
class-attribute
instance-attribute
¶
The type of the security scheme. Must be 'apiKey'.
AgentCapabilities
¶
Bases: A2ABaseModel
Defines optional capabilities supported by an agent.
extensions = None
class-attribute
instance-attribute
¶
A list of protocol extensions supported by the agent.
push_notifications = None
class-attribute
instance-attribute
¶
Indicates if the agent supports sending push notifications for asynchronous task updates.
state_transition_history = None
class-attribute
instance-attribute
¶
Indicates if the agent provides a history of state transitions for a task.
streaming = None
class-attribute
instance-attribute
¶
Indicates if the agent supports Server-Sent Events (SSE) for streaming responses.
AgentCard
¶
Bases: A2ABaseModel
The AgentCard is a self-describing manifest for an agent. It provides essential metadata including the agent's identity, capabilities, skills, supported communication methods, and security requirements.
additional_interfaces = None
class-attribute
instance-attribute
¶
A list of additional supported interfaces (transport and URL combinations). This allows agents to expose multiple transports, potentially at different URLs.
Best practices: - SHOULD include all supported transports for completeness - SHOULD include an entry matching the main 'url' and 'preferredTransport' - MAY reuse URLs if multiple transports are available at the same endpoint - MUST accurately declare the transport available at each URL
Clients can select any interface from this list based on their transport capabilities and preferences. This enables transport negotiation and fallback scenarios.
capabilities
instance-attribute
¶
A declaration of optional capabilities supported by the agent.
default_input_modes
instance-attribute
¶
Default set of supported input MIME types for all skills, which can be overridden on a per-skill basis.
default_output_modes
instance-attribute
¶
Default set of supported output MIME types for all skills, which can be overridden on a per-skill basis.
description = Field(..., examples=['Agent that helps users with recipes and cooking.'])
class-attribute
instance-attribute
¶
A human-readable description of the agent, assisting users and other agents in understanding its purpose.
documentation_url = None
class-attribute
instance-attribute
¶
An optional URL to the agent's documentation.
icon_url = None
class-attribute
instance-attribute
¶
An optional URL to an icon for the agent.
name = Field(..., examples=['Recipe Agent'])
class-attribute
instance-attribute
¶
A human-readable name for the agent.
preferred_transport = Field(default='JSONRPC', examples=['JSONRPC', 'GRPC', 'HTTP+JSON'])
class-attribute
instance-attribute
¶
The transport protocol for the preferred endpoint (the main 'url' field). If not specified, defaults to 'JSONRPC'.
IMPORTANT: The transport specified here MUST be available at the main 'url'. This creates a binding between the main URL and its supported transport protocol. Clients should prefer this transport and URL combination when both are supported.
protocol_version = '0.3.0'
class-attribute
instance-attribute
¶
The version of the A2A protocol this agent supports.
provider = None
class-attribute
instance-attribute
¶
Information about the agent's service provider.
security = Field(default=None, examples=[[{'oauth': ['read']}, {'api-key': [], 'mtls': []}]])
class-attribute
instance-attribute
¶
A list of security requirement objects that apply to all agent interactions. Each object lists security schemes that can be used. Follows the OpenAPI 3.0 Security Requirement Object. This list can be seen as an OR of ANDs. Each object in the list describes one possible set of security requirements that must be present on a request. This allows specifying, for example, "callers must either use OAuth OR an API Key AND mTLS."
security_schemes = None
class-attribute
instance-attribute
¶
A declaration of the security schemes available to authorize requests. The key is the scheme name. Follows the OpenAPI 3.0 Security Scheme Object.
signatures = None
class-attribute
instance-attribute
¶
JSON Web Signatures computed for this AgentCard.
skills
instance-attribute
¶
The set of skills, or distinct capabilities, that the agent can perform.
supports_authenticated_extended_card = None
class-attribute
instance-attribute
¶
If true, the agent can provide an extended agent card with additional details to authenticated users. Defaults to false.
url = Field(..., examples=['https://api.example.com/a2a/v1'])
class-attribute
instance-attribute
¶
The preferred endpoint URL for interacting with the agent. This URL MUST support the transport specified by 'preferredTransport'.
version = Field(..., examples=['1.0.0'])
class-attribute
instance-attribute
¶
The agent's own version number. The format is defined by the provider.
AgentCardSignature
¶
Bases: A2ABaseModel
AgentCardSignature represents a JWS signature of an AgentCard. This follows the JSON format of an RFC 7515 JSON Web Signature (JWS).
AgentExtension
¶
Bases: A2ABaseModel
A declaration of a protocol extension supported by an Agent.
description = None
class-attribute
instance-attribute
¶
A human-readable description of how this agent uses the extension.
params = None
class-attribute
instance-attribute
¶
Optional, extension-specific configuration parameters.
required = None
class-attribute
instance-attribute
¶
If true, the client must understand and comply with the extension's requirements to interact with the agent.
uri
instance-attribute
¶
The unique URI identifying the extension.
AgentInterface
¶
Bases: A2ABaseModel
Declares a combination of a target URL and a transport protocol for interacting with the agent. This allows agents to expose the same functionality over multiple transport mechanisms.
transport = Field(..., examples=['JSONRPC', 'GRPC', 'HTTP+JSON'])
class-attribute
instance-attribute
¶
The transport protocol supported at this URL.
url = Field(..., examples=['https://api.example.com/a2a/v1', 'https://grpc.example.com/a2a', 'https://rest.example.com/v1'])
class-attribute
instance-attribute
¶
The URL where this interface is available. Must be a valid absolute HTTPS URL in production.
AgentProvider
¶
AgentSkill
¶
Bases: A2ABaseModel
Represents a distinct capability or function that an agent can perform.
description
instance-attribute
¶
A detailed description of the skill, intended to help clients or users understand its purpose and functionality.
examples = Field(default=None, examples=[['I need a recipe for bread']])
class-attribute
instance-attribute
¶
Example prompts or scenarios that this skill can handle. Provides a hint to the client on how to use the skill.
id
instance-attribute
¶
A unique identifier for the agent's skill.
input_modes = None
class-attribute
instance-attribute
¶
The set of supported input MIME types for this skill, overriding the agent's defaults.
name
instance-attribute
¶
A human-readable name for the skill.
output_modes = None
class-attribute
instance-attribute
¶
The set of supported output MIME types for this skill, overriding the agent's defaults.
security = Field(default=None, examples=[[{'google': ['oidc']}]])
class-attribute
instance-attribute
¶
Security schemes necessary for the agent to leverage this skill. As in the overall AgentCard.security, this list represents a logical OR of security requirement objects. Each object is a set of security schemes that must be used together (a logical AND).
tags = Field(..., examples=[['cooking', 'customer support', 'billing']])
class-attribute
instance-attribute
¶
A set of keywords describing the skill's capabilities.
Artifact
¶
Bases: A2ABaseModel
Represents a file, data structure, or other resource generated by an agent during a task.
artifact_id
instance-attribute
¶
A unique identifier (e.g. UUID) for the artifact within the scope of the task.
description = None
class-attribute
instance-attribute
¶
An optional, human-readable description of the artifact.
extensions = None
class-attribute
instance-attribute
¶
The URIs of extensions that are relevant to this artifact.
metadata = None
class-attribute
instance-attribute
¶
Optional metadata for extensions. The key is an extension-specific identifier.
name = None
class-attribute
instance-attribute
¶
An optional, human-readable name for the artifact.
parts
instance-attribute
¶
An array of content parts that make up the artifact.
AuthenticatedExtendedCardNotConfiguredError
¶
Bases: A2ABaseModel
An A2A-specific error indicating that the agent does not have an Authenticated Extended Card configured
code = -32007
class-attribute
instance-attribute
¶
The error code for when an authenticated extended card is not configured.
data = None
class-attribute
instance-attribute
¶
A primitive or structured value containing additional information about the error. This may be omitted.
message = 'Authenticated Extended Card is not configured'
class-attribute
instance-attribute
¶
The error message.
AuthorizationCodeOAuthFlow
¶
Bases: A2ABaseModel
Defines configuration details for the OAuth 2.0 Authorization Code flow.
authorization_url
instance-attribute
¶
The authorization URL to be used for this flow. This MUST be a URL and use TLS.
refresh_url = None
class-attribute
instance-attribute
¶
The URL to be used for obtaining refresh tokens. This MUST be a URL and use TLS.
scopes
instance-attribute
¶
The available scopes for the OAuth2 security scheme. A map between the scope name and a short description for it.
token_url
instance-attribute
¶
The token URL to be used for this flow. This MUST be a URL and use TLS.
CancelTaskRequest
¶
Bases: A2ABaseModel
Represents a JSON-RPC request for the tasks/cancel
method.
id
instance-attribute
¶
The identifier for this request.
jsonrpc = '2.0'
class-attribute
instance-attribute
¶
The version of the JSON-RPC protocol. MUST be exactly "2.0".
method = 'tasks/cancel'
class-attribute
instance-attribute
¶
The method name. Must be 'tasks/cancel'.
params
instance-attribute
¶
The parameters identifying the task to cancel.
CancelTaskResponse
¶
Bases: RootModel[JSONRPCErrorResponse | CancelTaskSuccessResponse]
root
instance-attribute
¶
Represents a JSON-RPC response for the tasks/cancel
method.
CancelTaskSuccessResponse
¶
Bases: A2ABaseModel
Represents a successful JSON-RPC response for the tasks/cancel
method.
ClientCredentialsOAuthFlow
¶
Bases: A2ABaseModel
Defines configuration details for the OAuth 2.0 Client Credentials flow.
refresh_url = None
class-attribute
instance-attribute
¶
The URL to be used for obtaining refresh tokens. This MUST be a URL.
scopes
instance-attribute
¶
The available scopes for the OAuth2 security scheme. A map between the scope name and a short description for it.
token_url
instance-attribute
¶
The token URL to be used for this flow. This MUST be a URL.
ContentTypeNotSupportedError
¶
Bases: A2ABaseModel
An A2A-specific error indicating an incompatibility between the requested content types and the agent's capabilities.
code = -32005
class-attribute
instance-attribute
¶
The error code for an unsupported content type.
data = None
class-attribute
instance-attribute
¶
A primitive or structured value containing additional information about the error. This may be omitted.
message = 'Incompatible content types'
class-attribute
instance-attribute
¶
The error message.
DataPart
¶
Bases: A2ABaseModel
Represents a structured data segment (e.g., JSON) within a message or artifact.
DeleteTaskPushNotificationConfigParams
¶
Bases: A2ABaseModel
Defines parameters for deleting a specific push notification configuration for a task.
DeleteTaskPushNotificationConfigRequest
¶
Bases: A2ABaseModel
Represents a JSON-RPC request for the tasks/pushNotificationConfig/delete
method.
id
instance-attribute
¶
The identifier for this request.
jsonrpc = '2.0'
class-attribute
instance-attribute
¶
The version of the JSON-RPC protocol. MUST be exactly "2.0".
method = 'tasks/pushNotificationConfig/delete'
class-attribute
instance-attribute
¶
The method name. Must be 'tasks/pushNotificationConfig/delete'.
params
instance-attribute
¶
The parameters identifying the push notification configuration to delete.
DeleteTaskPushNotificationConfigResponse
¶
Bases: RootModel[JSONRPCErrorResponse | DeleteTaskPushNotificationConfigSuccessResponse]
root
instance-attribute
¶
Represents a JSON-RPC response for the tasks/pushNotificationConfig/delete
method.
DeleteTaskPushNotificationConfigSuccessResponse
¶
Bases: A2ABaseModel
Represents a successful JSON-RPC response for the tasks/pushNotificationConfig/delete
method.
FileBase
¶
FilePart
¶
Bases: A2ABaseModel
Represents a file segment within a message or artifact. The file content can be provided either directly as bytes or as a URI.
file
instance-attribute
¶
The file content, represented as either a URI or as base64-encoded bytes.
kind = 'file'
class-attribute
instance-attribute
¶
The type of this part, used as a discriminator. Always 'file'.
metadata = None
class-attribute
instance-attribute
¶
Optional metadata associated with this part.
FileWithBytes
¶
Bases: A2ABaseModel
Represents a file with its content provided directly as a base64-encoded string.
FileWithUri
¶
Bases: A2ABaseModel
Represents a file with its content located at a specific URI.
GetAuthenticatedExtendedCardRequest
¶
Bases: A2ABaseModel
Represents a JSON-RPC request for the agent/getAuthenticatedExtendedCard
method.
id
instance-attribute
¶
The identifier for this request.
jsonrpc = '2.0'
class-attribute
instance-attribute
¶
The version of the JSON-RPC protocol. MUST be exactly "2.0".
method = 'agent/getAuthenticatedExtendedCard'
class-attribute
instance-attribute
¶
The method name. Must be 'agent/getAuthenticatedExtendedCard'.
GetAuthenticatedExtendedCardResponse
¶
Bases: RootModel[JSONRPCErrorResponse | GetAuthenticatedExtendedCardSuccessResponse]
root
instance-attribute
¶
Represents a JSON-RPC response for the agent/getAuthenticatedExtendedCard
method.
GetAuthenticatedExtendedCardSuccessResponse
¶
Bases: A2ABaseModel
Represents a successful JSON-RPC response for the agent/getAuthenticatedExtendedCard
method.
GetTaskPushNotificationConfigParams
¶
Bases: A2ABaseModel
Defines parameters for fetching a specific push notification configuration for a task.
id
instance-attribute
¶
The unique identifier (e.g. UUID) of the task.
metadata = None
class-attribute
instance-attribute
¶
Optional metadata associated with the request.
push_notification_config_id = None
class-attribute
instance-attribute
¶
The ID of the push notification configuration to retrieve.
GetTaskPushNotificationConfigRequest
¶
Bases: A2ABaseModel
Represents a JSON-RPC request for the tasks/pushNotificationConfig/get
method.
id
instance-attribute
¶
The identifier for this request.
jsonrpc = '2.0'
class-attribute
instance-attribute
¶
The version of the JSON-RPC protocol. MUST be exactly "2.0".
method = 'tasks/pushNotificationConfig/get'
class-attribute
instance-attribute
¶
The method name. Must be 'tasks/pushNotificationConfig/get'.
params
instance-attribute
¶
The parameters for getting a push notification configuration.
GetTaskPushNotificationConfigResponse
¶
Bases: RootModel[JSONRPCErrorResponse | GetTaskPushNotificationConfigSuccessResponse]
root
instance-attribute
¶
Represents a JSON-RPC response for the tasks/pushNotificationConfig/get
method.
GetTaskPushNotificationConfigSuccessResponse
¶
Bases: A2ABaseModel
Represents a successful JSON-RPC response for the tasks/pushNotificationConfig/get
method.
id = None
class-attribute
instance-attribute
¶
The identifier established by the client.
jsonrpc = '2.0'
class-attribute
instance-attribute
¶
The version of the JSON-RPC protocol. MUST be exactly "2.0".
result
instance-attribute
¶
The result, containing the requested push notification configuration.
GetTaskRequest
¶
Bases: A2ABaseModel
Represents a JSON-RPC request for the tasks/get
method.
id
instance-attribute
¶
The identifier for this request.
jsonrpc = '2.0'
class-attribute
instance-attribute
¶
The version of the JSON-RPC protocol. MUST be exactly "2.0".
method = 'tasks/get'
class-attribute
instance-attribute
¶
The method name. Must be 'tasks/get'.
params
instance-attribute
¶
The parameters for querying a task.
GetTaskResponse
¶
Bases: RootModel[JSONRPCErrorResponse | GetTaskSuccessResponse]
root
instance-attribute
¶
Represents a JSON-RPC response for the tasks/get
method.
GetTaskSuccessResponse
¶
Bases: A2ABaseModel
Represents a successful JSON-RPC response for the tasks/get
method.
HTTPAuthSecurityScheme
¶
Bases: A2ABaseModel
Defines a security scheme using HTTP authentication.
bearer_format = None
class-attribute
instance-attribute
¶
A hint to the client to identify how the bearer token is formatted (e.g., "JWT"). This is primarily for documentation purposes.
description = None
class-attribute
instance-attribute
¶
An optional description for the security scheme.
scheme
instance-attribute
¶
The name of the HTTP Authentication scheme to be used in the Authorization header, as defined in RFC7235 (e.g., "Bearer"). This value should be registered in the IANA Authentication Scheme registry.
type = 'http'
class-attribute
instance-attribute
¶
The type of the security scheme. Must be 'http'.
ImplicitOAuthFlow
¶
Bases: A2ABaseModel
Defines configuration details for the OAuth 2.0 Implicit flow.
authorization_url
instance-attribute
¶
The authorization URL to be used for this flow. This MUST be a URL.
refresh_url = None
class-attribute
instance-attribute
¶
The URL to be used for obtaining refresh tokens. This MUST be a URL.
scopes
instance-attribute
¶
The available scopes for the OAuth2 security scheme. A map between the scope name and a short description for it.
In
¶
Bases: str
, Enum
The location of the API key.
InternalError
¶
Bases: A2ABaseModel
An error indicating an internal error on the server.
code = -32603
class-attribute
instance-attribute
¶
The error code for an internal server error.
data = None
class-attribute
instance-attribute
¶
A primitive or structured value containing additional information about the error. This may be omitted.
message = 'Internal error'
class-attribute
instance-attribute
¶
The error message.
InvalidAgentResponseError
¶
Bases: A2ABaseModel
An A2A-specific error indicating that the agent returned a response that does not conform to the specification for the current method.
code = -32006
class-attribute
instance-attribute
¶
The error code for an invalid agent response.
data = None
class-attribute
instance-attribute
¶
A primitive or structured value containing additional information about the error. This may be omitted.
message = 'Invalid agent response'
class-attribute
instance-attribute
¶
The error message.
InvalidParamsError
¶
Bases: A2ABaseModel
An error indicating that the method parameters are invalid.
code = -32602
class-attribute
instance-attribute
¶
The error code for an invalid parameters error.
data = None
class-attribute
instance-attribute
¶
A primitive or structured value containing additional information about the error. This may be omitted.
message = 'Invalid parameters'
class-attribute
instance-attribute
¶
The error message.
InvalidRequestError
¶
Bases: A2ABaseModel
An error indicating that the JSON sent is not a valid Request object.
code = -32600
class-attribute
instance-attribute
¶
The error code for an invalid request.
data = None
class-attribute
instance-attribute
¶
A primitive or structured value containing additional information about the error. This may be omitted.
message = 'Request payload validation error'
class-attribute
instance-attribute
¶
The error message.
JSONParseError
¶
Bases: A2ABaseModel
An error indicating that the server received invalid JSON.
code = -32700
class-attribute
instance-attribute
¶
The error code for a JSON parse error.
data = None
class-attribute
instance-attribute
¶
A primitive or structured value containing additional information about the error. This may be omitted.
message = 'Invalid JSON payload'
class-attribute
instance-attribute
¶
The error message.
JSONRPCError
¶
Bases: A2ABaseModel
Represents a JSON-RPC 2.0 Error object, included in an error response.
code
instance-attribute
¶
A number that indicates the error type that occurred.
data = None
class-attribute
instance-attribute
¶
A primitive or structured value containing additional information about the error. This may be omitted.
message
instance-attribute
¶
A string providing a short description of the error.
JSONRPCErrorResponse
¶
Bases: A2ABaseModel
Represents a JSON-RPC 2.0 Error Response object.
JSONRPCMessage
¶
Bases: A2ABaseModel
Defines the base structure for any JSON-RPC 2.0 request, response, or notification.
id = None
class-attribute
instance-attribute
¶
A unique identifier established by the client. It must be a String, a Number, or null. The server must reply with the same value in the response. This property is omitted for notifications.
jsonrpc = '2.0'
class-attribute
instance-attribute
¶
The version of the JSON-RPC protocol. MUST be exactly "2.0".
JSONRPCRequest
¶
Bases: A2ABaseModel
Represents a JSON-RPC 2.0 Request object.
id = None
class-attribute
instance-attribute
¶
A unique identifier established by the client. It must be a String, a Number, or null. The server must reply with the same value in the response. This property is omitted for notifications.
jsonrpc = '2.0'
class-attribute
instance-attribute
¶
The version of the JSON-RPC protocol. MUST be exactly "2.0".
method
instance-attribute
¶
A string containing the name of the method to be invoked.
params = None
class-attribute
instance-attribute
¶
A structured value holding the parameter values to be used during the method invocation.
JSONRPCResponse
¶
Bases: RootModel[JSONRPCErrorResponse | SendMessageSuccessResponse | SendStreamingMessageSuccessResponse | GetTaskSuccessResponse | CancelTaskSuccessResponse | SetTaskPushNotificationConfigSuccessResponse | GetTaskPushNotificationConfigSuccessResponse | ListTaskPushNotificationConfigSuccessResponse | DeleteTaskPushNotificationConfigSuccessResponse | GetAuthenticatedExtendedCardSuccessResponse]
root
instance-attribute
¶
A discriminated union representing all possible JSON-RPC 2.0 responses for the A2A specification methods.
JSONRPCSuccessResponse
¶
Bases: A2ABaseModel
Represents a successful JSON-RPC 2.0 Response object.
id = None
class-attribute
instance-attribute
¶
The identifier established by the client.
jsonrpc = '2.0'
class-attribute
instance-attribute
¶
The version of the JSON-RPC protocol. MUST be exactly "2.0".
result
instance-attribute
¶
The value of this member is determined by the method invoked on the Server.
ListTaskPushNotificationConfigParams
¶
ListTaskPushNotificationConfigRequest
¶
Bases: A2ABaseModel
Represents a JSON-RPC request for the tasks/pushNotificationConfig/list
method.
id
instance-attribute
¶
The identifier for this request.
jsonrpc = '2.0'
class-attribute
instance-attribute
¶
The version of the JSON-RPC protocol. MUST be exactly "2.0".
method = 'tasks/pushNotificationConfig/list'
class-attribute
instance-attribute
¶
The method name. Must be 'tasks/pushNotificationConfig/list'.
params
instance-attribute
¶
The parameters identifying the task whose configurations are to be listed.
ListTaskPushNotificationConfigResponse
¶
Bases: RootModel[JSONRPCErrorResponse | ListTaskPushNotificationConfigSuccessResponse]
root
instance-attribute
¶
Represents a JSON-RPC response for the tasks/pushNotificationConfig/list
method.
ListTaskPushNotificationConfigSuccessResponse
¶
Bases: A2ABaseModel
Represents a successful JSON-RPC response for the tasks/pushNotificationConfig/list
method.
id = None
class-attribute
instance-attribute
¶
The identifier established by the client.
jsonrpc = '2.0'
class-attribute
instance-attribute
¶
The version of the JSON-RPC protocol. MUST be exactly "2.0".
result
instance-attribute
¶
The result, containing an array of all push notification configurations for the task.
Message
¶
Bases: A2ABaseModel
Represents a single message in the conversation between a user and an agent.
context_id = None
class-attribute
instance-attribute
¶
The context ID for this message, used to group related interactions.
extensions = None
class-attribute
instance-attribute
¶
The URIs of extensions that are relevant to this message.
kind = 'message'
class-attribute
instance-attribute
¶
The type of this object, used as a discriminator. Always 'message' for a Message.
message_id
instance-attribute
¶
A unique identifier for the message, typically a UUID, generated by the sender.
metadata = None
class-attribute
instance-attribute
¶
Optional metadata for extensions. The key is an extension-specific identifier.
parts
instance-attribute
¶
An array of content parts that form the message body. A message can be composed of multiple parts of different types (e.g., text and files).
reference_task_ids = None
class-attribute
instance-attribute
¶
A list of other task IDs that this message references for additional context.
role
instance-attribute
¶
Identifies the sender of the message. user
for the client, agent
for the service.
task_id = None
class-attribute
instance-attribute
¶
The ID of the task this message is part of. Can be omitted for the first message of a new task.
MessageSendConfiguration
¶
Bases: A2ABaseModel
Defines configuration options for a message/send
or message/stream
request.
accepted_output_modes = None
class-attribute
instance-attribute
¶
A list of output MIME types the client is prepared to accept in the response.
blocking = None
class-attribute
instance-attribute
¶
If true, the client will wait for the task to complete. The server may reject this if the task is long-running.
history_length = None
class-attribute
instance-attribute
¶
The number of most recent messages from the task's history to retrieve in the response.
push_notification_config = None
class-attribute
instance-attribute
¶
Configuration for the agent to send push notifications for updates after the initial response.
MessageSendParams
¶
Bases: A2ABaseModel
Defines the parameters for a request to send a message to an agent. This can be used to create a new task, continue an existing one, or restart a task.
MethodNotFoundError
¶
Bases: A2ABaseModel
An error indicating that the requested method does not exist or is not available.
code = -32601
class-attribute
instance-attribute
¶
The error code for a method not found error.
data = None
class-attribute
instance-attribute
¶
A primitive or structured value containing additional information about the error. This may be omitted.
message = 'Method not found'
class-attribute
instance-attribute
¶
The error message.
MutualTLSSecurityScheme
¶
OAuth2SecurityScheme
¶
Bases: A2ABaseModel
Defines a security scheme using OAuth 2.0.
description = None
class-attribute
instance-attribute
¶
An optional description for the security scheme.
flows
instance-attribute
¶
An object containing configuration information for the supported OAuth 2.0 flows.
oauth2_metadata_url = None
class-attribute
instance-attribute
¶
URL to the oauth2 authorization server metadata RFC8414. TLS is required.
type = 'oauth2'
class-attribute
instance-attribute
¶
The type of the security scheme. Must be 'oauth2'.
OAuthFlows
¶
Bases: A2ABaseModel
Defines the configuration for the supported OAuth 2.0 flows.
authorization_code = None
class-attribute
instance-attribute
¶
Configuration for the OAuth Authorization Code flow. Previously called accessCode in OpenAPI 2.0.
client_credentials = None
class-attribute
instance-attribute
¶
Configuration for the OAuth Client Credentials flow. Previously called application in OpenAPI 2.0.
implicit = None
class-attribute
instance-attribute
¶
Configuration for the OAuth Implicit flow.
password = None
class-attribute
instance-attribute
¶
Configuration for the OAuth Resource Owner Password flow.
OpenIdConnectSecurityScheme
¶
Bases: A2ABaseModel
Defines a security scheme using OpenID Connect.
description = None
class-attribute
instance-attribute
¶
An optional description for the security scheme.
open_id_connect_url
instance-attribute
¶
The OpenID Connect Discovery URL for the OIDC provider's metadata.
type = 'openIdConnect'
class-attribute
instance-attribute
¶
The type of the security scheme. Must be 'openIdConnect'.
Part
¶
PartBase
¶
Bases: A2ABaseModel
Defines base properties common to all message or artifact parts.
metadata = None
class-attribute
instance-attribute
¶
Optional metadata associated with this part.
PasswordOAuthFlow
¶
Bases: A2ABaseModel
Defines configuration details for the OAuth 2.0 Resource Owner Password flow.
refresh_url = None
class-attribute
instance-attribute
¶
The URL to be used for obtaining refresh tokens. This MUST be a URL.
scopes
instance-attribute
¶
The available scopes for the OAuth2 security scheme. A map between the scope name and a short description for it.
token_url
instance-attribute
¶
The token URL to be used for this flow. This MUST be a URL.
PushNotificationAuthenticationInfo
¶
Bases: A2ABaseModel
Defines authentication details for a push notification endpoint.
PushNotificationConfig
¶
Bases: A2ABaseModel
Defines the configuration for setting up push notifications for task updates.
authentication = None
class-attribute
instance-attribute
¶
Optional authentication details for the agent to use when calling the notification URL.
id = None
class-attribute
instance-attribute
¶
A unique identifier (e.g. UUID) for the push notification configuration, set by the client to support multiple notification callbacks.
token = None
class-attribute
instance-attribute
¶
A unique token for this task or session to validate incoming push notifications.
url
instance-attribute
¶
The callback URL where the agent should send push notifications.
PushNotificationNotSupportedError
¶
Bases: A2ABaseModel
An A2A-specific error indicating that the agent does not support push notifications.
code = -32003
class-attribute
instance-attribute
¶
The error code for when push notifications are not supported.
data = None
class-attribute
instance-attribute
¶
A primitive or structured value containing additional information about the error. This may be omitted.
message = 'Push Notification is not supported'
class-attribute
instance-attribute
¶
The error message.
Role
¶
Bases: str
, Enum
Identifies the sender of the message. user
for the client, agent
for the service.
SecurityScheme
¶
Bases: RootModel[APIKeySecurityScheme | HTTPAuthSecurityScheme | OAuth2SecurityScheme | OpenIdConnectSecurityScheme | MutualTLSSecurityScheme]
root
instance-attribute
¶
Defines a security scheme that can be used to secure an agent's endpoints. This is a discriminated union type based on the OpenAPI 3.0 Security Scheme Object.
SecuritySchemeBase
¶
Bases: A2ABaseModel
Defines base properties shared by all security scheme objects.
description = None
class-attribute
instance-attribute
¶
An optional description for the security scheme.
SendMessageRequest
¶
Bases: A2ABaseModel
Represents a JSON-RPC request for the message/send
method.
id
instance-attribute
¶
The identifier for this request.
jsonrpc = '2.0'
class-attribute
instance-attribute
¶
The version of the JSON-RPC protocol. MUST be exactly "2.0".
method = 'message/send'
class-attribute
instance-attribute
¶
The method name. Must be 'message/send'.
params
instance-attribute
¶
The parameters for sending a message.
SendMessageResponse
¶
Bases: RootModel[JSONRPCErrorResponse | SendMessageSuccessResponse]
root
instance-attribute
¶
Represents a JSON-RPC response for the message/send
method.
SendMessageSuccessResponse
¶
Bases: A2ABaseModel
Represents a successful JSON-RPC response for the message/send
method.
id = None
class-attribute
instance-attribute
¶
The identifier established by the client.
jsonrpc = '2.0'
class-attribute
instance-attribute
¶
The version of the JSON-RPC protocol. MUST be exactly "2.0".
result
instance-attribute
¶
The result, which can be a direct reply Message or the initial Task object.
SendStreamingMessageRequest
¶
Bases: A2ABaseModel
Represents a JSON-RPC request for the message/stream
method.
id
instance-attribute
¶
The identifier for this request.
jsonrpc = '2.0'
class-attribute
instance-attribute
¶
The version of the JSON-RPC protocol. MUST be exactly "2.0".
method = 'message/stream'
class-attribute
instance-attribute
¶
The method name. Must be 'message/stream'.
params
instance-attribute
¶
The parameters for sending a message.
SendStreamingMessageResponse
¶
Bases: RootModel[JSONRPCErrorResponse | SendStreamingMessageSuccessResponse]
root
instance-attribute
¶
Represents a JSON-RPC response for the message/stream
method.
SendStreamingMessageSuccessResponse
¶
Bases: A2ABaseModel
Represents a successful JSON-RPC response for the message/stream
method.
The server may send multiple response objects for a single request.
id = None
class-attribute
instance-attribute
¶
The identifier established by the client.
jsonrpc = '2.0'
class-attribute
instance-attribute
¶
The version of the JSON-RPC protocol. MUST be exactly "2.0".
result
instance-attribute
¶
The result, which can be a Message, Task, or a streaming update event.
SetTaskPushNotificationConfigRequest
¶
Bases: A2ABaseModel
Represents a JSON-RPC request for the tasks/pushNotificationConfig/set
method.
id
instance-attribute
¶
The identifier for this request.
jsonrpc = '2.0'
class-attribute
instance-attribute
¶
The version of the JSON-RPC protocol. MUST be exactly "2.0".
method = 'tasks/pushNotificationConfig/set'
class-attribute
instance-attribute
¶
The method name. Must be 'tasks/pushNotificationConfig/set'.
params
instance-attribute
¶
The parameters for setting the push notification configuration.
SetTaskPushNotificationConfigResponse
¶
Bases: RootModel[JSONRPCErrorResponse | SetTaskPushNotificationConfigSuccessResponse]
root
instance-attribute
¶
Represents a JSON-RPC response for the tasks/pushNotificationConfig/set
method.
SetTaskPushNotificationConfigSuccessResponse
¶
Bases: A2ABaseModel
Represents a successful JSON-RPC response for the tasks/pushNotificationConfig/set
method.
Task
¶
Bases: A2ABaseModel
Represents a single, stateful operation or conversation between a client and an agent.
artifacts = None
class-attribute
instance-attribute
¶
A collection of artifacts generated by the agent during the execution of the task.
context_id
instance-attribute
¶
A server-generated unique identifier (e.g. UUID) for maintaining context across multiple related tasks or interactions.
history = None
class-attribute
instance-attribute
¶
An array of messages exchanged during the task, representing the conversation history.
id
instance-attribute
¶
A unique identifier (e.g. UUID) for the task, generated by the server for a new task.
kind = 'task'
class-attribute
instance-attribute
¶
The type of this object, used as a discriminator. Always 'task' for a Task.
metadata = None
class-attribute
instance-attribute
¶
Optional metadata for extensions. The key is an extension-specific identifier.
status
instance-attribute
¶
The current status of the task, including its state and a descriptive message.
TaskArtifactUpdateEvent
¶
Bases: A2ABaseModel
An event sent by the agent to notify the client that an artifact has been generated or updated. This is typically used in streaming models.
append = None
class-attribute
instance-attribute
¶
If true, the content of this artifact should be appended to a previously sent artifact with the same ID.
artifact
instance-attribute
¶
The artifact that was generated or updated.
context_id
instance-attribute
¶
The context ID associated with the task.
kind = 'artifact-update'
class-attribute
instance-attribute
¶
The type of this event, used as a discriminator. Always 'artifact-update'.
last_chunk = None
class-attribute
instance-attribute
¶
If true, this is the final chunk of the artifact.
metadata = None
class-attribute
instance-attribute
¶
Optional metadata for extensions.
task_id
instance-attribute
¶
The ID of the task this artifact belongs to.
TaskIdParams
¶
TaskNotCancelableError
¶
Bases: A2ABaseModel
An A2A-specific error indicating that the task is in a state where it cannot be canceled.
code = -32002
class-attribute
instance-attribute
¶
The error code for a task that cannot be canceled.
data = None
class-attribute
instance-attribute
¶
A primitive or structured value containing additional information about the error. This may be omitted.
message = 'Task cannot be canceled'
class-attribute
instance-attribute
¶
The error message.
TaskNotFoundError
¶
Bases: A2ABaseModel
An A2A-specific error indicating that the requested task ID was not found.
code = -32001
class-attribute
instance-attribute
¶
The error code for a task not found error.
data = None
class-attribute
instance-attribute
¶
A primitive or structured value containing additional information about the error. This may be omitted.
message = 'Task not found'
class-attribute
instance-attribute
¶
The error message.
TaskPushNotificationConfig
¶
TaskQueryParams
¶
Bases: A2ABaseModel
Defines parameters for querying a task, with an option to limit history length.
history_length = None
class-attribute
instance-attribute
¶
The number of most recent messages from the task's history to retrieve.
id
instance-attribute
¶
The unique identifier (e.g. UUID) of the task.
metadata = None
class-attribute
instance-attribute
¶
Optional metadata associated with the request.
TaskResubscriptionRequest
¶
Bases: A2ABaseModel
Represents a JSON-RPC request for the tasks/resubscribe
method, used to resume a streaming connection.
id
instance-attribute
¶
The identifier for this request.
jsonrpc = '2.0'
class-attribute
instance-attribute
¶
The version of the JSON-RPC protocol. MUST be exactly "2.0".
method = 'tasks/resubscribe'
class-attribute
instance-attribute
¶
The method name. Must be 'tasks/resubscribe'.
params
instance-attribute
¶
The parameters identifying the task to resubscribe to.
TaskState
¶
Bases: str
, Enum
Defines the lifecycle states of a Task.
TaskStatus
¶
Bases: A2ABaseModel
Represents the status of a task at a specific point in time.
message = None
class-attribute
instance-attribute
¶
An optional, human-readable message providing more details about the current status.
state
instance-attribute
¶
The current state of the task's lifecycle.
timestamp = Field(default=None, examples=['2023-10-27T10:00:00Z'])
class-attribute
instance-attribute
¶
An ISO 8601 datetime string indicating when this status was recorded.
TaskStatusUpdateEvent
¶
Bases: A2ABaseModel
An event sent by the agent to notify the client of a change in a task's status. This is typically used in streaming or subscription models.
context_id
instance-attribute
¶
The context ID associated with the task.
final
instance-attribute
¶
If true, this is the final event in the stream for this interaction.
kind = 'status-update'
class-attribute
instance-attribute
¶
The type of this event, used as a discriminator. Always 'status-update'.
metadata = None
class-attribute
instance-attribute
¶
Optional metadata for extensions.
status
instance-attribute
¶
The new status of the task.
task_id
instance-attribute
¶
The ID of the task that was updated.
TextPart
¶
Bases: A2ABaseModel
Represents a text segment within a message or artifact.
TransportProtocol
¶
Bases: str
, Enum
Supported A2A transport protocols.
UnsupportedOperationError
¶
Bases: A2ABaseModel
An A2A-specific error indicating that the requested operation is not supported by the agent.
code = -32004
class-attribute
instance-attribute
¶
The error code for an unsupported operation.
data = None
class-attribute
instance-attribute
¶
A primitive or structured value containing additional information about the error. This may be omitted.
message = 'This operation is not supported'
class-attribute
instance-attribute
¶
The error message.
utils
¶
Utility functions for the A2A Python SDK.
append_artifact_to_task(task, event)
¶
Helper method for updating a Task object with new artifact data from an event.
Handles creating the artifacts list if it doesn't exist, adding new artifacts,
and appending parts to existing artifacts based on the append
flag in the event.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
task
|
Task
|
The |
required |
event
|
TaskArtifactUpdateEvent
|
The |
required |
are_modalities_compatible(server_output_modes, client_output_modes)
¶
Checks if server and client output modalities (MIME types) are compatible.
Modalities are compatible if: 1. The client specifies no preferred output modes (client_output_modes is None or empty). 2. The server specifies no supported output modes (server_output_modes is None or empty). 3. There is at least one common modality between the server's supported list and the client's preferred list.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
server_output_modes
|
list[str] | None
|
A list of MIME types supported by the server/agent for output. Can be None or empty if the server doesn't specify. |
required |
client_output_modes
|
list[str] | None
|
A list of MIME types preferred by the client for output. Can be None or empty if the client accepts any. |
required |
Returns:
Type | Description |
---|---|
bool
|
True if the modalities are compatible, False otherwise. |
build_text_artifact(text, artifact_id)
¶
Helper to create a text artifact.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
text
|
str
|
The text content for the artifact. |
required |
artifact_id
|
str
|
The ID for the artifact. |
required |
Returns:
Type | Description |
---|---|
Artifact
|
An |
completed_task(task_id, context_id, artifacts, history=None)
¶
Creates a Task object in the 'completed' state.
Useful for constructing a final Task representation when the agent finishes and produces artifacts.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
task_id
|
str
|
The ID of the task. |
required |
context_id
|
str
|
The context ID of the task. |
required |
artifacts
|
list[Artifact]
|
A list of |
required |
history
|
list[Message] | None
|
An optional list of |
None
|
Returns:
Type | Description |
---|---|
Task
|
A |
create_task_obj(message_send_params)
¶
Create a new task object from message send params.
Generates UUIDs for task and context IDs if they are not already present in the message.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
message_send_params
|
MessageSendParams
|
The |
required |
Returns:
Type | Description |
---|---|
Task
|
A new |
get_data_parts(parts)
¶
Extracts dictionary data from all DataPart objects in a list of Parts.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
parts
|
list[Part]
|
A list of |
required |
Returns:
Type | Description |
---|---|
list[dict[str, Any]]
|
A list of dictionaries containing the data from any |
get_file_parts(parts)
¶
Extracts file data from all FilePart objects in a list of Parts.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
parts
|
list[Part]
|
A list of |
required |
Returns:
Type | Description |
---|---|
list[FileWithBytes | FileWithUri]
|
A list of |
get_message_text(message, delimiter='\n')
¶
Extracts and joins all text content from a Message's parts.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
message
|
Message
|
The |
required |
delimiter
|
str
|
The string to use when joining text from multiple TextParts. |
'\n'
|
Returns:
Type | Description |
---|---|
str
|
A single string containing all text content, or an empty string if no text parts are found. |
get_text_parts(parts)
¶
Extracts text content from all TextPart objects in a list of Parts.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
parts
|
list[Part]
|
A list of |
required |
Returns:
Type | Description |
---|---|
list[str]
|
A list of strings containing the text content from any |
new_agent_parts_message(parts, context_id=None, task_id=None)
¶
Creates a new agent message containing a list of Parts.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
parts
|
list[Part]
|
The list of |
required |
context_id
|
str | None
|
The context ID for the message. |
None
|
task_id
|
str | None
|
The task ID for the message. |
None
|
Returns:
Type | Description |
---|---|
Message
|
A new |
new_agent_text_message(text, context_id=None, task_id=None)
¶
Creates a new agent message containing a single TextPart.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
text
|
str
|
The text content of the message. |
required |
context_id
|
str | None
|
The context ID for the message. |
None
|
task_id
|
str | None
|
The task ID for the message. |
None
|
Returns:
Type | Description |
---|---|
Message
|
A new |
new_artifact(parts, name, description='')
¶
Creates a new Artifact object.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
parts
|
list[Part]
|
The list of |
required |
name
|
str
|
The human-readable name of the artifact. |
required |
description
|
str
|
An optional description of the artifact. |
''
|
Returns:
Type | Description |
---|---|
Artifact
|
A new |
new_data_artifact(name, data, description='')
¶
Creates a new Artifact object containing only a single DataPart.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name
|
str
|
The human-readable name of the artifact. |
required |
data
|
dict[str, Any]
|
The structured data content of the artifact. |
required |
description
|
str
|
An optional description of the artifact. |
''
|
Returns:
Type | Description |
---|---|
Artifact
|
A new |
new_task(request)
¶
Creates a new Task object from an initial user message.
Generates task and context IDs if not provided in the message.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
Message
|
The initial |
required |
Returns:
Type | Description |
---|---|
Task
|
A new |
Raises:
Type | Description |
---|---|
TypeError
|
If the message role is None. |
ValueError
|
If the message parts are empty, if any part has empty content, or if the provided context_id is invalid. |
new_text_artifact(name, text, description='')
¶
Creates a new Artifact object containing only a single TextPart.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name
|
str
|
The human-readable name of the artifact. |
required |
text
|
str
|
The text content of the artifact. |
required |
description
|
str
|
An optional description of the artifact. |
''
|
Returns:
Type | Description |
---|---|
Artifact
|
A new |
artifact
¶
Utility functions for creating A2A Artifact objects.
new_artifact(parts, name, description='')
¶
Creates a new Artifact object.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
parts
|
list[Part]
|
The list of |
required |
name
|
str
|
The human-readable name of the artifact. |
required |
description
|
str
|
An optional description of the artifact. |
''
|
Returns:
Type | Description |
---|---|
Artifact
|
A new |
new_data_artifact(name, data, description='')
¶
Creates a new Artifact object containing only a single DataPart.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name
|
str
|
The human-readable name of the artifact. |
required |
data
|
dict[str, Any]
|
The structured data content of the artifact. |
required |
description
|
str
|
An optional description of the artifact. |
''
|
Returns:
Type | Description |
---|---|
Artifact
|
A new |
new_text_artifact(name, text, description='')
¶
Creates a new Artifact object containing only a single TextPart.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name
|
str
|
The human-readable name of the artifact. |
required |
text
|
str
|
The text content of the artifact. |
required |
description
|
str
|
An optional description of the artifact. |
''
|
Returns:
Type | Description |
---|---|
Artifact
|
A new |
constants
¶
Constants for well-known URIs used throughout the A2A Python SDK.
error_handlers
¶
errors
¶
Custom exceptions for A2A server-side errors.
A2AServerError
¶
Bases: Exception
Base exception for A2A Server errors.
MethodNotImplementedError
¶
Bases: A2AServerError
Exception raised for methods that are not implemented by the server handler.
__init__(message='This method is not implemented by the server')
¶
Initializes the MethodNotImplementedError.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
message
|
str
|
A descriptive error message. |
'This method is not implemented by the server'
|
ServerError
¶
Bases: Exception
Wrapper exception for A2A or JSON-RPC errors originating from the server's logic.
This exception is used internally by request handlers and other server components to signal a specific error that should be formatted as a JSON-RPC error response.
__init__(error)
¶
Initializes the ServerError.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
error
|
JSONRPCError | JSONParseError | InvalidRequestError | MethodNotFoundError | InvalidParamsError | InternalError | TaskNotFoundError | TaskNotCancelableError | PushNotificationNotSupportedError | UnsupportedOperationError | ContentTypeNotSupportedError | InvalidAgentResponseError | AuthenticatedExtendedCardNotConfiguredError | None
|
The specific A2A or JSON-RPC error model instance.
If None, an |
required |
helpers
¶
General utility functions for the A2A Python SDK.
append_artifact_to_task(task, event)
¶
Helper method for updating a Task object with new artifact data from an event.
Handles creating the artifacts list if it doesn't exist, adding new artifacts,
and appending parts to existing artifacts based on the append
flag in the event.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
task
|
Task
|
The |
required |
event
|
TaskArtifactUpdateEvent
|
The |
required |
are_modalities_compatible(server_output_modes, client_output_modes)
¶
Checks if server and client output modalities (MIME types) are compatible.
Modalities are compatible if: 1. The client specifies no preferred output modes (client_output_modes is None or empty). 2. The server specifies no supported output modes (server_output_modes is None or empty). 3. There is at least one common modality between the server's supported list and the client's preferred list.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
server_output_modes
|
list[str] | None
|
A list of MIME types supported by the server/agent for output. Can be None or empty if the server doesn't specify. |
required |
client_output_modes
|
list[str] | None
|
A list of MIME types preferred by the client for output. Can be None or empty if the client accepts any. |
required |
Returns:
Type | Description |
---|---|
bool
|
True if the modalities are compatible, False otherwise. |
build_text_artifact(text, artifact_id)
¶
Helper to create a text artifact.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
text
|
str
|
The text content for the artifact. |
required |
artifact_id
|
str
|
The ID for the artifact. |
required |
Returns:
Type | Description |
---|---|
Artifact
|
An |
create_task_obj(message_send_params)
¶
Create a new task object from message send params.
Generates UUIDs for task and context IDs if they are not already present in the message.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
message_send_params
|
MessageSendParams
|
The |
required |
Returns:
Type | Description |
---|---|
Task
|
A new |
validate(expression, error_message=None)
¶
Decorator that validates if a given expression evaluates to True.
Typically used on class methods to check capabilities or configuration
before executing the method's logic. If the expression is False,
a ServerError
with an UnsupportedOperationError
is raised.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
expression
|
Callable[[Any], bool]
|
A callable that takes the instance ( |
required |
error_message
|
str | None
|
An optional custom error message for the |
None
|
Examples:
Demonstrating with an async method:
>>> import asyncio
>>> from a2a.utils.errors import ServerError
>>>
>>> class MyAgent:
... def __init__(self, streaming_enabled: bool):
... self.streaming_enabled = streaming_enabled
...
... @validate(
... lambda self: self.streaming_enabled,
... 'Streaming is not enabled for this agent',
... )
... async def stream_response(self, message: str):
... return f'Streaming: {message}'
>>>
>>> async def run_async_test():
... # Successful call
... agent_ok = MyAgent(streaming_enabled=True)
... result = await agent_ok.stream_response('hello')
... print(result)
...
... # Call that fails validation
... agent_fail = MyAgent(streaming_enabled=False)
... try:
... await agent_fail.stream_response('world')
... except ServerError as e:
... print(e.error.message)
>>>
>>> asyncio.run(run_async_test())
Streaming: hello
Streaming is not enabled for this agent
Demonstrating with a sync method:
>>> class SecureAgent:
... def __init__(self):
... self.auth_enabled = False
...
... @validate(
... lambda self: self.auth_enabled,
... 'Authentication must be enabled for this operation',
... )
... def secure_operation(self, data: str):
... return f'Processing secure data: {data}'
>>>
>>> # Error case example
>>> agent = SecureAgent()
>>> try:
... agent.secure_operation('secret')
... except ServerError as e:
... print(e.error.message)
Authentication must be enabled for this operation
Note
This decorator works with both sync and async methods automatically.
validate_async_generator(expression, error_message=None)
¶
Decorator that validates if a given expression evaluates to True for async generators.
Typically used on class methods to check capabilities or configuration
before executing the method's logic. If the expression is False,
a ServerError
with an UnsupportedOperationError
is raised.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
expression
|
Callable[[Any], bool]
|
A callable that takes the instance ( |
required |
error_message
|
str | None
|
An optional custom error message for the |
None
|
Examples:
Streaming capability validation with success case:
>>> import asyncio
>>> from a2a.utils.errors import ServerError
>>>
>>> class StreamingAgent:
... def __init__(self, streaming_enabled: bool):
... self.streaming_enabled = streaming_enabled
...
... @validate_async_generator(
... lambda self: self.streaming_enabled,
... 'Streaming is not supported by this agent',
... )
... async def stream_messages(self, count: int):
... for i in range(count):
... yield f'Message {i}'
>>>
>>> async def run_streaming_test():
... # Successful streaming
... agent = StreamingAgent(streaming_enabled=True)
... async for msg in agent.stream_messages(2):
... print(msg)
>>>
>>> asyncio.run(run_streaming_test())
Message 0
Message 1
Error case - validation fails:
>>> class FeatureAgent:
... def __init__(self):
... self.features = {'real_time': False}
...
... @validate_async_generator(
... lambda self: self.features.get('real_time', False),
... 'Real-time feature must be enabled to stream updates',
... )
... async def real_time_updates(self):
... yield 'This should not be yielded'
>>>
>>> async def run_error_test():
... agent = FeatureAgent()
... try:
... async for _ in agent.real_time_updates():
... pass
... except ServerError as e:
... print(e.error.message)
>>>
>>> asyncio.run(run_error_test())
Real-time feature must be enabled to stream updates
Note
This decorator is specifically for async generator methods (async def with yield). The validation happens before the generator starts yielding values.
message
¶
Utility functions for creating and handling A2A Message objects.
get_data_parts(parts)
¶
Extracts dictionary data from all DataPart objects in a list of Parts.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
parts
|
list[Part]
|
A list of |
required |
Returns:
Type | Description |
---|---|
list[dict[str, Any]]
|
A list of dictionaries containing the data from any |
get_file_parts(parts)
¶
Extracts file data from all FilePart objects in a list of Parts.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
parts
|
list[Part]
|
A list of |
required |
Returns:
Type | Description |
---|---|
list[FileWithBytes | FileWithUri]
|
A list of |
get_message_text(message, delimiter='\n')
¶
Extracts and joins all text content from a Message's parts.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
message
|
Message
|
The |
required |
delimiter
|
str
|
The string to use when joining text from multiple TextParts. |
'\n'
|
Returns:
Type | Description |
---|---|
str
|
A single string containing all text content, or an empty string if no text parts are found. |
get_text_parts(parts)
¶
Extracts text content from all TextPart objects in a list of Parts.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
parts
|
list[Part]
|
A list of |
required |
Returns:
Type | Description |
---|---|
list[str]
|
A list of strings containing the text content from any |
new_agent_parts_message(parts, context_id=None, task_id=None)
¶
Creates a new agent message containing a list of Parts.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
parts
|
list[Part]
|
The list of |
required |
context_id
|
str | None
|
The context ID for the message. |
None
|
task_id
|
str | None
|
The task ID for the message. |
None
|
Returns:
Type | Description |
---|---|
Message
|
A new |
new_agent_text_message(text, context_id=None, task_id=None)
¶
Creates a new agent message containing a single TextPart.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
text
|
str
|
The text content of the message. |
required |
context_id
|
str | None
|
The context ID for the message. |
None
|
task_id
|
str | None
|
The task ID for the message. |
None
|
Returns:
Type | Description |
---|---|
Message
|
A new |
proto_utils
¶
Utils for converting between proto and Python types.
FromProto
¶
Converts proto types to Python types.
ToProto
¶
Converts Python types to proto types.
update_event(event)
classmethod
¶
Converts a task, message, or task update event to a StreamResponse.
dict_to_struct(dictionary)
¶
Converts a Python dict to a Struct proto.
Unfortunately, using json_format.ParseDict
does not work because this
wants the dictionary to be an exact match of the Struct proto with fields
and keys and values, not the traditional Python dict structure.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dictionary
|
dict[str, Any]
|
The Python dict to convert. |
required |
Returns:
Type | Description |
---|---|
Struct
|
The Struct proto. |
task
¶
Utility functions for creating A2A Task objects.
completed_task(task_id, context_id, artifacts, history=None)
¶
Creates a Task object in the 'completed' state.
Useful for constructing a final Task representation when the agent finishes and produces artifacts.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
task_id
|
str
|
The ID of the task. |
required |
context_id
|
str
|
The context ID of the task. |
required |
artifacts
|
list[Artifact]
|
A list of |
required |
history
|
list[Message] | None
|
An optional list of |
None
|
Returns:
Type | Description |
---|---|
Task
|
A |
new_task(request)
¶
Creates a new Task object from an initial user message.
Generates task and context IDs if not provided in the message.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
Message
|
The initial |
required |
Returns:
Type | Description |
---|---|
Task
|
A new |
Raises:
Type | Description |
---|---|
TypeError
|
If the message role is None. |
ValueError
|
If the message parts are empty, if any part has empty content, or if the provided context_id is invalid. |
telemetry
¶
OpenTelemetry Tracing Utilities for A2A Python SDK.
This module provides decorators to simplify the integration of OpenTelemetry
tracing into Python applications. It offers trace_function
for instrumenting
individual functions (both synchronous and asynchronous) and trace_class
for instrumenting multiple methods within a class.
The tracer is initialized with the module name and version defined by
INSTRUMENTING_MODULE_NAME
('a2a-python-sdk') and
INSTRUMENTING_MODULE_VERSION
('1.0.0').
Features:
- Automatic span creation for decorated functions/methods.
- Support for both synchronous and asynchronous functions.
- Default span naming based on module and function/class/method name.
- Customizable span names, kinds, and static attributes.
- Dynamic attribute setting via an attribute_extractor
callback.
- Automatic recording of exceptions and setting of span status.
- Selective method tracing in classes using include/exclude lists.
Usage
For a single function:
from your_module import trace_function
@trace_function
def my_function():
# ...
pass
@trace_function(span_name='custom.op', kind=SpanKind.CLIENT)
async def my_async_function():
# ...
pass
For a class:
trace_class(include_list=None, exclude_list=None, kind=SpanKind.INTERNAL)
¶
A class decorator to automatically trace specified methods of a class.
This decorator iterates over the methods of a class and applies the
trace_function
decorator to them, based on the include_list
and
exclude_list
criteria. Methods starting or ending with double underscores
(dunder methods, e.g., __init__
, __call__
) are always excluded by default.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
include_list
|
list[str]
|
A list of method names to explicitly include for tracing. If provided, only methods in this list (that are not dunder methods) will be traced. Defaults to None (trace all non-dunder methods). |
None
|
exclude_list
|
list[str]
|
A list of method names to exclude
from tracing. This is only considered if |
None
|
kind
|
SpanKind
|
The |
INTERNAL
|
Returns:
Name | Type | Description |
---|---|---|
callable |
Callable
|
A decorator function that, when applied to a class, modifies the class to wrap its specified methods with tracing. |
trace_function(func=None, *, span_name=None, kind=SpanKind.INTERNAL, attributes=None, attribute_extractor=None)
¶
A decorator to automatically trace a function call with OpenTelemetry.
This decorator can be used to wrap both sync and async functions. When applied, it creates a new span for each call to the decorated function. The span will record the execution time, status (OK or ERROR), and any exceptions that occur.
It can be used in two ways:
- As a direct decorator:
@trace_function
- As a decorator factory to provide arguments:
@trace_function(span_name="custom.name")
Parameters:
Name | Type | Description | Default |
---|---|---|---|
func
|
callable
|
The function to be decorated. If None, the decorator returns a partial function, allowing it to be called with arguments. Defaults to None. |
None
|
span_name
|
str
|
Custom name for the span. If None,
it defaults to |
None
|
kind
|
SpanKind
|
The |
INTERNAL
|
attributes
|
dict
|
A dictionary of static attributes to be set on the span. Keys are attribute names (str) and values are the corresponding attribute values. Defaults to None. |
None
|
attribute_extractor
|
callable
|
A function that can be used
to dynamically extract and set attributes on the span.
It is called within a |
None
|
Returns:
Name | Type | Description |
---|---|---|
callable |
Callable
|
The wrapped function that includes tracing, or a partial
decorator if |