a2aserver

package module
v2.23.0 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: Apache-2.0 Imports: 22 Imported by: 2 modules, 2 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package a2aserver provides a standalone A2A-protocol HTTP server that can be backed by any conversation implementation satisfying the interfaces defined here. It imports only runtime/ and has no dependency on sdk/.

The server speaks A2A 1.0 and 0.3 over one JSON-RPC endpoint, POST /a2a, and answers each request in the protocol version it asked for. It also serves the agent card at /.well-known/agent-card.json (and the legacy /.well-known/agent.json) and the liveness and readiness probes /healthz and /readyz.

There are two ways to supply the agent. NewServer takes a ConversationOpener and owns the conversations: it opens one per context ID, caches it, and expires it when idle. NewServerFor does the same with an opener that is given the request opening the context, so the conversation can act for the caller the host's authentication identified. NewStatelessServer takes a MessageHandler and keeps no conversations, so the embedder decides what a conversation is. In both modes the server runs the task state machine, stores tasks in a TaskStore, and streams updates over SSE. The server does not support push notifications.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	ErrTaskNotFound      = errors.New("a2a: task not found")
	ErrTaskAlreadyExists = errors.New("a2a: task already exists")
	ErrInvalidTransition = errors.New("a2a: invalid state transition")
	ErrTaskTerminal      = errors.New("a2a: task is in a terminal state")

	// ErrTransitionRefused is for a store to wrap when it refuses a state
	// change on purpose, such as a store that keeps a task working while one
	// of its tool calls waits for approval. The server logs the refusal at
	// debug level instead of as a failure, and, as for any SetState error,
	// does not publish the state.
	ErrTransitionRefused = errors.New("a2a: state transition refused by the store")
)

Task store errors, returned by TaskStore methods.

View Source
var ErrTooManySubscribers = errors.New("a2a: too many subscribers")

ErrTooManySubscribers is returned when a task has reached its subscriber limit.

Functions

This section is empty.

Types

type AgentCardProvider

type AgentCardProvider interface {
	AgentCard(r *http.Request) (*a2a.AgentCard, error)
}

AgentCardProvider returns the agent card to serve at /.well-known/agent-card.json (and the legacy /.well-known/agent.json). The server completes the returned card as WithCard describes.

A card from a provider may differ per request (by tenant, cookie or forwarded header), so unless WithCardMaxAge is set it is served with Cache-Control: no-cache: clients revalidate every fetch, and its ETag makes an unchanged card a 304. A *StaticCard is cached like a WithCard card.

type Authenticator

type Authenticator interface {
	Authenticate(r *http.Request) error
}

Authenticator validates incoming requests to POST /a2a. Return a non-nil error to reject the request, which the server answers with HTTP 401 and a JSON-RPC error. The agent card and health endpoints are not authenticated.

type CompletableConversation added in v2.20.0

type CompletableConversation interface {
	Conversation
	// Complete ends the conversation and releases it, as Close does.
	Complete() error
}

CompletableConversation is a Conversation the server can end rather than release. With WithCompleteOnEviction, the server calls Complete instead of Close when it evicts an idle conversation that implements it. An SDK conversation's Complete runs its on_conversation_complete evals.

type Conversation

type Conversation interface {
	// Send delivers a message and returns the completed turn. The message is the
	// result of a2a.MessageToMessage, a *types.Message.
	Send(ctx context.Context, message any) (SendResult, error)
	// Close releases the conversation. The server calls it on eviction and on
	// Shutdown.
	Close() error
}

Conversation is the non-streaming conversation interface the server uses.

type ConversationOpener

type ConversationOpener func(contextID string) (Conversation, error)

ConversationOpener creates or retrieves a conversation for a given context ID. NewServer calls it once per context ID and caches the result.

type EventKind

type EventKind int

EventKind discriminates the payload of a StreamEvent.

const (
	// EventText indicates the event contains text content.
	EventText EventKind = iota

	// EventToolCall indicates a tool call (suppressed by the server).
	EventToolCall

	// EventMedia indicates the event contains media content.
	EventMedia

	// EventDone indicates the stream is complete.
	EventDone

	// EventClientTool indicates a client tool request awaiting fulfillment.
	EventClientTool

	// EventPending indicates the turn is paused on something the server cannot
	// see, most often a human approving a tool call. Text carries the reason.
	// The task moves to input-required instead of completed. A handler that
	// never pauses never emits it.
	EventPending
)

