a2a

package
v1.1.2 Latest Latest
Warning

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

Go to latest
Published: Aug 7, 2026 License: Apache-2.0 Imports: 21 Imported by: 0

Documentation

Overview

Package a2a exposes an adaptor Runner as an A2A-compatible agent.

Scope:

  • converts a host-supplied Agent Card to the official A2A model
  • exposes HTTP handlers that hosts can mount wherever they serve A2A
  • maps SendMessage and SendStreamingMessage onto Runner.Stream
  • maps Event, Result, and Cancel onto Task status/artifact updates

The bridge is intentionally Driver-agnostic: it depends only on the core Runner and Stream contracts and never imports concrete Driver packages. It uses github.com/a2aproject/a2a-go/v2/a2asrv for protocol handling; hosts remain responsible for HTTP routing, auth middleware, TLS, tenancy, and durability.

Inbound prompt extraction defaults to the last non-empty text part. Hosts can provide a PromptBuilder to support domain-specific message, file, or data-part projection without changing the SDK core.

Index

Constants

View Source
const (
	// AdapterStreamSchemaV1 identifies the versioned adaptor Event A2A DataPart
	// wire schema. Its V1 suffix denotes the wire version.
	AdapterStreamSchemaV1 = "adapter.stream.v1"
	// AdapterStreamExtensionURI identifies the Agent Card extension that
	// advertises adapter.stream.v1 status DataParts.
	AdapterStreamExtensionURI = "urn:agent-adaptor:stream:v1"
)
View Source
const (
	// DefaultEphemeralTaskLimit is the maximum number of tasks retained by the
	// default in-memory task store.
	DefaultEphemeralTaskLimit = 256
	// DefaultEphemeralTaskTTL is the retention period used by the default
	// in-memory task store.
	DefaultEphemeralTaskTTL = time.Hour
)
View Source
const (
	// ArtifactAgentAdaptorResult is the bridge-owned A2A artifact name used
	// for the terminal structured SDK result summary and opt-in diagnostics.
	ArtifactAgentAdaptorResult = "agent-adaptor-result"
)

Variables

This section is empty.

Functions

func DecodeAdapterEventV1

func DecodeAdapterEventV1(data any) (decoded adaptor.Event, matched bool, err error)

DecodeAdapterEventV1 restores one adapter.stream.v1 DataPart as the public Event vocabulary, including EventMeta, complete tool snapshots, approval request fields, and detailed Dropped markers. A false matched result means the value belongs to another DataPart schema. Its V1 suffix is intentional because it selects the versioned wire schema.

Types

type AdapterEventMetaV1

type AdapterEventMetaV1 struct {
	// RunID is the adaptor-assigned run identifier.
	RunID string `json:"run_id,omitempty"`
	// ThreadKey is the host-visible adaptor Thread key.
	ThreadKey string `json:"thread_key,omitempty"`
	// Sequence is the adaptor-assigned receive-order sequence.
	Sequence uint64 `json:"sequence,omitempty"`
	// Time is the adaptor event time formatted as RFC 3339 with nanoseconds.
	Time string `json:"time,omitempty"`
	// TurnID identifies the provider turn when available.
	TurnID string `json:"turn_id,omitempty"`
	// Source contains provider-reported coordinates when metadata exposure is
	// enabled.
	Source *AdapterEventSourceMetaV1 `json:"source,omitempty"`
}

AdapterEventMetaV1 is the versioned wire form of adaptor.EventMeta. Its V1 suffix is intentional. Flat identity fields remain part of the v1 wire contract; Meta adds the host Thread key and, when exposure allows it, provider-source coordinates without making either compete with the adaptor envelope.

type AdapterEventSourceMetaV1

type AdapterEventSourceMetaV1 struct {
	// RunID is the provider-reported run identifier.
	RunID string `json:"run_id,omitempty"`
	// ThreadID is the provider-reported thread identifier.
	ThreadID string `json:"thread_id,omitempty"`
	// TurnID is the provider-reported turn identifier.
	TurnID string `json:"turn_id,omitempty"`
	// Sequence is the provider-reported sequence.
	Sequence uint64 `json:"sequence,omitempty"`
	// Timestamp is the provider-reported time formatted as RFC 3339 with
	// nanoseconds.
	Timestamp string `json:"timestamp,omitempty"`
}

