a2a

package
v1.3.11 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 9, 2026 License: Apache-2.0 Imports: 26 Imported by: 0

Documentation

Overview

Package a2a provides types for the Agent-to-Agent (A2A) protocol.

Types are derived from the A2A protocol specification (a2a.proto) and use camelCase JSON tags matching the JSON-RPC binding convention.

Index

Constants

View Source
const (
	DefaultA2AMaxRetries   = 3
	DefaultA2AInitialDelay = 500 * time.Millisecond
	DefaultA2AMaxDelay     = 30 * time.Second

	// DefaultClientTTL is the default time-to-live for cached A2A clients.
	// Clients not used within this duration are evicted from the cache.
	DefaultClientTTL = 30 * time.Minute

	// DefaultMaxClients is the default maximum number of cached A2A clients.
	// When exceeded, the least recently used client is evicted.
	DefaultMaxClients = 100
)

Default retry constants for A2A executor.

View Source
const (
	MethodSendMessage          = "message/send"
	MethodSendStreamingMessage = "message/stream"
	MethodGetTask              = "tasks/get"
	MethodCancelTask           = "tasks/cancel"
	MethodListTasks            = "tasks/list"
	MethodTaskSubscribe        = "tasks/subscribe"
)

A2A JSON-RPC method names.

View Source
const (

	// DefaultSSEIdleTimeout is the default idle timeout for SSE streams.
	// If no event is received within this duration, ReadSSE returns an error
	// so callers can reconnect.
	DefaultSSEIdleTimeout = 5 * time.Minute
)

HTTP client defaults for A2A communication.

Variables

View Source
var ErrSSEIdleTimeout = fmt.Errorf("a2a: SSE idle timeout exceeded")

ErrSSEIdleTimeout is returned when an SSE stream has not received any event within the configured idle timeout period.

Functions

func ExtractResponseParts added in v1.3.10

func ExtractResponseParts(task *Task) []types.ContentPart

ExtractResponseParts converts all A2A Parts from a completed task into PromptKit ContentParts. It collects parts from the status message (if present) and all artifacts. Parts that fail conversion (e.g., structured data) are silently skipped.

func ExtractResponseText

func ExtractResponseText(task *Task) string

ExtractResponseText extracts text from a completed A2A task. It checks the status message first, then artifacts.

func InferContentType

func InferContentType(mediaType string) string

InferContentType maps a MIME type to a PromptKit content type string.

func MessageToMessage

func MessageToMessage(msg *Message) (*types.Message, error)

MessageToMessage converts an A2A Message to a PromptKit Message.

func PartToContentPart

func PartToContentPart(part *Part) (types.ContentPart, error)

PartToContentPart converts an A2A Part to a PromptKit ContentPart.

func ReadSSE

func ReadSSE(ctx context.Context, r io.Reader, ch chan<- StreamEvent)

ReadSSE reads SSE events from r and sends parsed StreamEvents to ch. It has no idle timeout; use ReadSSEWithIdleTimeout for timeout support.

func ReadSSEWithIdleTimeout added in v1.3.10

func ReadSSEWithIdleTimeout(ctx context.Context, r io.Reader, ch chan<- StreamEvent, idleTimeout time.Duration)

ReadSSEWithIdleTimeout reads SSE events from r and sends parsed StreamEvents to ch. If idleTimeout is positive and no line is received within that duration, reading stops (callers should reconnect). A zero or negative idleTimeout disables idle detection.

Types

type AgentCapabilities

type AgentCapabilities struct {
	Streaming         bool             `json:"streaming,omitempty"`
	PushNotifications bool             `json:"pushNotifications,omitempty"`
	ExtendedAgentCard bool             `json:"extendedAgentCard,omitempty"`
	Extensions        []AgentExtension `json:"extensions,omitempty"`
}

AgentCapabilities describes what the agent supports.

type AgentCard