type HealthChecker

type HealthChecker interface {
	Check(ctx context.Context) error
}

HealthChecker performs a named health check. Implementations should return nil when healthy and a non-nil error describing the problem otherwise.

type HealthCheckerFunc

type HealthCheckerFunc func(ctx context.Context) error

HealthCheckerFunc adapts an ordinary function to the HealthChecker interface.

func (HealthCheckerFunc) Check

func (f HealthCheckerFunc) Check(ctx context.Context) error

Check calls f(ctx).

type InMemoryTaskStore

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

InMemoryTaskStore is a concurrency-safe, in-memory implementation of TaskStore, TaskQuerier, OwnedTaskStore, TenantTaskStore, TaskHistoryStore and InterruptedTaskEvictor.

Example

ExampleInMemoryTaskStore demonstrates the task lifecycle: create a task, transition it through states, and read it back. InMemoryTaskStore needs no external services, making it a good default for local development and tests; production deployments typically supply a persistent TaskStore.

package main

import (
	"fmt"

	a2aserver "github.com/AltairaLabs/PromptKit/server/a2a/v2"
)

func main() {
	store := a2aserver.NewInMemoryTaskStore()

	task, err := store.Create("task-1", "ctx-1")
	if err != nil {
		fmt.Println("create error:", err)
		return
	}
	fmt.Println("created:", task.Status.State)

	if err := store.SetState("task-1", "working", nil); err != nil {
		fmt.Println("transition error:", err)
		return
	}

	got, err := store.Get("task-1")
	if err != nil {
		fmt.Println("get error:", err)
		return
	}
	fmt.Println("state:", got.Status.State)
}
Output:
created: submitted
state: working

func NewInMemoryTaskStore

func NewInMemoryTaskStore() *InMemoryTaskStore

NewInMemoryTaskStore creates a new InMemoryTaskStore.

func (*InMemoryTaskStore) AddArtifacts

func (s *InMemoryTaskStore) AddArtifacts(taskID string, artifacts []a2a.Artifact) error

AddArtifacts appends artifacts to a task.

func (*InMemoryTaskStore) AppendHistory added in v2.22.0

func (s *InMemoryTaskStore) AppendHistory(taskID string, limit int, msgs ...a2a.Message) error

AppendHistory implements TaskHistoryStore.

func (*InMemoryTaskStore) Cancel

func (s *InMemoryTaskStore) Cancel(taskID string) error

Cancel transitions the task to the canceled state from any non-terminal state, and returns ErrTaskTerminal otherwise.

func (*InMemoryTaskStore) Create

func (s *InMemoryTaskStore) Create(taskID, contextID string) (*a2a.Task, error)

Create initializes a new task in the submitted state.

func (*InMemoryTaskStore) CreateInTenant added in v2.22.0

func (s *InMemoryTaskStore) CreateInTenant(taskID, contextID, owner, tenant string) (*a2a.Task, error)

CreateInTenant implements TenantTaskStore. An empty owner or tenant records none.

func (*InMemoryTaskStore) CreateOwned added in v2.8.0

func (s *InMemoryTaskStore) CreateOwned(taskID, contextID, owner string) (*a2a.Task, error)

CreateOwned implements OwnedTaskStore. An empty owner records none.

func (*InMemoryTaskStore) EvictInterrupted added in v2.22.0

func (s *InMemoryTaskStore) EvictInterrupted(cutoff time.Time) []string

EvictInterrupted implements InterruptedTaskEvictor: it removes tasks waiting for the caller (input-required, auth-required) whose last status timestamp is older than cutoff, and returns their IDs.

func (*InMemoryTaskStore) EvictTerminal

func (s *InMemoryTaskStore) EvictTerminal(cutoff time.Time) []string

EvictTerminal removes tasks in a terminal state whose last status timestamp is older than cutoff. It returns the IDs of evicted tasks.

func (*InMemoryTaskStore) Get

func (s *InMemoryTaskStore) Get(taskID string) (*a2a.Task, error)

Get retrieves a deep copy of a task by ID. The returned task is safe to read/modify without holding the store lock.

func (*InMemoryTaskStore) List

func (s *InMemoryTaskStore) List(contextID string, limit, offset int) ([]*a2a.Task, error)

List returns deep copies of tasks matching the given contextID with pagination. If contextID is empty, all tasks are returned. Results are ordered most recently updated first, ID breaking ties, for deterministic pagination. Offset and limit control pagination.