AdapterEventSourceMetaV1 is the versioned opt-in provider envelope nested under the adaptor-owned AdapterEventMetaV1 coordinates. Its V1 suffix is intentional.

type AdapterStreamEnvelopeV1

type AdapterStreamEnvelopeV1 struct {
	// Schema is always [AdapterStreamSchemaV1].
	Schema string `json:"schema"`
	// Event contains one projected adaptor Event.
	Event AdapterStreamEventV1 `json:"event"`
}

AdapterStreamEnvelopeV1 is the stable, versioned wire envelope used in StatusUpdate DataParts. Its V1 suffix is intentional.

type AdapterStreamEventV1

type AdapterStreamEventV1 struct {
	// Kind identifies the event shape, such as text.content, tool_call.result,
	// hitl.requested, or stream.dropped.
	Kind string `json:"kind"`
	// Sequence is the flattened event sequence retained for v1 wire
	// compatibility.
	Sequence uint64 `json:"sequence,omitempty"`
	// RunID is the flattened run identifier retained for v1 wire compatibility.
	RunID string `json:"run_id,omitempty"`
	// ThreadID is the flattened thread coordinate retained for v1 wire
	// compatibility. It prefers the host Thread key and otherwise carries the
	// provider lifecycle thread identifier.
	ThreadID string `json:"thread_id,omitempty"`
	// TurnID identifies the provider turn, when reported.
	TurnID string `json:"turn_id,omitempty"`
	// MessageID identifies a text or reasoning message.
	MessageID string `json:"message_id,omitempty"`
	// ToolCallID identifies a tool call or approval-associated tool call.
	ToolCallID string `json:"tool_call_id,omitempty"`
	// Name is the tool name for tool-call events.
	Name string `json:"name,omitempty"`
	// Delta contains incremental text or tool arguments.
	Delta string `json:"delta,omitempty"`
	// Args contains a complete structured tool argument snapshot when available.
	Args map[string]any `json:"args,omitempty"`
	// Result contains a structured tool result snapshot when available.
	Result map[string]any `json:"result,omitempty"`
	// Role identifies the text message role.
	Role string `json:"role,omitempty"`
	// Timestamp is the flattened RFC 3339 event time retained for v1 wire
	// compatibility.
	Timestamp string `json:"timestamp,omitempty"`
	// HITL contains the approval request or resolution payload.
	HITL map[string]any `json:"hitl,omitempty"`
	// Raw contains event-specific diagnostic fields, including Dropped details.
	Raw map[string]any `json:"raw,omitempty"`
	// Meta is the adaptor-owned event metadata envelope.
	Meta *AdapterEventMetaV1 `json:"meta,omitempty"`
}

AdapterStreamEventV1 is the stable versioned wire DTO decoded into adaptor.Event. Its V1 suffix is intentional.

type AgentCard

type AgentCard struct {
	// Name is the human-readable agent name.
	Name string
	// Description explains the agent's purpose and supported use cases.
	Description string
	// URL is the default JSON-RPC endpoint and the fallback URL for interface
	// entries whose URL is empty.
	URL string
	// Version identifies the implementation version advertised by the agent.
	Version string
	// DocumentationURL points callers to human-readable agent documentation.
	DocumentationURL string
	// IconURL points callers to an icon representing the agent.
	IconURL string
	// Provider identifies the organization operating the agent, when known.
	Provider *Provider
	// Capabilities declares optional protocol behavior and extensions.
	Capabilities Capabilities
	// DefaultInputModes lists accepted media types. An empty slice defaults to
	// text/plain.
	DefaultInputModes []string
	// DefaultOutputModes lists produced media types. An empty slice defaults to
	// text/plain.
	DefaultOutputModes []string
	// Skills advertises the agent's supported tasks.
	Skills []Skill
	// Interfaces lists supported protocol endpoints. When empty, URL is exposed
	// as a single JSON-RPC interface.
	Interfaces []AgentInterface
	// SecuritySchemes declares named authentication schemes referenced by
	// Security.
	SecuritySchemes []SecurityScheme
	// Security lists alternative authentication requirements. Schemes within
	// one requirement are all required; separate entries are alternatives.
	Security []SecurityRequirement
}