type AgentCard struct {
	Name                string            `json:"name"`
	Description         string            `json:"description,omitempty"`
	Version             string            `json:"version,omitempty"`
	Provider            *AgentProvider    `json:"provider,omitempty"`
	Capabilities        AgentCapabilities `json:"capabilities,omitzero"`
	Skills              []AgentSkill      `json:"skills,omitempty"`
	DefaultInputModes   []string          `json:"defaultInputModes,omitempty"`
	DefaultOutputModes  []string          `json:"defaultOutputModes,omitempty"`
	SupportedInterfaces []AgentInterface  `json:"supportedInterfaces,omitempty"`
	IconURL             string            `json:"iconUrl,omitempty"`
	DocumentationURL    string            `json:"documentationUrl,omitempty"`
}

AgentCard describes an agent's capabilities and endpoints.

type AgentExtension

type AgentExtension struct {
	URI         string `json:"uri"`
	Description string `json:"description,omitempty"`
	Required    bool   `json:"required,omitempty"`
}

AgentExtension describes an optional protocol extension.

type AgentInterface

type AgentInterface struct {
	URL             string `json:"url"`
	ProtocolBinding string `json:"protocolBinding,omitempty"`
	ProtocolVersion string `json:"protocolVersion,omitempty"`
}

AgentInterface describes a protocol endpoint.

type AgentProvider

type AgentProvider struct {
	Organization string `json:"organization"`
	URL          string `json:"url,omitempty"`
}

AgentProvider identifies the organization behind an agent.

type AgentSkill

type AgentSkill struct {
	ID          string   `json:"id"`
	Name        string   `json:"name"`
	Description string   `json:"description,omitempty"`
	Tags        []string `json:"tags,omitempty"`
	Examples    []string `json:"examples,omitempty"`
	InputModes  []string `json:"inputModes,omitempty"`
	OutputModes []string `json:"outputModes,omitempty"`
}

AgentSkill describes a specific skill an agent can perform.

type Artifact

type Artifact struct {
	ArtifactID  string         `json:"artifactId"`
	Name        string         `json:"name,omitempty"`
	Description string         `json:"description,omitempty"`
	Parts       []Part         `json:"parts"`
	Extensions  []string       `json:"extensions,omitempty"`
	Metadata    map[string]any `json:"metadata,omitempty"`
}

Artifact is a named output generated by an agent.

func ContentPartsToArtifacts

func ContentPartsToArtifacts(parts []types.ContentPart) ([]Artifact, error)

ContentPartsToArtifacts converts PromptKit ContentParts into A2A Artifacts. It creates a single Artifact containing all non-empty parts. Returns nil if parts is empty or all parts fail to convert.

type CancelTaskRequest

type CancelTaskRequest struct {
	ID string `json:"id"`
}

CancelTaskRequest is the params for tasks/cancel.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is an HTTP client for discovering and calling external A2A agents.

func NewClient

func NewClient(baseURL string, opts ...ClientOption) *Client

NewClient creates a Client targeting baseURL.

func (*Client) CancelTask

func (c *Client) CancelTask(ctx context.Context, taskID string) error

CancelTask cancels a task by ID via tasks/cancel.

func (*Client) Discover

func (c *Client) Discover(ctx context.Context) (*AgentCard, error)

Discover fetches the agent card from /.well-known/agent.json. The card is cached after the first successful call.

func (*Client) GetTask

func (c *Client) GetTask(ctx context.Context, taskID string) (*Task, error)

GetTask retrieves a task by ID via tasks/get.

func (*Client) ListTasks

func (c *Client) ListTasks(ctx context.Context, params *ListTasksRequest) ([]*Task, error)

ListTasks lists tasks via tasks/list.

func (*Client) SendMessage

func (c *Client) SendMessage(ctx context.Context, params *SendMessageRequest) (*Task, error)

SendMessage sends a message/send JSON-RPC request.

func (*Client) SendMessageStream

func (c *Client) SendMessageStream(ctx context.Context, params *SendMessageRequest) (<-chan StreamEvent, error)

SendMessageStream sends a message/stream request and returns a channel of streaming events. The channel is closed when the stream ends or the context is canceled.

