protocol

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Jul 22, 2025 License: MIT Imports: 13 Imported by: 0

Documentation

Overview

Package protocol A2A Agent Card. Current version: 0.2.2

Index

Constants

View Source
const (
	// -32700: Invalid JSON payload
	ErrCodeParseError = -32700

	// -32600: Invalid JSON-RPC Request
	ErrCodeInvalidRequest = -32600

	// -32601: Method not found
	ErrCodeMethodNotFound = -32601

	// -32602: Invalid method parameters
	ErrCodeInvalidParams = -32602

	// -32603: Internal server error
	ErrCodeInternalError = -32603

	// -32000 to -32099: Reserved for server-defined errors (A2A-specific)
	ErrCodeServerErrorStart = -32099
	ErrCodeServerErrorEnd   = -32000
)

JSON-RPC 2.0 standard error codes (per A2A specification)

Variables

This section is empty.

Functions

func FreePort

func FreePort() (port int, err error)

FreePort finds a free TCP port on the localhost.

Types

type AgentCapabilities

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

AgentCapabilities defines the capabilities of the agent as per the A2A specification.

type AgentCard

type AgentCard struct {
	Name                              string                `json:"name"`
	Description                       string                `json:"description"`
	URL                               string                `json:"url"`
	IconURL                           *string               `json:"iconUrl,omitempty"`
	Provider                          *AgentProvider        `json:"provider,omitempty"`
	Version                           string                `json:"version"`
	DocumentationURL                  *string               `json:"documentationUrl,omitempty"`
	Capabilities                      AgentCapabilities     `json:"capabilities"`
	SecuritySchemes                   map[string]string     `json:"securitySchemes,omitempty"`
	Security                          []map[string][]string `json:"security,omitempty"`
	DefaultInputModes                 []string              `json:"defaultInputModes"`
	DefaultOutputModes                []string              `json:"defaultOutputModes"`
	Skills                            []AgentSkill          `json:"skills"`
	SupportsAuthenticatedExtendedCard *bool                 `json:"supportsAuthenticatedExtendedCard,omitempty"`
}

AgentCard represents the A2A Agent Card as defined in the A2A specification. SecurityScheme isn't implemented yet, but should be defined as per the A2A spec. Check docs for it: https://google-a2a.github.io/A2A/latest/specification/#553-securityscheme-object

type AgentExtension

type AgentExtension struct {
	URI         string         `json:"uri"`
	Description *string        `json:"description,omitempty"`
	Required    *bool          `json:"required,omitempty"`
	Params      map[string]any `json:"params,omitempty"`
}

AgentExtension represents an extension that can be used by the agent.

type AgentProvider

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

AgentProvider represents the organization and URL of the agent provider.

type AgentSkill

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

AgentSkill represents a skill that the agent can perform.

type Artifact

type Artifact struct {
	ArtifactID  string           `json:"artifactId"`            // Required: unique identifier
	Name        *string          `json:"name,omitempty"`        // Optional: human-readable name
	Description *string          `json:"description,omitempty"` // Optional: human-readable description
	Parts       []map[string]any `json:"parts"`                 // Required: parts (can be refined later)
	Metadata    map[string]any   `json:"metadata,omitempty"`    // Optional: extension metadata
	Extensions  []string         `json:"extensions,omitempty"`  // Optional: contributed extension URIs
}

Artifact represents an object with various attributes and metadata.

type CardBuilder added in v0.2.0

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

CardBuilder is a builder for constructing AgentCard objects.

func Card

func Card() *CardBuilder

Card creates and returns a new cardBuilder with default AgentCard values.

func (*CardBuilder) Build added in v0.2.0

func (b *CardBuilder) Build() *AgentCard

Build returns the constructed AgentCard.

func (*CardBuilder) Capabilities added in v0.2.0

func (b *CardBuilder) Capabilities(capabilities AgentCapabilities) *CardBuilder

Capabilities sets the agent's declared capabilities.

func (*CardBuilder) DefaultInputModes added in v0.2.0

func (b *CardBuilder) DefaultInputModes(modes []string) *CardBuilder

DefaultInputModes sets the default input modes supported by the agent.

func (*CardBuilder) DefaultOutputModes added in v0.2.0

func (b *CardBuilder) DefaultOutputModes(modes []string) *CardBuilder

DefaultOutputModes sets the default output modes supported by the agent.

func (*CardBuilder) Description added in v0.2.0

func (b *CardBuilder) Description(desc string) *CardBuilder

Description sets the description of the agent card.

func (*CardBuilder) DocumentationURL added in v0.2.0

func (b *CardBuilder) DocumentationURL(url string) *CardBuilder

DocumentationURL sets the optional documentation URL for the agent.