func (*InMemoryTaskStore) Owner added in v2.8.0

func (s *InMemoryTaskStore) Owner(taskID string) (string, error)

Owner implements OwnedTaskStore. A task created without an owner has "".

func (*InMemoryTaskStore) Query added in v2.8.0

func (s *InMemoryTaskStore) Query(q TaskQuery) (TaskPage, error)

Query implements TaskQuerier.

func (*InMemoryTaskStore) SetState

func (s *InMemoryTaskStore) SetState(taskID string, state a2a.TaskState, msg *a2a.Message) error

SetState transitions the task to a new state with an optional status message.

func (*InMemoryTaskStore) Tenant added in v2.22.0

func (s *InMemoryTaskStore) Tenant(taskID string) (string, error)

Tenant implements TenantTaskStore. A task created in no tenant has "".

type InterruptedTaskEvictor added in v2.22.0

type InterruptedTaskEvictor interface {
	// EvictInterrupted removes tasks in the input-required or auth-required
	// state whose last status timestamp is older than olderThan, and returns
	// their IDs.
	EvictInterrupted(olderThan time.Time) []string
}

InterruptedTaskEvictor is optionally implemented by a TaskStore that can evict tasks left waiting for the caller (WithInterruptedTaskTTL). InMemoryTaskStore is one. A store without it keeps such tasks until they are canceled, so it must bound them itself. A store embedding *InMemoryTaskStore gets the embedded store's EvictInterrupted, which removes only the tasks that store holds.

type MessageHandler added in v2.5.0

type MessageHandler interface {
	Handle(ctx context.Context, req MessageRequest) <-chan StreamEvent
}

MessageHandler turns one inbound A2A message into a stream of events.

Handle is called once per message and the server keeps no state between calls. ctx is the HTTP request's context, so whatever the embedder's middleware put on it (caller identity, tenant, trace) is readable here, which is the thing ConversationOpener cannot offer.

The returned channel must be closed when the turn is over. A closing channel that sent no EventDone is treated as a completed turn.

type MessageRequest added in v2.5.0

type MessageRequest struct {
	// ContextID is client-supplied. The server attaches no meaning to it: the
	// embedder decides whether it identifies a session, and whether two callers
	// presenting the same one share anything.
	ContextID string

	// TaskID is the id of the task this message runs on: a task the server
	// created for it, or the existing task its taskId continues.
	TaskID string

	// Message is the inbound A2A message.
	Message a2a.Message

	// Tenant is the request's tenant (A2A 1.0), "" when it named none.
	Tenant string
}

MessageRequest is one inbound message, as the handler sees it.

type Option

type Option func(*Server)

Option configures a Server.

func WithAuthenticator

func WithAuthenticator(auth Authenticator) Option

WithAuthenticator sets an authenticator for incoming JSON-RPC requests.

func WithCard

func WithCard(card *a2a.AgentCard) Option

WithCard sets the agent card served at /.well-known/agent-card.json.

The server completes a copy of the card before serving it. A card with no interfaces gets a JSON-RPC interface pointing at this server's /a2a endpoint, derived from the request's Host; JSON-RPC interfaces are declared for both A2A 1.0 and 0.3; Streaming is set to true (false WithoutStreaming) and PushNotifications to false. Declare SecuritySchemes and SecurityRequirements on the card when WithAuthenticator is in use, so callers can discover how to authenticate.

func WithCardMaxAge added in v2.22.0

func WithCardMaxAge(d time.Duration) Option

WithCardMaxAge sets the max-age of the Cache-Control header on the served agent card (A2A 1.0 §8.6): how long a client or cache may reuse the card before asking again. Without it, a card set with WithCard (or none) gets five minutes and a card from a dynamic AgentCardProvider gets "no-cache". Zero or less sends "no-cache", so clients revalidate every time; the card's ETag keeps that to a 304 while the card is unchanged.

func WithCardProvider

func WithCardProvider(p AgentCardProvider) Option

WithCardProvider sets a dynamic agent card provider.

func WithCompleteOnEviction added in v2.20.0

func WithCompleteOnEviction() Option

WithCompleteOnEviction makes idle eviction (WithConversationTTL) end a conversation rather than suspend it: the server calls Complete on an evicted conversation that implements CompletableConversation, and Close on any other. Set it when the opener starts a fresh conversation for each context ID, so an evicted conversation cannot carry on. Leave it unset when the opener resumes stored state, where eviction is a pause and completing at each one would score the conversation more than once. Shutdown always calls Close.