type ClientOption

type ClientOption func(*Client)

ClientOption configures a Client.

func WithAuth

func WithAuth(scheme, token string) ClientOption

WithAuth sets the Authorization header on all requests.

func WithHTTPClient

func WithHTTPClient(hc *http.Client) ClientOption

WithHTTPClient sets the underlying HTTP client.

func WithHeaders added in v1.3.11

func WithHeaders(headers map[string]string) ClientOption

WithHeaders sets custom headers that are sent on all requests.

func WithSSEIdleTimeout added in v1.3.10

func WithSSEIdleTimeout(d time.Duration) ClientOption

WithSSEIdleTimeout sets the idle timeout for SSE streams. If no event is received within this duration, the stream is considered stale and ReadSSE returns ErrSSEIdleTimeout so callers can reconnect. A zero or negative value disables the idle timeout.

type Executor

type Executor struct {
	// contains filtered or unexported fields
}

Executor implements tools.Executor and tools.MultimodalExecutor for A2A agent tools. It dispatches tool calls to remote A2A agents via the A2A client. The executor maintains a cache of A2A clients with TTL-based eviction. Call Close when the executor is no longer needed to release resources.

func NewExecutor

func NewExecutor(opts ...ExecutorOption) *Executor

NewExecutor creates a new A2A executor with optional configuration. The executor starts a background goroutine for cache cleanup. Call Close when the executor is no longer needed.

func (*Executor) Close added in v1.3.10

func (e *Executor) Close() error

Close stops the background cleanup goroutine and clears the client cache.

func (*Executor) Execute

func (e *Executor) Execute(
	ctx context.Context, descriptor *tools.ToolDescriptor, args json.RawMessage,
) (json.RawMessage, error)

Execute calls a remote A2A agent with the tool arguments and returns the response.

func (*Executor) ExecuteMultimodal added in v1.3.10

func (e *Executor) ExecuteMultimodal(
	ctx context.Context, descriptor *tools.ToolDescriptor, args json.RawMessage,
) (json.RawMessage, []types.ContentPart, error)

ExecuteMultimodal calls a remote A2A agent and returns both JSON result and multimodal content parts. It implements tools.MultimodalExecutor.

func (*Executor) Name

func (e *Executor) Name() string

Name returns "a2a" to match the Mode on A2A tool descriptors.

type ExecutorOption added in v1.3.10

type ExecutorOption func(*Executor)

ExecutorOption configures an Executor.

func WithClientTTL added in v1.3.10

func WithClientTTL(d time.Duration) ExecutorOption

WithClientTTL sets the time-to-live for cached A2A clients. Clients not used within this duration are evicted from the cache.

func WithMaxClients added in v1.3.10

func WithMaxClients(n int) ExecutorOption

WithMaxClients sets the maximum number of cached A2A clients. When exceeded, the least recently used client is evicted.

func WithNoRetry added in v1.3.10

func WithNoRetry() ExecutorOption

WithNoRetry disables retry for the A2A executor.

func WithRetryPolicy added in v1.3.10

func WithRetryPolicy(policy RetryPolicy) ExecutorOption

WithRetryPolicy sets the retry policy for the A2A executor.

type GetTaskRequest

type GetTaskRequest struct {
	ID            string `json:"id"`
	HistoryLength *int   `json:"historyLength,omitempty"`
}

GetTaskRequest is the params for tasks/get.

type HTTPStatusError added in v1.3.10

type HTTPStatusError struct {
	StatusCode int
	Method     string
}

HTTPStatusError is returned when an A2A HTTP request receives a non-200 status code.

func (*HTTPStatusError) Error added in v1.3.10

func (e *HTTPStatusError) Error() string

type JSONRPCError

type JSONRPCError struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
	Data    any    `json:"data,omitempty"`
}

JSONRPCError is a JSON-RPC 2.0 error object.

type JSONRPCRequest