func (*CardBuilder) Name added in v0.2.0

func (b *CardBuilder) Name(name string) *CardBuilder

Name sets the name of the agent card.

func (*CardBuilder) Provider added in v0.2.0

func (b *CardBuilder) Provider(provider AgentProvider) *CardBuilder

Provider sets the provider information of the agent.

func (*CardBuilder) Skill added in v0.2.0

func (b *CardBuilder) Skill(_, name, description string) *CardBuilder

Skill appends a single skill to the agent's skill list.

func (*CardBuilder) Skills added in v0.2.0

func (b *CardBuilder) Skills(skills []AgentSkill) *CardBuilder

Skills sets the list of skills for the agent.

func (*CardBuilder) URL added in v0.2.0

func (b *CardBuilder) URL(url string) *CardBuilder

URL sets the URL of the agent.

func (*CardBuilder) Version added in v0.2.0

func (b *CardBuilder) Version(version string) *CardBuilder

Version sets the version string of the agent.

type Client

type Client interface {
	SendMessage(question MessageSendParams) (*JSONRPCResponse, error)
	StreamMessage()
	GetTask()
	CancelTask()
}

Client represents the interface for a protocol client.

type CustomClient

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

CustomClient represents a client for interacting with a custom API.

func NewCustomClient

func NewCustomClient(url string) *CustomClient

NewCustomClient creates a new instance of CustomClient with a specified URL.

func (*CustomClient) CancelTask

func (c *CustomClient) CancelTask()

CancelTask is a placeholder for canceling a task.

func (*CustomClient) GetTask

func (c *CustomClient) GetTask()

GetTask is a placeholder for retrieving a task.

func (*CustomClient) SendMessage

func (c *CustomClient) SendMessage(params MessageSendParams) (*JSONRPCResponse, error)

SendMessage sends a message using the custom API and returns the JSON-RPC response.

func (*CustomClient) StreamMessage

func (c *CustomClient) StreamMessage()

StreamMessage is a placeholder for streaming a message.

type DataPart

type DataPart struct {
	Kind PartKind       `json:"kind"` // Must be "data"
	Data map[string]any `json:"data"` // Required structured content
}

DataPart represents a data part in a message.

func (*DataPart) PartKind

func (p *DataPart) PartKind() PartKind

PartKind returns the kind of the part.

type FilePart

type FilePart struct {
	Kind PartKind `json:"kind"` // Must be "file"
	File any      `json:"file"` // Can be FileWithBytes or FileWithUri
}

FilePart represents a file part in a message.

func NewFileBytes

func NewFileBytes(data []byte) *FilePart

NewFileBytes creates a new FilePart with file content as bytes.

func NewFileURI

func NewFileURI(uri string) *FilePart

NewFileURI creates a new FilePart with a file URI.

func (*FilePart) PartKind

func (p *FilePart) PartKind() PartKind

PartKind returns the kind of the part.

func (*FilePart) UnmarshalJSON

func (p *FilePart) UnmarshalJSON(data []byte) error

UnmarshalJSON unmarshals a JSON representation of FilePart, detecting its file type.

type FileWithBytes

type FileWithBytes struct {
	Bytes string `json:"bytes"` // Required: base64-encoded content
}

FileWithBytes represents a file with its content encoded in base64.

type FileWithURI

type FileWithURI struct {
	URI string `json:"uri"` // Required: URI to the file
}

FileWithURI represents a file referenced by its URI.

type Handler added in v0.2.0

type Handler func(next Handler, r *JSONRPCRequest) (*JSONRPCResponse, error)

Handler handles all incoming requests on JSONRPC level

type JSONRPCError

type JSONRPCError struct {
	Code    int    `json:"code"`           // Error code indicating the type of error
	Message string `json:"message"`        // Short description of the error
	Data    any    `json:"data,omitempty"` // Optional additional information (any type)
}

JSONRPCError represents an error in a JSON-RPC response.

type JSONRPCRequest

type JSONRPCRequest struct {
	JSONRPC string `json:"jsonrpc"`          // MUST be "2.0"
	Method  string `json:"method"`           // e.g., "message/send"
	Params  any    `json:"params,omitempty"` // Can be any structured value (typically an object)
	ID      any    `json:"id,omitempty"`     // string, number (int), or nil
}

JSONRPCRequest represents a request in the JSON-RPC protocol.

type JSONRPCResponse

type JSONRPCResponse struct {
	JSONRPC string        `json:"jsonrpc"`          // MUST be "2.0"
	ID      any           `json:"id"`               // Same type as in request (string, int, or null)
	Result  any           `json:"result,omitempty"` // Present only on success
	Error   *JSONRPCError `json:"error,omitempty"`  // Present only on failure
}