func WithConversationTTL

func WithConversationTTL(d time.Duration) Option

WithConversationTTL sets how long idle conversations are retained before automatic eviction. A conversation is considered idle when its last-use timestamp exceeds this duration. Default: 1 hour. Set to 0 to disable.

func WithExtendedCardProvider added in v2.22.0

func WithExtendedCardProvider(p AgentCardProvider) Option

WithExtendedCardProvider sets the extended agent card: the card GetExtendedAgentCard returns to a caller that has authenticated (A2A 1.0 §3.1.11), which may name skills or details the public card leaves out. The public card then declares capabilities.extendedAgentCard, and the server completes the extended card as WithCard describes. The provider is given the request, so it can tailor the card to the caller; use WithAuthenticator so that only authenticated callers reach it: A2A 1.0 §3.1.11 requires the call to be authenticated, so a server with no authenticator, WithTaskOwner or NewServerFor answers it with ExtendedAgentCardNotConfiguredError instead of serving the card. A *StaticCard serves the same card to every caller.

func WithHealthCheck

func WithHealthCheck(name string, checker HealthChecker) Option

WithHealthCheck registers a named health checker that is evaluated by the /readyz endpoint. Multiple checkers can be registered; each is reported individually in the response body.

func WithIdleTimeout

func WithIdleTimeout(d time.Duration) Option

WithIdleTimeout sets the maximum amount of time to wait for the next request when keep-alives are enabled. Default: 120s.

func WithInterruptedTaskTTL added in v2.22.0

func WithInterruptedTaskTTL(d time.Duration) Option

WithInterruptedTaskTTL sets how long a task left waiting for the caller (input-required or auth-required) is kept, from its last status change, before it is evicted; GetTask then reports it not found. A caller that never comes back would otherwise leave it in the store for good, as does a client that resumes without the task's taskId, which starts a new task instead. Default: 24 hours. Set to 0 to keep waiting tasks until they are canceled.

The default in-memory store supports it. A custom TaskStore takes part by implementing InterruptedTaskEvictor; one that does not is left to bound its waiting tasks itself.

func WithLogger added in v2.20.0

func WithLogger(l *slog.Logger) Option

WithLogger sets the logger the server writes its diagnostics to. Without it, the server uses PromptKit's logger (logger.GetLogger), so logger.SetLogger and logger.Configure apply.

func WithMaxBlockingWait added in v2.8.0

func WithMaxBlockingWait(d time.Duration) Option

WithMaxBlockingWait caps how long a blocking SendMessage holds its request open. When the turn has not finished or been interrupted by then, the server answers with the task in its current (working) state, and the turn runs on: the caller polls GetTask or subscribes for the rest. Default: 0, no cap. A 1.0 SendMessage waits for the turn, as the spec requires, until the turn ends or the caller disconnects.

Set it below the timeout of whatever sits in front of the server (a load balancer's idle timeout, a proxy's read timeout), so the caller gets a task to follow rather than a gateway error.

func WithMaxBodySize

func WithMaxBodySize(n int64) Option

WithMaxBodySize sets the maximum allowed request body size in bytes for JSON-RPC requests. Default: 10 MB.

func WithMaxTaskHistory added in v2.22.0

func WithMaxTaskHistory(n int) Option

WithMaxTaskHistory caps how many messages a task's history keeps: past the cap the oldest are dropped. Default: 100. Zero or less keeps them all. A message is kept as it was sent, file parts and their bytes included, so a conversation exchanging files holds up to that many of them per task.

func WithPort

func WithPort(port int) Option

WithPort sets the TCP port for ListenAndServe. It has no effect on Serve.

func WithReadTimeout

func WithReadTimeout(d time.Duration) Option

WithReadTimeout sets the maximum duration for reading the entire request. Default: 30s.

func WithTaskCanceler added in v2.8.0

func WithTaskCanceler(c TaskCanceler) Option

WithTaskCanceler sets how CancelTask reaches the instance running a task. Default: in-process only.

func WithTaskEventBus added in v2.8.0

func WithTaskEventBus(bus TaskEventBus) Option

WithTaskEventBus sets how task updates reach SubscribeToTask callers. Default: in-process only.

func WithTaskOwner added in v2.8.0

func WithTaskOwner(owner OwnerFunc) Option