type JSONRPCRequest struct {
	JSONRPC string          `json:"jsonrpc"`
	ID      any             `json:"id"`
	Method  string          `json:"method"`
	Params  json.RawMessage `json:"params,omitempty"`
}

JSONRPCRequest is a JSON-RPC 2.0 request.

type JSONRPCResponse

type JSONRPCResponse struct {
	JSONRPC string          `json:"jsonrpc"`
	ID      any             `json:"id"`
	Result  json.RawMessage `json:"result,omitempty"`
	Error   *JSONRPCError   `json:"error,omitempty"`
}

JSONRPCResponse is a JSON-RPC 2.0 response.

type ListTasksRequest

type ListTasksRequest struct {
	ContextID     string     `json:"contextId"`
	Status        *TaskState `json:"status,omitempty"`
	PageSize      int        `json:"pageSize,omitempty"`
	PageToken     string     `json:"pageToken,omitempty"`
	HistoryLength *int       `json:"historyLength,omitempty"`
}

ListTasksRequest is the params for tasks/list.

type ListTasksResponse

type ListTasksResponse struct {
	Tasks         []Task `json:"tasks"`
	NextPageToken string `json:"nextPageToken,omitempty"`
	PageSize      int    `json:"pageSize,omitempty"`
	TotalSize     int    `json:"totalSize,omitempty"`
}

ListTasksResponse is the result for tasks/list.

type Message

type Message struct {
	MessageID        string         `json:"messageId"`
	ContextID        string         `json:"contextId,omitempty"`
	TaskID           string         `json:"taskId,omitempty"`
	Role             Role           `json:"role"`
	Parts            []Part         `json:"parts"`
	ReferenceTaskIDs []string       `json:"referenceTaskIds,omitempty"`
	Extensions       []string       `json:"extensions,omitempty"`
	Metadata         map[string]any `json:"metadata,omitempty"`
}

Message is a communication unit in the A2A protocol.

type Part

type Part struct {
	Text *string        `json:"text,omitempty"`
	Raw  []byte         `json:"raw,omitempty"`
	URL  *string        `json:"url,omitempty"`
	Data map[string]any `json:"data,omitempty"`

	Metadata  map[string]any `json:"metadata,omitempty"`
	Filename  string         `json:"filename,omitempty"`
	MediaType string         `json:"mediaType,omitempty"`
}

Part represents a piece of content within a message or artifact. Exactly one of Text, Raw, URL, or Data should be set.

func ContentPartToA2APart

func ContentPartToA2APart(part types.ContentPart) (Part, error)

ContentPartToA2APart converts a PromptKit ContentPart to an A2A Part.

type RPCError

type RPCError struct {
	Code    int
	Message string
}

RPCError represents a JSON-RPC error returned by an A2A agent.

func (*RPCError) Error

func (e *RPCError) Error() string

type RetryPolicy added in v1.3.10

type RetryPolicy struct {
	MaxRetries   int
	InitialDelay time.Duration
	MaxDelay     time.Duration
}

RetryPolicy configures retry behavior for the A2A executor.

func DefaultRetryPolicy added in v1.3.10

func DefaultRetryPolicy() RetryPolicy

DefaultRetryPolicy returns the default retry policy for A2A calls.

type Role

type Role string

Role identifies the sender of a message.

const (
	RoleUser  Role = "user"
	RoleAgent Role = "agent"
)

Role constants for message senders.

type SendMessageConfiguration

type SendMessageConfiguration struct {
	AcceptedOutputModes []string `json:"acceptedOutputModes,omitempty"`
	HistoryLength       *int     `json:"historyLength,omitempty"`
	Blocking            bool     `json:"blocking,omitempty"`
}

SendMessageConfiguration controls message handling.

type SendMessageRequest

type SendMessageRequest struct {
	Message       Message                   `json:"message"`
	Configuration *SendMessageConfiguration `json:"configuration,omitempty"`
	Metadata      map[string]any            `json:"metadata,omitempty"`
}

SendMessageRequest is the params for message/send and message/stream.

type StreamEvent