JSONRPCResponse represents a response to a JSON-RPC request.

func (*JSONRPCResponse) UnmarshalJSON

func (r *JSONRPCResponse) UnmarshalJSON(data []byte) error

UnmarshalJSON implements custom unmarshalling for JSON-RPC responses.

type Kind

type Kind string

Kind represents the type of a protocol entity, such as a task or a message.

const (
	// KindTask represents a task entity.
	KindTask Kind = "task"

	// KindMessage represents a message entity.
	KindMessage Kind = "message"
)

type Message

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

Message represents a communication unit between a user and an agent.

type MessageBuilder

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

MessageBuilder provides a fluent API for constructing Message objects.

func NewMessageBuilder

func NewMessageBuilder() *MessageBuilder

NewMessageBuilder creates and returns a new MessageBuilder instance.

func (*MessageBuilder) Build

func (b *MessageBuilder) Build() *Message

Build finalizes and returns the constructed Message.

func (*MessageBuilder) ContextID

func (b *MessageBuilder) ContextID(contextID string) *MessageBuilder

ContextID sets the optional context ID associated with the message.

func (*MessageBuilder) Extensions

func (b *MessageBuilder) Extensions(ext ...string) *MessageBuilder

Extensions appends one or more extension URIs to the message.

func (*MessageBuilder) MessageID

func (b *MessageBuilder) MessageID(id string) *MessageBuilder

MessageID sets the unique identifier for the message.

func (*MessageBuilder) MetadataField

func (b *MessageBuilder) MetadataField(key string, value any) *MessageBuilder

MetadataField sets a key-value pair in the message metadata.

func (*MessageBuilder) Part

func (b *MessageBuilder) Part(part Part) *MessageBuilder

Part appends a message part to the message content.

func (*MessageBuilder) ReferenceTaskIDs

func (b *MessageBuilder) ReferenceTaskIDs(ids ...string) *MessageBuilder

ReferenceTaskIDs appends one or more task IDs to the reference list.

func (*MessageBuilder) Role

func (b *MessageBuilder) Role(role string) *MessageBuilder

Role sets the role of the message sender (e.g., "user" or "agent").

func (*MessageBuilder) TaskID

func (b *MessageBuilder) TaskID(taskID string) *MessageBuilder

TaskID sets the optional task ID associated with the message.

type MessageSendConfiguration

type MessageSendConfiguration struct {
	AcceptedOutputModes    []string                `json:"acceptedOutputModes"`              // Required
	HistoryLength          *int                    `json:"historyLength,omitempty"`          // Optional
	PushNotificationConfig *PushNotificationConfig `json:"pushNotificationConfig,omitempty"` // Optional
	Blocking               *bool                   `json:"blocking,omitempty"`               // Optional
}

MessageSendConfiguration defines the configuration for sending a message.

type MessageSendParams

type MessageSendParams struct {
	Message       *Message                  `json:"message"`                 // Required
	Configuration *MessageSendConfiguration `json:"configuration,omitempty"` // Optional
	Metadata      map[string]any            `json:"metadata,omitempty"`      // Optional key-value extension metadata
}

MessageSendParams defines the parameters for sending a message to an agent.

type MessageSendParamsBuilder

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

MessageSendParamsBuilder defines a builder for constructing MessageSendParams.

func NewMessageSendParamsBuilder

func NewMessageSendParamsBuilder() *MessageSendParamsBuilder

NewMessageSendParamsBuilder creates a new instance of MessageSendParamsBuilder.

func (*MessageSendParamsBuilder) Build

Build constructs the MessageSendParams from the builder.

func (*MessageSendParamsBuilder) Configuration

Configuration sets the configuration for sending the message in the MessageSendParamsBuilder.

func (*MessageSendParamsBuilder) Message

Message sets the message to be sent in the MessageSendParamsBuilder.

func (*MessageSendParamsBuilder) Metadata

Metadata sets the metadata for the message in the MessageSendParamsBuilder.

type MsgHandler added in v0.2.0

type MsgHandler func(message *Message) (*Message, error)

MsgHandler handles messages received from the A2A server on Message level

type Part

type Part interface {
	PartKind() PartKind
}

Part is an interface that defines the common behavior for all parts in a message.

type PartKind

type PartKind string

PartKind represents the type of a part in a message.

const (
	// PartKindText represents a text part.
	PartKindText PartKind = "text"

	// PartKindFile represents a file part.
	PartKindFile PartKind = "file"

	// PartKindData represents a data part.
	PartKindData PartKind = "data"
)

type Parts

type Parts []Part

Parts represents a collection of Part interfaces.

func (*Parts) UnmarshalJSON