WithTaskOwner scopes every task to the caller that created it. owner identifies the caller of each request; GetTask, CancelTask, ListTasks and SubscribeToTask then see only the caller's own tasks, and ListTasks without a contextId lists them all. A task another caller owns is reported as not found. With NewServer, a message into a conversation another caller opened is refused; with NewStatelessServer the handler owns contexts and decides.

The task store must implement OwnedTaskStore (the default in-memory store does); NewServer and NewStatelessServer panic otherwise. A request whose owner is empty is refused with HTTP 401.

func WithTaskStore

func WithTaskStore(store TaskStore) Option

WithTaskStore sets a custom task store. Defaults to an in-memory store.

func WithTaskTTL

func WithTaskTTL(d time.Duration) Option

WithTaskTTL sets how long completed/failed/canceled tasks are retained before automatic eviction. Default: 1 hour. Set to 0 to disable eviction.

func WithWriteTimeout

func WithWriteTimeout(d time.Duration) Option

WithWriteTimeout sets the HTTP server's WriteTimeout for ListenAndServe and Serve: the most time a response may take, from the end of reading the request headers. Default: 0, no write timeout. SSE streams (SendStreamingMessage, SubscribeToTask) lift it for their own connection, so they stay open for as long as the turn runs; a blocking SendMessage does not, so set it above the longest turn a caller waits on, or cap that wait with WithMaxBlockingWait.

func WithoutStreaming added in v2.22.0

func WithoutStreaming() Option

WithoutStreaming turns streaming off. The served card declares capabilities.streaming false, and SendStreamingMessage and SubscribeToTask (0.3: message/stream, tasks/resubscribe) fail with UnsupportedOperationError (-32004), as A2A 1.0 §3.3.4 requires of an agent that does not declare streaming. Callers send with SendMessage and poll GetTask. Use it when something in front of the server cannot carry Server-Sent Events.

type OwnedTaskStore added in v2.8.0

type OwnedTaskStore interface {
	TaskStore
	// CreateOwned creates a task, as Create does, recording owner as its
	// creator.
	CreateOwned(taskID, contextID, owner string) (*a2a.Task, error)
	// Owner returns the owner recorded for a task, or ErrTaskNotFound.
	Owner(taskID string) (string, error)
}

OwnedTaskStore is a TaskStore that records which caller created each task. WithTaskOwner requires one; InMemoryTaskStore is one.

A store that also implements TaskQuerier must honor TaskQuery.Owner.

type OwnerFunc added in v2.8.0

type OwnerFunc func(r *http.Request) string

OwnerFunc identifies the caller of a request, typically from what the host's authentication middleware put on the request context. It must return a non-empty identity for every caller allowed to use the server.

type PendingClientToolInfo

type PendingClientToolInfo struct {
	CallID     string         `json:"call_id"`
	ToolName   string         `json:"tool_name"`
	Args       map[string]any `json:"args,omitempty"`
	ConsentMsg string         `json:"consent_message,omitempty"`
}

PendingClientToolInfo describes a client-side tool call awaiting fulfillment.

type RequestConversationOpener added in v2.22.0

type RequestConversationOpener func(r *http.Request, contextID string) (Conversation, error)

RequestConversationOpener is ConversationOpener given the HTTP request that opens the context. The A2A protocol carries no caller identity of its own: the host's authentication puts it on the request (its context or headers), so this is where a host reads who the conversation acts for. NewServerFor calls it once per context ID, with the request whose message first names that context, and caches the result.

type ResumableConversation

type ResumableConversation interface {
	Conversation
	// SendToolResult supplies the result of the client tool call callID.
	SendToolResult(callID string, result any) error
	// RejectClientTool records that the caller declined the client tool call
	// callID, with the caller's reason.
	RejectClientTool(callID string, reason string)
	// Resume continues the turn once the pending tool calls are resolved and
	// returns the completed turn.
	Resume(ctx context.Context) (SendResult, error)
	// ResumeStream is Resume for a streamed turn.
	ResumeStream(ctx context.Context) <-chan StreamEvent
}

ResumableConversation extends Conversation with the ability to submit client-side tool results and resume pipeline execution.

type SendResult

