// Copyright 2025 The A2A Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package a2asrv import ( "context" "errors" "fmt" "iter" "log/slog" "time" "github.com/a2aproject/a2a-go/v2/a2a" "github.com/a2aproject/a2a-go/v2/a2aevent" "github.com/a2aproject/a2a-go/v2/a2asrv/eventqueue" "github.com/a2aproject/a2a-go/v2/a2asrv/limiter" "github.com/a2aproject/a2a-go/v2/a2asrv/push" "github.com/a2aproject/a2a-go/v2/a2asrv/taskstore" "github.com/a2aproject/a2a-go/v2/a2asrv/workqueue" "github.com/a2aproject/a2a-go/v2/internal/taskexec" ) // ErrAgentInactivityTimeout is the cancellation cause set on an agent's // execution context when no events are written to the event pipe for the // duration configured via [WithAgentInactivityTimeout]. Callers can detect // this condition with errors.Is. var ErrAgentInactivityTimeout = taskexec.ErrAgentInactivityTimeout var defaultMaterializer = taskstore.NewFullUpdateMaterializer(a2aevent.ApplyShallowUpdate) // RequestHandler defines a transport-agnostic interface for handling incoming A2A requests. type RequestHandler interface { // GetTask handles the 'GetTask' protocol method. GetTask(context.Context, *a2a.GetTaskRequest) (*a2a.Task, error) // ListTasks handles the 'ListTasks' protocol method. ListTasks(context.Context, *a2a.ListTasksRequest) (*a2a.ListTasksResponse, error) // CancelTask handles the 'CancelTask' protocol method. CancelTask(context.Context, *a2a.CancelTaskRequest) (*a2a.Task, error) // SendMessage handles the 'SendMessage' protocol method (non-streaming). SendMessage(context.Context, *a2a.SendMessageRequest) (a2a.SendMessageResult, error) // SubscribeToTask handles the `SubscribeToTask` protocol method. SubscribeToTask(context.Context, *a2a.SubscribeToTaskRequest) iter.Seq2[a2a.Event, error] // SendStreamingMessage handles the 'SendStreamingMessage' protocol method (streaming). SendStreamingMessage(context.Context, *a2a.SendMessageRequest) iter.Seq2[a2a.Event, error] // GetTaskPushConfig handles the `GetTaskPushNotificationConfig` protocol method. GetTaskPushConfig(context.Context, *a2a.GetTaskPushConfigRequest) (*a2a.PushConfig, error) // ListTaskPushConfigs handles the `ListTaskPushNotificationConfigs` protocol method. ListTaskPushConfigs(context.Context, *a2a.ListTaskPushConfigRequest) (*a2a.ListTaskPushConfigResponse, error) // CreateTaskPushConfig handles the `CreateTaskPushNotificationConfig` protocol method. CreateTaskPushConfig(context.Context, *a2a.PushConfig) (*a2a.PushConfig, error) // DeleteTaskPushConfig handles the `DeleteTaskPushNotificationConfig` protocol method. DeleteTaskPushConfig(context.Context, *a2a.DeleteTaskPushConfigRequest) error // GetExtendedAgentCard handles the `GetExtendedAgentCard` protocol method. GetExtendedAgentCard(context.Context, *a2a.GetExtendedAgentCardRequest) (*a2a.AgentCard, error) } // Implements a2asrv.RequestHandler. type defaultRequestHandler struct { agentExecutor AgentExecutor execManager taskexec.Manager panicHandler taskexec.PanicHandlerFn pushSender push.Sender queueManager eventqueue.Manager concurrencyConfig limiter.ConcurrencyConfig pushConfigStore push.ConfigStore taskStore taskstore.Store materializer taskstore.UpdateMaterializer workQueue workqueue.Queue ctxCodec ContextCodec reqContextInterceptors []ExecutorContextInterceptor agentInactivityTimeout time.Duration authenticatedCardProducer ExtendedAgentCardProducer } var _ RequestHandler = (*defaultRequestHandler)(nil) // RequestHandlerOption can be used to customize the default [RequestHandler] implementation behavior. type RequestHandlerOption func(*InterceptedHandler, *defaultRequestHandler) // WithCapabilityChecks sets the provided capabilities for the request handler. // // Deprecated: Use [WithCallInterceptors] with [NewAgentCardEnforcer] instead. func WithCapabilityChecks(capabilities *a2a.AgentCapabilities) RequestHandlerOption { if capabilities == nil { return func(ih *InterceptedHandler, h *defaultRequestHandler) {} } interceptor, err := NewAgentCardEnforcer(&a2a.AgentCard{Capabilities: *capabilities}) if err != nil { panic(fmt.Errorf("failed to create agent card enforcer: %w", err)) } return WithCallInterceptors(interceptor) } // WithLogger sets a custom logger. Request scoped parameters will be attached to this logger // on method invocations. Any injected dependency will be able to access the logger using // [github.com/a2aproject/a2a-go/v2/log] package-level functions. // If not provided, defaults to slog.Default(). func WithLogger(logger *slog.Logger) RequestHandlerOption { return func(ih *InterceptedHandler, h *defaultRequestHandler) { ih.Logger = logger } } // WithEventQueueManager overrides eventqueue.Manager with custom implementation func WithEventQueueManager(manager eventqueue.Manager) RequestHandlerOption { return func(ih *InterceptedHandler, h *defaultRequestHandler) { h.queueManager = manager } } // WithExecutionPanicHandler allows to set a custom handler for panics occurred during execution. func WithExecutionPanicHandler(handler func(r any) error) RequestHandlerOption { return func(ih *InterceptedHandler, h *defaultRequestHandler) { h.panicHandler = handler } } // WithAgentInactivityTimeout configures the maximum time the server will wait // for the next event from an agent's producer before terminating its execution. // The timer is reset whenever the agent writes an event to the event pipe. // When the timeout fires the producer and consumer contexts are canceled with // [ErrAgentInactivityTimeout] as the cause, and the task is finalized via the // existing failure path. // // A value of 0 (default) or negative disables the inactivity watcher and // preserves prior behavior. The timeout applies in both single-process and // cluster modes. func WithAgentInactivityTimeout(d time.Duration) RequestHandlerOption { return func(ih *InterceptedHandler, h *defaultRequestHandler) { h.agentInactivityTimeout = d } } // WithConcurrencyConfig allows to set limits on the number of concurrent executions. func WithConcurrencyConfig(config limiter.ConcurrencyConfig) RequestHandlerOption { return func(ih *InterceptedHandler, h *defaultRequestHandler) { h.concurrencyConfig = config } } // WithPushNotifications adds support for push notifications. If dependencies are not provided // push-related methods will be returning a2a.ErrPushNotificationNotSupported, func WithPushNotifications(store push.ConfigStore, sender push.Sender) RequestHandlerOption { return func(ih *InterceptedHandler, h *defaultRequestHandler) { h.pushConfigStore = store h.pushSender = sender } } // WithTaskStore overrides TaskStore with a custom implementation. If not provided, // default to an in-memory implementation. func WithTaskStore(store taskstore.Store) RequestHandlerOption { return func(ih *InterceptedHandler, h *defaultRequestHandler) { h.taskStore = store } } // WithUpdateMaterializer overrides the [taskstore.UpdateMaterializer] which computes the task state passed to [taskstore.Store.Update] // during agent execution. By default the full task state is kept in memory while an agent is running. // Custom implementations allow stores which derive the task state from [taskstore.UpdateRequest.Event] // to avoid the cost of materialization. func WithUpdateMaterializer(m taskstore.UpdateMaterializer) RequestHandlerOption { return func(ih *InterceptedHandler, h *defaultRequestHandler) { h.materializer = m } } // ContextCodec is used for propagating context values through [workqueue.Queue]. type ContextCodec = taskexec.ContextCodec // ClusterConfig groups the necessary dependencies for A2A cluster mode operation. type ClusterConfig struct { QueueManager eventqueue.Manager WorkQueue workqueue.Queue TaskStore taskstore.Store ContextCodec ContextCodec } // WithClusterMode is an experimental feature where work queue is used to distribute tasks across multiple instances. func WithClusterMode(config ClusterConfig) RequestHandlerOption { return func(ih *InterceptedHandler, h *defaultRequestHandler) { h.workQueue = config.WorkQueue h.taskStore = config.TaskStore h.queueManager = config.QueueManager h.ctxCodec = config.ContextCodec } } // NewHandler creates a new request handler. func NewHandler(executor AgentExecutor, options ...RequestHandlerOption) RequestHandler { h := &defaultRequestHandler{agentExecutor: executor} ih := &InterceptedHandler{Handler: h, Logger: slog.Default()} for _, option := range options { option(ih, h) } for _, interceptor := range ih.Interceptors { if enforcer, ok := interceptor.(*agentCardEnforcer); ok && enforcer.capabilities.PushNotifications && (h.pushConfigStore == nil || h.pushSender == nil) { panic("push notifications are enforced and supported but push config store or sender are not configured") } } materializer := h.materializer if materializer == nil { materializer = defaultMaterializer } if h.workQueue == nil && h.taskStore == nil { h.taskStore = taskstore.NewInMemory(&taskstore.InMemoryStoreConfig{ Authenticator: NewTaskStoreAuthenticator(), }) } if h.taskStore != nil { h.taskStore = wrapWithPlugins(h.taskStore, ih.plugins, Plugin.WrapTaskStore) } pushDelivery := push.NewDeliveryHandler(h.pushSender) if pushDelivery != nil { pushDelivery = wrapWithPlugins(pushDelivery, ih.plugins, Plugin.WrapPushDelivery) } agent, cleaners := wrapExecutor(h.agentExecutor, ih.plugins) execFactory := &factory{ agent: agent, cleaners: cleaners, taskStore: h.taskStore, pushDelivery: pushDelivery, pushConfigStore: h.pushConfigStore, interceptors: h.reqContextInterceptors, materializer: materializer, // TODO(yarolegovich): there should be a flag to specify whether workqueue implementation supports // retries or not to be able to opt-out of extra GetTask RPC taskRetrySupported: h.workQueue != nil, } if h.workQueue != nil { if h.taskStore == nil || h.queueManager == nil { panic("TaskStore and QueueManager must be provided for cluster mode") } h.execManager = taskexec.NewDistributedManager(taskexec.DistributedManagerConfig{ WorkQueue: h.workQueue, TaskStore: h.taskStore, QueueManager: h.queueManager, ConcurrencyConfig: h.concurrencyConfig, Factory: execFactory, ContextCodec: &callCtxCodec{AttrCodec: h.ctxCodec}, PanicHandler: h.panicHandler, AgentInactivityTimeout: h.agentInactivityTimeout, }) } else { if h.queueManager == nil { h.queueManager = eventqueue.NewInMemoryManager() } h.execManager = taskexec.NewLocalManager(taskexec.LocalManagerConfig{ QueueManager: h.queueManager, ConcurrencyConfig: h.concurrencyConfig, Factory: execFactory, TaskStore: h.taskStore, PanicHandler: h.panicHandler, AgentInactivityTimeout: h.agentInactivityTimeout, }) } return ih } // GetTask implements RequestHandler. func (h *defaultRequestHandler) GetTask(ctx context.Context, req *a2a.GetTaskRequest) (*a2a.Task, error) { taskID := req.ID if taskID == "" { return nil, fmt.Errorf("missing TaskID: %w", a2a.ErrInvalidParams) } storedTask, err := h.taskStore.Get(ctx, taskID) if err != nil { return nil, fmt.Errorf("failed to get task: %w", err) } task := trimTaskHistory(storedTask.Task, req.HistoryLength) return task, nil } // ListTasks implements RequestHandler. func (h *defaultRequestHandler) ListTasks(ctx context.Context, req *a2a.ListTasksRequest) (*a2a.ListTasksResponse, error) { listResponse, err := h.taskStore.List(ctx, req) if err != nil { return nil, fmt.Errorf("failed to list tasks: %w", err) } return listResponse, nil } // CancelTask implements RequestHandler. func (h *defaultRequestHandler) CancelTask(ctx context.Context, req *a2a.CancelTaskRequest) (*a2a.Task, error) { if req == nil || req.ID == "" { return nil, a2a.ErrInvalidParams } response, err := h.execManager.Cancel(ctx, req) if err != nil { return nil, fmt.Errorf("failed to cancel: %w", err) } return response, nil } // SendMessage implements RequestHandler. func (h *defaultRequestHandler) SendMessage(ctx context.Context, req *a2a.SendMessageRequest) (a2a.SendMessageResult, error) { result, err := h.sendMessage(ctx, req) if err != nil { return nil, err } if task, ok := result.(*a2a.Task); ok && req.Config != nil { return trimTaskHistory(task, req.Config.HistoryLength), nil } return result, nil } // SendStreamingMessage implements RequestHandler. func (h *defaultRequestHandler) SendStreamingMessage(ctx context.Context, req *a2a.SendMessageRequest) iter.Seq2[a2a.Event, error] { return func(yield func(a2a.Event, error) bool) { subscription, err := h.handleSendMessage(ctx, req) if err != nil { yield(nil, err) return } for ev, err := range subscription.Events(ctx) { if task, ok := ev.(*a2a.Task); ok && req.Config != nil { ev = trimTaskHistory(task, req.Config.HistoryLength) } if !yield(ev, err) { return } } } } // SubscribeToTask implements RequestHandler. func (h *defaultRequestHandler) SubscribeToTask(ctx context.Context, req *a2a.SubscribeToTaskRequest) iter.Seq2[a2a.Event, error] { return func(yield func(a2a.Event, error) bool) { if req == nil { yield(nil, a2a.ErrInvalidParams) return } subscription, err := h.execManager.Resubscribe(ctx, req.ID) if err != nil { storedTask, getErr := h.taskStore.Get(ctx, req.ID) if getErr != nil || storedTask == nil { yield(nil, fmt.Errorf("%w: %w", a2a.ErrTaskNotFound, err)) return } if storedTask.Task.Status.State.Terminal() { yield(nil, fmt.Errorf("task in a terminal state %q: %w", storedTask.Task.Status.State, a2a.ErrUnsupportedOperation)) return } yield(storedTask.Task, nil) return } for ev, err := range subscription.Events(ctx) { if !yield(ev, err) { return } } } } func (h *defaultRequestHandler) sendMessage(ctx context.Context, req *a2a.SendMessageRequest) (a2a.SendMessageResult, error) { subscription, err := h.handleSendMessage(ctx, req) if err != nil { return nil, err } var lastEvent a2a.Event for event, err := range subscription.Events(ctx) { if err != nil { return nil, err } if taskID, interrupt := shouldInterruptNonStreaming(req, event); interrupt { storedTask, err := h.taskStore.Get(ctx, taskID) if err != nil { return nil, fmt.Errorf("failed to load task on event processing interrupt: %w", err) } return storedTask.Task, nil } lastEvent = event } if res, ok := lastEvent.(a2a.SendMessageResult); ok { return res, nil } if lastEvent == nil { return nil, fmt.Errorf("execution finished without producing any events: %w", a2a.ErrInvalidAgentResponse) } task, err := h.taskStore.Get(ctx, lastEvent.TaskInfo().TaskID) if err != nil { return nil, fmt.Errorf("failed to load result after execution finished: %w", err) } return task.Task, nil } func (h *defaultRequestHandler) handleSendMessage(ctx context.Context, req *a2a.SendMessageRequest) (taskexec.Subscription, error) { switch { case req == nil: return nil, fmt.Errorf("SendMessageRequest is required: %w", a2a.ErrInvalidParams) case req.Message == nil: return nil, fmt.Errorf("message is required: %w", a2a.ErrInvalidParams) case req.Message.ID == "": return nil, fmt.Errorf("message ID is required: %w", a2a.ErrInvalidParams) case len(req.Message.Parts) == 0: return nil, fmt.Errorf("message parts is required: %w", a2a.ErrInvalidParams) case req.Message.Role == "": return nil, fmt.Errorf("message role is required: %w", a2a.ErrInvalidParams) } return h.execManager.Execute(ctx, req) } // GetTaskPushConfig implements RequestHandler. func (h *defaultRequestHandler) GetTaskPushConfig(ctx context.Context, req *a2a.GetTaskPushConfigRequest) (*a2a.PushConfig, error) { if err := checkPushNotificationConfigs(h); err != nil { return nil, err } // Authorize: only the task owner can read its push configs. if _, err := h.taskStore.Get(ctx, req.TaskID); err != nil { return nil, fmt.Errorf("failed to get push config: %w", err) } config, err := h.pushConfigStore.Get(ctx, req.TaskID, req.ID) if errors.Is(err, push.ErrPushConfigNotFound) { return nil, fmt.Errorf("%w: %w", err, a2a.ErrTaskNotFound) } if err != nil { return nil, fmt.Errorf("failed to get push config: %w", err) } if config == nil { return nil, fmt.Errorf("%w: %w", push.ErrPushConfigNotFound, a2a.ErrTaskNotFound) } return config, nil } // ListTaskPushConfigs implements RequestHandler. func (h *defaultRequestHandler) ListTaskPushConfigs(ctx context.Context, req *a2a.ListTaskPushConfigRequest) (*a2a.ListTaskPushConfigResponse, error) { if err := checkPushNotificationConfigs(h); err != nil { return nil, err } // Authorize: only the task owner can list its push configs. if _, err := h.taskStore.Get(ctx, req.TaskID); err != nil { return nil, fmt.Errorf("failed to list push configs: %w", err) } configs, err := h.pushConfigStore.List(ctx, req.TaskID) if err != nil { return nil, fmt.Errorf("failed to list push configs: %w", err) } if configs == nil { return &a2a.ListTaskPushConfigResponse{Configs: []*a2a.PushConfig{}}, nil } return &a2a.ListTaskPushConfigResponse{Configs: configs}, nil } // CreateTaskPushConfig implements RequestHandler. func (h *defaultRequestHandler) CreateTaskPushConfig(ctx context.Context, req *a2a.PushConfig) (*a2a.PushConfig, error) { if err := checkPushNotificationConfigs(h); err != nil { return nil, err } // Authorize: only the task owner can create push configs for it. if _, err := h.taskStore.Get(ctx, req.TaskID); err != nil { return nil, fmt.Errorf("failed to create push config: %w", err) } saved, err := h.pushConfigStore.Save(ctx, req.TaskID, req) if err != nil { return nil, fmt.Errorf("failed to create push config: %w", err) } return saved, nil } // DeleteTaskPushConfig implements RequestHandler. func (h *defaultRequestHandler) DeleteTaskPushConfig(ctx context.Context, req *a2a.DeleteTaskPushConfigRequest) error { if err := checkPushNotificationConfigs(h); err != nil { return err } // Authorize: only the task owner can delete its push configs. if _, err := h.taskStore.Get(ctx, req.TaskID); err != nil { return fmt.Errorf("failed to delete push config: %w", err) } return h.pushConfigStore.Delete(ctx, req.TaskID, req.ID) } // GetExtendedAgentCard implements RequestHandler. func (h *defaultRequestHandler) GetExtendedAgentCard(ctx context.Context, req *a2a.GetExtendedAgentCardRequest) (*a2a.AgentCard, error) { if h.authenticatedCardProducer == nil { return nil, a2a.ErrExtendedCardNotConfigured } return h.authenticatedCardProducer.ExtendedCard(ctx, req) } func shouldInterruptNonStreaming(req *a2a.SendMessageRequest, event a2a.Event) (a2a.TaskID, bool) { // ReturnImmediately clients receive a result on the first task event if req.Config != nil && req.Config.ReturnImmediately { if _, ok := event.(*a2a.Message); ok { return "", false } taskInfo := event.TaskInfo() return taskInfo.TaskID, true } // Non-streaming clients need to be notified when auth is required switch v := event.(type) { case *a2a.Task: return v.ID, v.Status.State == a2a.TaskStateAuthRequired case *a2a.TaskStatusUpdateEvent: return v.TaskID, v.Status.State == a2a.TaskStateAuthRequired } return "", false } func checkPushNotificationConfigs(h *defaultRequestHandler) error { if h.pushConfigStore == nil || h.pushSender == nil { return a2a.ErrPushNotificationNotSupported } return nil } func trimTaskHistory(task *a2a.Task, historyLength *int) *a2a.Task { if task == nil || historyLength == nil { return task } hl := *historyLength if hl >= len(task.History) { return task } trimmed := *task if hl <= 0 { trimmed.History = []*a2a.Message{} } else if hl < len(task.History) { trimmed.History = task.History[len(task.History)-hl:] } return &trimmed }