func (p *Parts) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface for Parts.

type PushNotificationAuthenticationInfo

type PushNotificationAuthenticationInfo struct {
	Schemes     []string `json:"schemes"`
	Credentials *string  `json:"credentials,omitempty"`
}

PushNotificationAuthenticationInfo provides authentication details used in push notification requests.

type PushNotificationConfig

type PushNotificationConfig struct {
	ID             *string                             `json:"id,omitempty"`
	URL            string                              `json:"url"`
	Token          *string                             `json:"token,omitempty"`
	Authentication *PushNotificationAuthenticationInfo `json:"authentication,omitempty"`
}

PushNotificationConfig defines configuration for sending push notifications to an external URL.

type Server

type Server interface {
	// Start starts the server and listens on the specified port, while signaling readiness.
	Start(ready chan<- struct{}) error

	// MsgHandler sets the message handler for the server.
	MsgHandler(handler MsgHandler)

	// Handler sets the handler function for processing requests.
	Handler(handler Handler)

	// Close stops the server gracefully.
	Close() error
}

Server defines the interface for a server that can handle incoming A2A messages

func NewCustomServer

func NewCustomServer(card *AgentCard, port int) Server

NewCustomServer creates a new instance of a custom server that handles A2A requests

func NewTrpcServer

func NewTrpcServer(card *AgentCard, port int) (Server, error)

NewTrpcServer is an interface for a TRPC server that handles A2A communication.

type Task

type Task struct {
	ID        string         `json:"id"`                  // Required: task ID
	ContextID string         `json:"contextId"`           // Required: contextual alignment
	Status    TaskStatus     `json:"status"`              // Required: current status
	History   []Message      `json:"history,omitempty"`   // Optional: message history
	Artifacts []Artifact     `json:"artifacts,omitempty"` // Optional: artifacts created
	Metadata  map[string]any `json:"metadata,omitempty"`  // Optional: extension metadata
	Kind      Kind           `json:"kind"`                // Required: must be "task"
}

Task represents a task in the A2A protocol.

type TaskPushNotificationConfig

type TaskPushNotificationConfig struct {
	TaskID                 string                 `json:"taskId"`
	PushNotificationConfig PushNotificationConfig `json:"pushNotificationConfig"`
}

TaskPushNotificationConfig links a task with its push notification configuration.

type TaskState

type TaskState string

TaskState represents the lifecycle state of a task.

const (
	// TaskStateSubmitted indicates the task was received by the server and acknowledged,
	// but processing has not yet started.
	TaskStateSubmitted TaskState = "submitted"

	// TaskStateWorking indicates the task is actively being processed by the agent.
	// The client may expect further updates or a terminal state.
	TaskStateWorking TaskState = "working"

	// TaskStateInputRequired indicates the agent requires additional input from the client
	// or user to proceed. The task is effectively paused.
	TaskStateInputRequired TaskState = "input-required"

	// TaskStateCompleted indicates the task finished successfully.
	// Results are typically available in Task.artifacts or TaskStatus.message.
	TaskStateCompleted TaskState = "completed"

	// TaskStateCanceled indicates the task was canceled, for example by a tasks/cancel request
	// or a server-side policy.
	TaskStateCanceled TaskState = "canceled"

	// TaskStateFailed indicates the task terminated due to an error during processing.
	// TaskStatus.message may contain error details.
	TaskStateFailed TaskState = "failed"

	// TaskStateRejected indicates the task was rejected by the remote agent.
	// TaskStatus.message may contain error details.
	TaskStateRejected TaskState = "rejected"

	// TaskStateAuthRequired indicates the agent requires additional authentication to proceed.
	// The task is effectively paused.
	TaskStateAuthRequired TaskState = "auth-required"

	// TaskStateUnknown indicates the state of the task cannot be determined.
	// This may occur if the task ID is invalid, unknown, or expired.
	TaskStateUnknown TaskState = "unknown"
)

type TaskStatus

type TaskStatus struct {
	State     TaskState `json:"state"`               // Required
	Message   *Message  `json:"message,omitempty"`   // Optional: additional status message
	Timestamp *string   `json:"timestamp,omitempty"` // Optional: ISO 8601 datetime string
}

TaskStatus represents the state of a task in the A2A protocol.

type TextPart

type TextPart struct {
	Kind PartKind `json:"kind"` // Must be "text"
	Text string   `json:"text"` // Required text content
}

TextPart represents a text part in a message.

func NewText

func NewText(text string) *TextPart

NewText creates a new TextPart with the given text.

func (*TextPart) PartKind

func (p *TextPart) PartKind() PartKind

PartKind returns the kind of the part.

Jump to

Keyboard shortcuts

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