type SendResult interface {
	// HasPendingTools reports whether there are tools awaiting approval
	// (HITL or client-side). When true the task transitions to input_required.
	HasPendingTools() bool

	// HasPendingClientTools reports whether there are client-side tools
	// awaiting fulfillment by the caller.
	HasPendingClientTools() bool

	// PendingClientTools returns metadata for each pending client tool.
	PendingClientTools() []PendingClientToolInfo

	// Parts returns the content parts of the response.
	Parts() []types.ContentPart

	// Text returns the text content of the response as a fallback
	// when Parts() is empty.
	Text() string
}

SendResult is what the server needs from a completed conversation turn.

type Server

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

Server is an HTTP server that exposes a Conversation as an A2A-compliant JSON-RPC endpoint.

func NewServer

func NewServer(opener ConversationOpener, opts ...Option) *Server

NewServer creates a new A2A server that owns its conversations: it opens one per context id through the supplied opener, caches it, and reuses it when that id returns. Suits an embedder running A2A and the runtime in one process. A background goroutine evicts expired tasks and idle conversations until Shutdown.

For an embedder that owns conversations itself (because the runtime lives elsewhere, or it already tracks sessions), see NewStatelessServer.

func NewServerFor added in v2.22.0

func NewServerFor(callerID OwnerFunc, opener RequestConversationOpener, opts ...Option) *Server

NewServerFor is NewServer for conversations that act for the caller of the request opening them. callerID identifies the caller of each request, typically from what the host's authentication middleware put on it; a request it gives no identity is refused. opener is given the request opening each context, so the conversation can act for that caller.

A context's conversation belongs to the caller who opened it: a message from another caller naming that context is refused, whether or not tasks are scoped with WithTaskOwner. Tasks are scoped by callerID as WithTaskOwner scopes them: GetTask, CancelTask, ListTasks and SubscribeToTask see only the caller's own tasks, and another caller's task is reported as not found. A WithTaskOwner in opts overrides callerID for task scoping, and like it the TaskStore must implement OwnedTaskStore. Openers run outside the server's lock, one at a time per context, so a slow open does not hold up other contexts.

func NewStatelessServer added in v2.5.0

func NewStatelessServer(h MessageHandler, opts ...Option) *Server

NewStatelessServer creates a server that holds no conversations.

It is NewServer's sibling: same protocol, same options, but each message goes to the handler with its request context and nothing is kept between calls. Use it when the embedder owns conversations: because it already tracks sessions, because the runtime is in another process, or because the server needs to scale horizontally with only the task store shared.

func (*Server) Handler

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

Handler returns an http.Handler implementing the A2A protocol. It serves the agent card at GET /.well-known/agent-card.json and /.well-known/agent.json, JSON-RPC at POST /a2a, and the probes GET /healthz and GET /readyz. Requests are traced with OpenTelemetry, and a panic in a handler is recovered and answered with a JSON-RPC internal error.

func (*Server) ListenAndServe

func (s *Server) ListenAndServe() error

ListenAndServe starts the HTTP server on the configured port and blocks until it stops. The server applies the read, write and idle timeouts the options set; see WithWriteTimeout for how SSE streams treat the write timeout.

func (*Server) Serve

func (s *Server) Serve(ln net.Listener) error

Serve starts the HTTP server on the given listener and blocks until it stops. It applies the same timeouts as ListenAndServe.

func (*Server) Shutdown

func (s *Server) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down the server: it marks the server not ready, stops the eviction goroutine, drains HTTP requests, ends task subscriptions, cancels in-flight tasks, and closes all conversations. It returns the first error from stopping the HTTP server or closing a conversation.

type StaticCard

type StaticCard struct {
	Card a2a.AgentCard
}

StaticCard is an AgentCardProvider that always returns the same card.

func (*StaticCard) AgentCard

func (s *StaticCard) AgentCard(*http.Request) (*a2a.AgentCard, error)

AgentCard returns the static card.

type StreamEvent

type StreamEvent struct {
	// Kind says which of the other fields applies.
	Kind EventKind
	// Text is the content of an EventText event, or the reason of an
	// EventPending event.
	Text string
	// ReplacesText marks an EventText whose Text replaces all the text the
	// turn streamed before it (an output guardrail cut the reply). The server
	// restarts the text artifact with it: the update goes out with append
	// false, so a client replaces the artifact's text, and the task keeps
	// only Text.
	ReplacesText bool
	// Media is the content of an EventMedia event.
	Media *types.MediaContent
	// ClientTool describes the request of an EventClientTool event.
	ClientTool *PendingClientToolInfo
	// Error, when non-nil, ends the turn and fails the task.
	Error error
}

StreamEvent is a single event on a streaming channel.

type StreamingConversation

type StreamingConversation interface {
	Conversation
	// Stream delivers a message and returns the events of the turn. The channel
	// is closed when the turn ends.
	Stream(ctx context.Context, message any) <-chan StreamEvent
}

StreamingConversation extends Conversation with streaming support. A conversation that does not implement it is streamed from its Send result.

type TaskCanceler added in v2.8.0

type TaskCanceler interface {
	// Cancel asks whichever instance is running taskID to stop it. The task
	// is already marked canceled in the store when this is called.
	Cancel(ctx context.Context, taskID string) error
	// Listen registers the function that stops a turn running on this
	// instance; the implementation calls it for every cancel request, from
	// any instance, and it is a no-op for tasks this instance is not
	// running. The server calls Listen once, when it is created, and stop
	// when it shuts down.
	Listen(cancelLocal func(taskID string)) (stop func())
}

TaskCanceler stops a task's in-flight turn wherever it runs.

The default is in-process: CancelTask stops a turn only on the instance running it. A host running several replicas supplies a shared implementation with WithTaskCanceler, or pins each task's callers to one replica.

type TaskEvent added in v2.8.0

type TaskEvent struct {
	StatusUpdate   *a2a.TaskStatusUpdateEvent   `json:"statusUpdate,omitempty"`
	ArtifactUpdate *a2a.TaskArtifactUpdateEvent `json:"artifactUpdate,omitempty"`
}

TaskEvent is one update to a task, as SubscribeToTask callers receive it. Exactly one field is set.

It is version-neutral because a subscriber may speak a different protocol version, and carries a different JSON-RPC id, than the caller whose turn produced the event, so each subscriber encodes it for itself.

func (TaskEvent) IsFinal added in v2.8.0

func (e TaskEvent) IsFinal() bool

IsFinal reports whether the event ends a task's stream: a status update to a terminal or interrupted state.

type TaskEventBus added in v2.8.0

type TaskEventBus interface {
	// Publish delivers evt to the task's subscribers, wherever they are.
	Publish(ctx context.Context, taskID string, evt TaskEvent) error
	// Subscribe returns the task's events from now on. The server stops
	// reading after a final event (TaskEvent.IsFinal); the implementation
	// must stop delivering, and release the subscription, when ctx ends.
	Subscribe(ctx context.Context, taskID string) (<-chan TaskEvent, error)
}

TaskEventBus carries task updates to SubscribeToTask callers.

The default is in-process: a subscriber sees updates only from turns this server instance runs. A host running several replicas behind one task store supplies a shared implementation (Redis pub/sub, NATS, ...) with WithTaskEventBus, or pins each task's callers to one replica.

type TaskHistoryStore added in v2.22.0

type TaskHistoryStore interface {
	// AppendHistory adds msgs to the end of the task's history, keeping at
	// most limit messages (the most recent; zero or less keeps all), or
	// returns ErrTaskNotFound.
	AppendHistory(taskID string, limit int, msgs ...a2a.Message) error
}

TaskHistoryStore is optionally implemented by a TaskStore that keeps each task's history (A2A 1.0 Task.history): the messages its turns exchanged. InMemoryTaskStore is one. The server appends the caller's message when a turn begins and the agent's status message when a turn ends with one, and expects Get to return them, oldest first, in Task.History; GetTask, ListTasks and SendMessage trim them to the caller's historyLength. A store without it serves tasks with no history. A store embedding *InMemoryTaskStore gets the embedded store's AppendHistory, which records history only on the tasks that store holds.

type TaskPage added in v2.8.0

type TaskPage struct {
	// Tasks are ordered most recently updated first (A2A 1.0 §3.1.4).
	Tasks []*a2a.Task
	// Total is the number of tasks matching the query across all pages.
	Total int
}

TaskPage is one page of a TaskQuery's result.

type TaskQuerier added in v2.8.0

type TaskQuerier interface {
	Query(q TaskQuery) (TaskPage, error)
}

TaskQuerier is optionally implemented by a TaskStore that can filter, order and page tasks itself. Without it the server pages through List and does the filtering and ordering in memory, which is correct but reads every task in the context on each call.

type TaskQuery added in v2.8.0

type TaskQuery struct {
	// Owner, when set, restricts the query to the tasks that caller created
	// (see OwnedTaskStore).
	Owner string
	// Tenant keeps only the tasks created in that tenant, "" only those
	// created in none (see TenantTaskStore).
	Tenant string
	// ContextID, when set, restricts the query to one context.
	ContextID string
	// Status, when set, keeps only tasks in that state.
	Status *a2a.TaskState
	// StatusAfter, when set, keeps only tasks whose status changed at or after it.
	StatusAfter *time.Time
	// Limit and Offset select the page within the ordered result.
	Limit  int
	Offset int
}

TaskQuery selects a page of tasks for ListTasks.

type TaskStore

type TaskStore interface {
	// Create makes a task in the submitted state, or returns
	// ErrTaskAlreadyExists.
	Create(taskID, contextID string) (*a2a.Task, error)
	// Get returns a copy of the task.
	Get(taskID string) (*a2a.Task, error)
	// SetState moves the task to state, with an optional status message. It
	// returns ErrTaskTerminal for a finished task and ErrInvalidTransition for a
	// move the state machine does not allow.
	SetState(taskID string, state a2a.TaskState, msg *a2a.Message) error
	// AddArtifacts appends artifacts to the task.
	AddArtifacts(taskID string, artifacts []a2a.Artifact) error
	// Cancel moves a task that has not finished to the canceled state, or
	// returns ErrTaskTerminal.
	Cancel(taskID string) error
	// List returns copies of the tasks in a context (all tasks when contextID is
	// empty), most recently updated first, at most limit of them from offset. A
	// limit of zero or less means no limit.
	List(contextID string, limit, offset int) ([]*a2a.Task, error)

	// EvictTerminal removes tasks in a terminal state whose last status
	// timestamp is older than the given cutoff time. It returns the IDs
	// of evicted tasks so callers can clean up associated resources.
	EvictTerminal(olderThan time.Time) []string
}

TaskStore defines the interface for task persistence and lifecycle management. Methods return ErrTaskNotFound for an unknown task.

type TenantTaskStore added in v2.22.0

type TenantTaskStore interface {
	OwnedTaskStore
	// CreateInTenant creates a task, as CreateOwned does, recording tenant
	// as the tenant it was created in ("" for none).
	CreateInTenant(taskID, contextID, owner, tenant string) (*a2a.Task, error)
	// Tenant returns the tenant recorded for a task ("" for none), or
	// ErrTaskNotFound.
	Tenant(taskID string) (string, error)
}

TenantTaskStore is an OwnedTaskStore that also records the tenant each task was created in: the tenant an A2A 1.0 request names, as the client takes it from the AgentInterface it calls. With one, a task is visible only to requests in its tenant (another tenant, or none, gets TaskNotFound), and a context belongs to the tenant that first used it. A task the store records no tenant for is in none. InMemoryTaskStore is one. With a store that is not, a request that names a tenant is refused with UnsupportedOperationError rather than served across tenants.

A store that also implements TaskQuerier should honor TaskQuery.Tenant; the server drops another tenant's tasks from a query's page either way.

A store embedding *InMemoryTaskStore gets CreateInTenant and Tenant by promotion, acting on the embedded store's tasks: one that overrides Create, or keeps tasks elsewhere, must override them too, or embed the TaskStore interface instead.

type ToolResult added in v2.5.0

type ToolResult struct {
	// CallID identifies the tool call, as the handler supplied it.
	CallID string
	// Result is the tool's result, as the caller sent it.
	Result any

	// Rejected is true when the caller declined the tool. Reason carries their
	// explanation, if any.
	Rejected bool
	Reason   string
}

ToolResult is one fulfilled (or refused) client-side tool call.

type ToolResultHandler added in v2.5.0

type ToolResultHandler interface {
	HandleToolResult(ctx context.Context, req ToolResultRequest) <-chan StreamEvent
}

ToolResultHandler is the optional client-tool half of MessageHandler. A handler that implements it can receive the results of client-side tool calls it asked for earlier and continue the turn.

Without it, a stateless server rejects tool-result messages rather than pretending to resume something it is not holding.

type ToolResultRequest added in v2.5.0

type ToolResultRequest struct {
	// ContextID and TaskID identify the context and task the results belong to.
	ContextID string
	TaskID    string

	// Results are the fulfilled tool calls, keyed by the call id the handler
	// supplied in its [EventClientTool] events.
	Results []ToolResult

	// Tenant is the request's tenant (A2A 1.0), "" when it named none.
	Tenant string
}

ToolResultRequest carries client-tool results back to the handler.

Jump to

Keyboard shortcuts

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