AgentCard describes the public A2A identity and capabilities exposed by a Server. Name and Version are required. URL is required unless Interfaces contains at least one entry.

type AgentInterface

type AgentInterface struct {
	// URL is the endpoint for this interface. An empty value falls back to
	// AgentCard.URL.
	URL string
	// ProtocolBinding is the A2A transport protocol identifier. An empty value
	// defaults to JSON-RPC.
	ProtocolBinding string
	// Tenant identifies a tenant-specific endpoint, when applicable.
	Tenant string
	// ProtocolVersion overrides the A2A protocol version for this interface.
	ProtocolVersion string
}

AgentInterface describes one protocol endpoint advertised by the Agent Card.

type ArtifactSpec

type ArtifactSpec struct {
	// ID is the artifact identifier. When empty, Name is used; at least one of
	// ID and Name must be non-empty.
	ID string
	// Name is the artifact's machine-readable name.
	Name string
	// Description explains the artifact to callers.
	Description string
	// Parts contains the artifact content in source order.
	Parts []Part
	// Extensions contains extension URIs used by the artifact.
	Extensions []string
	// Metadata contains artifact-level A2A metadata.
	Metadata map[string]any
}

ArtifactSpec describes one terminal A2A artifact emitted by ResultBuilder. It reuses the bridge's stable Part projection so hosts can define TextPart/DataPart/URLPart payloads without depending on upstream proto types.

type BuiltResult

type BuiltResult struct {
	// StatusText overrides the final completed status message. Nil preserves
	// Result.Text; a pointer to an empty string deliberately emits empty text.
	StatusText *string
	// ReplaceDefaultArtifacts suppresses the bridge-owned terminal artifact.
	ReplaceDefaultArtifacts bool
	// Artifacts contains custom terminal artifacts in emission order.
	Artifacts []ArtifactSpec
}

BuiltResult is the terminal A2A projection returned by ResultBuilder.

When ReplaceDefaultArtifacts is false, Artifacts are appended after the bridge-owned terminal defaults (`agent-adaptor-result`). When true, only the custom terminal Artifacts are emitted. Streamed artifacts may already have been emitted before ResultBuilder runs and are not affected by this setting.

StatusText, when non-nil, overrides the final completed status message text. A nil value preserves the bridge's default Result.Text behavior.

type Capabilities

type Capabilities struct {
	// Streaming controls SendStreamingMessage support.
	Streaming CapabilityMode
	// PushNotifications advertises push-notification support. Enabling it
	// requires matching [PushNotificationSupport] in [ServerOptions].
	PushNotifications bool
	// ExtendedAgentCard advertises the authenticated extended-card endpoint.
	// Enabling it requires matching [ExtendedAgentCardSupport] in
	// [ServerOptions].
	ExtendedAgentCard bool
	// Extensions declares additional protocol extensions. NewServer always
	// appends the bridge's adapter.stream.v1 extension.
	Extensions []Extension
}

Capabilities declares the optional A2A features advertised by an agent. Streaming defaults to enabled; the other capabilities default to disabled.

type CapabilityMode

type CapabilityMode uint8

CapabilityMode controls a boolean A2A capability while preserving a field-specific default.

const (
	// CapabilityDefault applies the bridge default for the capability.
	CapabilityDefault CapabilityMode = iota
	// CapabilityEnabled explicitly enables the capability.
	CapabilityEnabled
	// CapabilityDisabled explicitly disables the capability.
	CapabilityDisabled
)

type DiagnosticsPolicy

type DiagnosticsPolicy struct {
	// IncludeMetadata exposes Result metadata, RunError details, and provider
	// source coordinates on streamed events.
	IncludeMetadata bool
	// IncludeUsage exposes observed token usage. Unobserved usage remains
	// omitted; an observed zero value is preserved.
	IncludeUsage bool
	// IncludeProviderResult exposes the provider's validated terminal payload.
	IncludeProviderResult bool
	// IncludeTranscript exposes normalized transcript entries.
	IncludeTranscript bool
	// IncludeRawStreams exposes captured process stdout and stderr.
	IncludeRawStreams bool
	// IncludeHITLPayloads exposes structured approval request details and
	// choices.
	IncludeHITLPayloads bool
	// IncludeHITLRaw exposes raw approval data carried by approval notices.
	IncludeHITLRaw bool
}

DiagnosticsPolicy controls opt-in exposure of internal execution details.

All enabled fields are sanitized before they leave the bridge.

type EphemeralTaskStoreOptions

type EphemeralTaskStoreOptions struct {
	// MaxTasks is the maximum retained task count. Oldest tasks are evicted
	// first when the limit is exceeded.
	MaxTasks int
	// TTL is the maximum time since the latest update before a task expires.
	TTL time.Duration
}

EphemeralTaskStoreOptions configures the bounded in-memory task store used when TaskLifecycleOptions.Store is nil. Zero fields use the package defaults; negative values are invalid.

type ExposurePolicy

type ExposurePolicy struct {
	// IncludeReasoning exposes thinking events in streaming status updates.
	IncludeReasoning bool
	// IncludeToolCalls exposes tool-call and tool-result events in streaming
	// status updates.
	IncludeToolCalls bool
	// IncludeHITL exposes approval lifecycle events. Approval payloads remain
	// gated by Diagnostics.
	IncludeHITL bool

	// Diagnostics controls additional, sanitized diagnostic fields.
	Diagnostics DiagnosticsPolicy
}

ExposurePolicy controls which non-user-facing bridge artifacts are exposed to remote A2A callers.

The zero value is intentionally conservative:

  • assistant-facing Result.Text still flows through the task status message
  • terminal summary still flows through the agent-adaptor-result artifact
  • reasoning, tool-call internals, HITL events, and diagnostics stay hidden

type ExtendedAgentCardProvider

type ExtendedAgentCardProvider interface {
	// ExtendedCard returns the Agent Card visible to the request's tenant.
	ExtendedCard(ctx context.Context, req ExtendedAgentCardRequest) (AgentCard, error)
}

ExtendedAgentCardProvider builds an authenticated extended Agent Card.

type ExtendedAgentCardProviderFunc

type ExtendedAgentCardProviderFunc func(context.Context, ExtendedAgentCardRequest) (AgentCard, error)

ExtendedAgentCardProviderFunc adapts a function to ExtendedAgentCardProvider.

func (ExtendedAgentCardProviderFunc) ExtendedCard

ExtendedCard calls fn with the request context and tenant.

type ExtendedAgentCardRequest

type ExtendedAgentCardRequest struct {
	// Tenant is the tenant identifier from the A2A request, when present.
	Tenant string
}

ExtendedAgentCardRequest contains caller context passed to a dynamic extended-card provider.

type ExtendedAgentCardSupport

type ExtendedAgentCardSupport struct {
	// Static is the same extended card for every authenticated caller.
	Static *AgentCard
	// Provider builds an extended card for each request.
	Provider ExtendedAgentCardProvider
}

ExtendedAgentCardSupport configures either a static or dynamically generated extended Agent Card. Exactly one of Static and Provider must be set.

type Extension

type Extension struct {
	// URI is the globally unique extension identifier.
	URI string
	// Description explains the extension to clients.
	Description string
	// Required reports whether clients must understand the extension to
	// interact with the agent.
	Required bool
	// Params contains extension-specific, JSON-compatible parameters.
	Params map[string]any
}

Extension describes one A2A Agent Card extension.

type InboundRequest

type InboundRequest struct {
	// TaskID is the A2A task identifier.
	TaskID string
	// ContextID is the A2A conversation context identifier.
	ContextID string
	// Message is the submitted user message.
	Message Message
	// Metadata contains request-level A2A metadata.
	Metadata map[string]any
}

InboundRequest is the bridge-owned view of one A2A execution request passed to a PromptBuilder or ResultBuilder.

type Message

type Message struct {
	// ID is the message identifier.
	ID string
	// Role is the A2A message role value.
	Role string
	// TaskID is the task associated with the message.
	TaskID string
	// ContextID is the conversation context associated with the message.
	ContextID string
	// Parts contains the message content in source order.
	Parts []Part
	// ReferenceTasks contains identifiers of tasks referenced by the message.
	ReferenceTasks []string
	// Extensions contains extension URIs used by the message.
	Extensions []string
	// Metadata contains message-level A2A metadata.
	Metadata map[string]any
}

Message is the stable, protocol-local projection of an A2A message.

type Part

type Part struct {
	// Kind identifies which payload field is active.
	Kind PartKind
	// Text contains a PartText payload.
	Text string
	// Raw contains a PartRaw payload.
	Raw []byte
	// Data contains a JSON-compatible PartData payload.
	Data any
	// URL contains a PartURL payload.
	URL string
	// MediaType identifies the payload's media type.
	MediaType string
	// Filename is the suggested file name for raw or URL payloads.
	Filename string
	// Metadata contains part-level A2A metadata.
	Metadata map[string]any
}

Part is the stable, protocol-local projection of one A2A content part. The field corresponding to Kind carries the payload; MediaType, Filename, and Metadata provide optional part attributes.

type PartKind

type PartKind string

PartKind identifies the payload representation of a Part.

const (
	// PartText identifies a UTF-8 text payload.
	PartText PartKind = "text"
	// PartRaw identifies an inline byte payload.
	PartRaw PartKind = "raw"
	// PartData identifies a structured JSON-compatible payload.
	PartData PartKind = "data"
	// PartURL identifies a remotely hosted payload.
	PartURL PartKind = "url"
)

type PromptBuilder

type PromptBuilder func(ctx context.Context, req InboundRequest) (prompt string, opts []adaptor.CallOption, err error)

PromptBuilder turns one inbound A2A request into the prompt and per-call options for the run. Its options are applied after ServerOptions.Options and therefore provide request-specific overrides. Returning an error rejects the request as invalid before execution starts.

type Provider

type Provider struct {
	// Organization is the provider's display name.
	Organization string
	// URL is the provider's website or information endpoint.
	URL string
}

Provider identifies the organization responsible for an A2A agent.

type PushNotificationSupport

type PushNotificationSupport struct {
	// Store persists caller push-notification configurations.
	Store push.ConfigStore
	// Sender delivers task updates to configured endpoints.
	Sender push.Sender
}

PushNotificationSupport supplies the persistence and delivery components required when an Agent Card enables push notifications.

type ResultBuilder

type ResultBuilder func(ctx context.Context, req InboundRequest, result *adaptor.Result) (BuiltResult, error)

ResultBuilder customizes the terminal A2A artifacts and final status text produced from a successful run. Returning an error turns the A2A task into a failed terminal state.

type SecurityRequirement

type SecurityRequirement struct {
	// Schemes maps scheme names to required authorization scopes. Every scheme
	// in the map is required for this alternative.
	Schemes map[string][]string
}

SecurityRequirement describes one alternative authentication requirement.

type SecurityScheme

type SecurityScheme struct {
	// Name is the identifier referenced by [SecurityRequirement]. Empty names
	// are omitted.
	Name string
	// Type selects the authentication scheme shape. Its zero value selects
	// SecurityHTTP.
	Type SecuritySchemeType
	// Description explains the authentication requirement to callers.
	Description string
	// Scheme is the HTTP authentication scheme. It defaults to Bearer for
	// SecurityHTTP.
	Scheme string
	// BearerFormat documents the bearer token format for SecurityHTTP.
	BearerFormat string
	// In is the API-key location for SecurityAPIKey. It defaults to header.
	In string
	// ParamName is the header, query, or cookie parameter name for
	// SecurityAPIKey.
	ParamName string
}

SecurityScheme declares one named authentication scheme on an Agent Card. Fields that do not apply to Type are ignored.

type SecuritySchemeType

type SecuritySchemeType string

SecuritySchemeType identifies an Agent Card authentication scheme shape.

const (
	// SecurityHTTP selects HTTP authentication, such as Bearer or Basic.
	SecurityHTTP SecuritySchemeType = "http"
	// SecurityAPIKey selects an API key carried in a header, query parameter,
	// or cookie.
	SecurityAPIKey SecuritySchemeType = "apiKey"
	// SecurityMutualTLS selects mutual TLS authentication.
	SecurityMutualTLS SecuritySchemeType = "mutualTLS"
)

type Server

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

Server exposes a Runner through the A2A JSON-RPC protocol. Mount Server.Handler and Server.AgentCardHandler on host-selected routes; the host remains responsible for authentication middleware, TLS, and HTTP lifecycle.

func NewServer

func NewServer(runner adaptor.Runner, opts ServerOptions) *Server

NewServer assembles an A2A server around a Runner, normally an Agent or Thread. It panics for construction-time programming errors: a nil runner, an invalid Agent Card or task lifecycle, or support that disagrees with the advertised capability flags.

func (*Server) AgentCard

func (s *Server) AgentCard() AgentCard

AgentCard returns a copy of the effective public card after bridge-owned extensions and defaults have been applied.

func (*Server) AgentCardHandler

func (s *Server) AgentCardHandler() http.Handler

AgentCardHandler returns an HTTP handler that serves the effective public Agent Card.

func (*Server) Handler

func (s *Server) Handler() http.Handler

Handler returns the A2A JSON-RPC endpoint handler.

type ServerOptions

type ServerOptions struct {
	// AgentCard is the public A2A identity of this server.
	AgentCard AgentCard

	// Session decides thread binding per inbound request. Nil uses Stateless.
	Session SessionBinding

	// Prompt, when set, replaces the default prompt extraction (the last
	// non-blank text part of the inbound message).
	Prompt PromptBuilder

	// Options are applied to every run at call scope. PromptBuilder options are
	// applied afterward.
	Options []adaptor.CallOption

	// ResultBuilder, when set, customizes successful terminal artifacts and
	// status text.
	ResultBuilder ResultBuilder

	// TaskLifecycle configures protocol task persistence and retention. Its zero
	// value uses an in-memory store retaining at most
	// DefaultEphemeralTaskLimit tasks for DefaultEphemeralTaskTTL.
	TaskLifecycle TaskLifecycleOptions

	// PushNotifications must be set exactly when the card enables the
	// capability; configuration is validated at construction.
	PushNotifications *PushNotificationSupport

	// ExtendedAgentCard must be set exactly when the card enables the
	// capability; configuration is validated at construction.
	ExtendedAgentCard *ExtendedAgentCardSupport

	// Exposure controls how much intermediate detail crosses the A2A
	// boundary. The zero value hides reasoning, tool calls, HITL traffic,
	// and all diagnostics.
	Exposure ExposurePolicy
}

ServerOptions configures NewServer. AgentCard is required. The zero values select stateless execution, the last non-blank text part as prompt, the bounded in-memory task store, and conservative exposure.

type SessionBinding

type SessionBinding interface {
	// contains filtered or unexported methods
}

SessionBinding decides which Runner executes an inbound A2A request. The package seals this interface so callers select either Stateless or ThreadByContextID. A nil binding is equivalent to Stateless.

func Stateless

func Stateless() SessionBinding

Stateless runs every inbound request on the configured Runner as-is, without creating Thread state or carrying conversation state between requests. It is the default SessionBinding.

func ThreadByContextID

func ThreadByContextID() SessionBinding

ThreadByContextID maps each non-empty A2A contextID to a collision-free, namespace-encoded Thread key. Follow-up messages in the same A2A context therefore continue the same conversation.

The configured Runner must be an *adaptor.Agent carrying a thread store (adaptor.WithThreadStore) — only an Agent can mint threads. A request without a contextID runs stateless.

type Skill

type Skill struct {
	// ID is the stable, machine-readable skill identifier.
	ID string
	// Name is the human-readable skill name.
	Name string
	// Description explains what the skill does.
	Description string
	// Tags are search and discovery labels.
	Tags []string
	// Examples contains representative prompts or use cases.
	Examples []string
	// InputModes overrides the Agent Card's default input modes for this skill.
	InputModes []string
	// OutputModes overrides the Agent Card's default output modes for this
	// skill.
	OutputModes []string
}

Skill describes a task the agent advertises through its Agent Card. ID is required.

type TaskLifecycleOptions

type TaskLifecycleOptions struct {
	// Store is a host-provided task store. When non-nil, it takes precedence
	// over Ephemeral.
	Store taskstore.Store
	// Ephemeral configures the default in-memory store used when Store is nil.
	// A nil value uses [DefaultEphemeralTaskLimit] and
	// [DefaultEphemeralTaskTTL].
	Ephemeral *EphemeralTaskStoreOptions
}

TaskLifecycleOptions selects how an A2A server persists protocol tasks.

Jump to

Keyboard shortcuts

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