type StreamEvent struct {
	StatusUpdate   *TaskStatusUpdateEvent
	ArtifactUpdate *TaskArtifactUpdateEvent
}

StreamEvent represents a single event received during message streaming. Exactly one field will be non-nil.

type SubscribeTaskRequest

type SubscribeTaskRequest struct {
	ID string `json:"id"`
}

SubscribeTaskRequest is the params for tasks/subscribe.

type Task

type Task struct {
	ID        string         `json:"id"`
	ContextID string         `json:"contextId"`
	Status    TaskStatus     `json:"status"`
	Artifacts []Artifact     `json:"artifacts,omitempty"`
	History   []Message      `json:"history,omitempty"`
	Metadata  map[string]any `json:"metadata,omitempty"`
}

Task is the top-level unit of work in the A2A protocol.

type TaskArtifactUpdateEvent

type TaskArtifactUpdateEvent struct {
	TaskID    string         `json:"taskId"`
	ContextID string         `json:"contextId"`
	Artifact  Artifact       `json:"artifact"`
	Append    bool           `json:"append,omitempty"`
	LastChunk bool           `json:"lastChunk,omitempty"`
	Metadata  map[string]any `json:"metadata,omitempty"`
}

TaskArtifactUpdateEvent is sent during streaming when an artifact is produced.

type TaskState

type TaskState string

TaskState represents the state of an A2A task.

const (
	TaskStateSubmitted     TaskState = "submitted"
	TaskStateWorking       TaskState = "working"
	TaskStateCompleted     TaskState = "completed"
	TaskStateFailed        TaskState = "failed"
	TaskStateCanceled      TaskState = "canceled"
	TaskStateInputRequired TaskState = "input_required"
	TaskStateRejected      TaskState = "rejected"
	TaskStateAuthRequired  TaskState = "auth_required"
)

TaskState constants for the A2A protocol.

func (TaskState) MarshalJSON

func (s TaskState) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (*TaskState) UnmarshalJSON

func (s *TaskState) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

type TaskStatus

type TaskStatus struct {
	State     TaskState  `json:"state"`
	Message   *Message   `json:"message,omitempty"`
	Timestamp *time.Time `json:"timestamp,omitempty"`
}

TaskStatus describes the current status of a task.

type TaskStatusUpdateEvent

type TaskStatusUpdateEvent struct {
	TaskID    string         `json:"taskId"`
	ContextID string         `json:"contextId"`
	Status    TaskStatus     `json:"status"`
	Metadata  map[string]any `json:"metadata,omitempty"`
}

TaskStatusUpdateEvent is sent during streaming when a task's status changes.

type ToolBridge

type ToolBridge struct {
	// contains filtered or unexported fields
}

ToolBridge discovers an A2A agent and creates ToolDescriptor entries for each of the agent's skills so they can be invoked through the standard tool registry.

func NewToolBridge

func NewToolBridge(client *Client) *ToolBridge

NewToolBridge creates a ToolBridge backed by the given A2A client.

func NewToolBridgeWithConfig added in v1.3.11

func NewToolBridgeWithConfig(client *Client, cfg *tools.A2AConfig) *ToolBridge

NewToolBridgeWithConfig creates a ToolBridge that applies the given A2AConfig (headers, auth, retry, skill filter) to all generated tool descriptors.

func (*ToolBridge) GetToolDescriptors

func (b *ToolBridge) GetToolDescriptors() []*tools.ToolDescriptor

GetToolDescriptors returns all tool descriptors accumulated via RegisterAgent calls.

func (*ToolBridge) RegisterAgent

func (b *ToolBridge) RegisterAgent(ctx context.Context) ([]*tools.ToolDescriptor, error)

RegisterAgent discovers the agent card and creates a ToolDescriptor for each skill. The descriptors are appended to the bridge's internal list (supporting multi-agent composition via GetToolDescriptors). Skills excluded by the skill filter are skipped.

Directories

Path Synopsis
Package mock provides a configurable mock A2A server for use in tests.
Package mock provides a configurable mock A2A server for use in tests.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL