API ReferenceClassesDefaultRequestHandler

title: Server. Default Request Handler

A2A Node SDK - v0.1.0 / Modules / Server / DefaultRequestHandler

Class: DefaultRequestHandler

Server.DefaultRequestHandler

Default implementation of the RequestHandler interface

This class provides the standard implementation of the RequestHandler interface, handling all A2A protocol requests including message sending, task management, push notifications, and agent discovery.

Example

// Create a request handler with available agents
const agents: AgentCard[] = [
  {
    id: 'assistant-agent',
    name: 'Assistant',
    description: 'A helpful assistant',
    capabilities: ['chat', 'answer-questions']
  }
];
 
const requestHandler = new DefaultRequestHandler(agents);
 
// Use in an Express app
app.use('/a2a', requestHandler.router);

Hierarchy

  • DefaultJsonRpcRequestHandler

    DefaultRequestHandler

Implements

Table of contents

Constructors

Properties

Methods

Constructors

constructor

new DefaultRequestHandler(agents?): DefaultRequestHandler

Creates a new DefaultRequestHandler

Parameters

NameTypeDefault valueDescription
agentsAgentCard[][]Array of available agent cards

Returns

DefaultRequestHandler

Overrides

DefaultJsonRpcRequestHandler.constructor

Properties

router

Readonly router: Router

Express router for handling HTTP requests

Implementation of

RequestHandler.router

Overrides

DefaultJsonRpcRequestHandler.router

Methods

buildErrorResponse

buildErrorResponse(id?, error?): JsonRpcResponse

Parameters

NameType
id?string | number
error?any

Returns

JsonRpcResponse

Inherited from

DefaultJsonRpcRequestHandler.buildErrorResponse


buildSuccessResponse

buildSuccessResponse(id?, result?): JsonRpcResponse

Builds a JSON-RPC success response

This method creates a properly formatted JSON-RPC 2.0 success response with the provided result data.

Parameters

NameTypeDescription
id?string | numberRequest ID from the original JSON-RPC request
result?anyResult data to include in the response

Returns

JsonRpcResponse

Properly formatted JSON-RPC success response

Example

// Create a success response
const response = jsonRpcHandler.buildSuccessResponse('request-123', {
  taskId: 'task-456'
});
 
// Send the response
res.json(response);

Inherited from

DefaultJsonRpcRequestHandler.buildSuccessResponse


formatResponse

formatResponse(): Middleware

Creates middleware for formatting responses

This method returns a middleware function that formats responses as JSON-RPC success responses. If the response already has a jsonrpc property, it is left unchanged.

Returns

Middleware

Middleware function that formats responses

Example

// Add response formatting middleware
jsonRpcHandler.use(jsonRpcHandler.formatResponse());

Inherited from

DefaultJsonRpcRequestHandler.formatResponse


handleCancelTask

handleCancelTask(taskId): Promise<void>

Cancels a running task

Attempts to cancel a task that is currently in progress. This will notify the agent to stop processing and update the task status to ‘canceled’.

Parameters

NameTypeDescription
taskIdstringID of the task to cancel

Returns

Promise<void>

Promise resolving when the task is canceled

Throws

If the task is not found or has no agent ID

Example

try {
  await requestHandler.handleCancelTask('task-123');
  console.log('Task canceled successfully');
} catch (error) {
  console.error('Failed to cancel task:', error);
}

Implementation of

RequestHandler.handleCancelTask

Overrides

DefaultJsonRpcRequestHandler.handleCancelTask


handleDiscoverAgents

handleDiscoverAgents(capability?): Promise<AgentCard[]>

Discovers available agents

Returns a list of available agents, optionally filtered by capability.

Parameters

NameTypeDescription
capability?stringOptional capability to filter agents by

Returns

Promise<AgentCard[]>

Promise resolving to an array of agent cards

Example

// Get all agents
const allAgents = await requestHandler.handleDiscoverAgents();
console.log('All agents:', allAgents);
 
// Get agents with a specific capability
const chatAgents = await requestHandler.handleDiscoverAgents('chat');
console.log('Chat agents:', chatAgents);

Implementation of

RequestHandler.handleDiscoverAgents

Overrides

DefaultJsonRpcRequestHandler.handleDiscoverAgents


handleErrors

handleErrors(): Middleware

Creates middleware for handling errors

This method returns a middleware function that catches any errors thrown during request processing and responds with a 500 Internal Server Error and a JSON-RPC error response.

Returns

Middleware

Middleware function that catches and processes errors

Example

// Add error handling middleware
jsonRpcHandler.use(jsonRpcHandler.handleErrors());

Inherited from

DefaultJsonRpcRequestHandler.handleErrors


handleGetPushConfig

handleGetPushConfig(taskId): Promise<PushNotificationConfig>

Gets push notification configuration for a task

Retrieves the current push notification configuration for a specific task.

Parameters

NameTypeDescription
taskIdstringID of the task

Returns

Promise<PushNotificationConfig>

Promise resolving to the push notification configuration

Throws

If the task is not found

Example

const config = await requestHandler.handleGetPushConfig('task-123');
console.log('Push notification config:', config);
console.log('Enabled:', config.enabled);
console.log('Events:', config.events);

Implementation of

RequestHandler.handleGetPushConfig


handleGetTaskStatus

handleGetTaskStatus(taskId): Promise<Task>

Gets the status of a task

Retrieves the current status and details of a task by its ID.

Parameters

NameTypeDescription
taskIdstringID of the task to retrieve

Returns

Promise<Task>

Promise resolving to the task object

Throws

If the task is not found

Example

try {
  const task = await requestHandler.handleGetTaskStatus('task-123');
  console.log('Task status:', task.status);
  console.log('Task result:', task.result);
} catch (error) {
  console.error('Failed to get task:', error);
}

Implementation of

RequestHandler.handleGetTaskStatus

Overrides

DefaultJsonRpcRequestHandler.handleGetTaskStatus


handleJsonRpcCancelTask

handleJsonRpcCancelTask(req, res): Promise<void>

Parameters

NameType
reqRequest<ParamsDictionary, any, any, ParsedQs, Record<string, any>>
resResponse<any, Record<string, any>>

Returns

Promise<void>

Inherited from

DefaultJsonRpcRequestHandler.handleJsonRpcCancelTask


handleJsonRpcDiscoverAgents

handleJsonRpcDiscoverAgents(req, res): Promise<void>

Parameters

NameType
reqRequest<ParamsDictionary, any, any, ParsedQs, Record<string, any>>
resResponse<any, Record<string, any>>

Returns

Promise<void>

Inherited from

DefaultJsonRpcRequestHandler.handleJsonRpcDiscoverAgents


handleJsonRpcGetTaskStatus

handleJsonRpcGetTaskStatus(req, res): Promise<void>

Parameters

NameType
reqRequest<ParamsDictionary, any, any, ParsedQs, Record<string, any>>
resResponse<any, Record<string, any>>

Returns

Promise<void>

Inherited from

DefaultJsonRpcRequestHandler.handleJsonRpcGetTaskStatus


handleJsonRpcSendMessage

handleJsonRpcSendMessage(req, res): Promise<void>

Parameters

NameType
reqRequest<ParamsDictionary, any, any, ParsedQs, Record<string, any>>
resResponse<any, Record<string, any>>

Returns

Promise<void>

Inherited from

DefaultJsonRpcRequestHandler.handleJsonRpcSendMessage


handleJsonRpcStreamMessage

handleJsonRpcStreamMessage(req, res): Promise<void>

Parameters

NameType
reqRequest<ParamsDictionary, any, any, ParsedQs, Record<string, any>>
resResponse<any, Record<string, any>>

Returns

Promise<void>

Inherited from

DefaultJsonRpcRequestHandler.handleJsonRpcStreamMessage


handleSendMessage

handleSendMessage(parts, agentId): Promise<string>

Handles sending a message to an agent

Parameters

NameTypeDescription
parts({ content: string ; format: "plain" | "markdown" ; type: "text" } | { content: string | Uint8Array<ArrayBuffer> ; mimeType: string ; name: string ; size?: number ; type: "file" } | { content: Record<string, any> ; schema?: string ; type: "data" } | { content: string ; format: "plain" ; type: "heartbeat" })[]Message parts to send
agentIdstringID of the target agent

Returns

Promise<string>

Promise resolving to the created task ID

Implementation of

RequestHandler.handleSendMessage

Overrides

DefaultJsonRpcRequestHandler.handleSendMessage


handleSetPushConfig

handleSetPushConfig(taskId, config): Promise<void>

Sets push notification configuration for a task

Configures push notifications for a specific task, including the endpoint to send notifications to and which events to notify about.

Parameters

NameTypeDescription
taskIdstringID of the task
configPushNotificationConfigPush notification configuration

Returns

Promise<void>

Promise resolving when the configuration is set

Throws

If the task is not found

Example

await requestHandler.handleSetPushConfig('task-123', {
  enabled: true,
  endpoint: 'https://webhook.example.com/notifications',
  authToken: 'your-auth-token',
  events: ['taskCompleted', 'taskFailed']
});

Implementation of

RequestHandler.handleSetPushConfig


handleStreamMessage

handleStreamMessage(parts, agentId): AsyncGenerator<{ content: string ; format: "plain" | "markdown" ; type: "text" } | { content: string | Uint8Array<ArrayBuffer> ; mimeType: string ; name: string ; size?: number ; type: "file" } | { content: Record<string, any> ; schema?: string ; type: "data" } | { content: string ; format: "plain" ; type: "heartbeat" }, void, unknown>

Handles streaming a message to an agent

Parameters

NameTypeDescription
parts({ content: string ; format: "plain" | "markdown" ; type: "text" } | { content: string | Uint8Array<ArrayBuffer> ; mimeType: string ; name: string ; size?: number ; type: "file" } | { content: Record<string, any> ; schema?: string ; type: "data" } | { content: string ; format: "plain" ; type: "heartbeat" })[]Message parts to send
agentIdstringID of the target agent

Returns

AsyncGenerator<{ content: string ; format: "plain" | "markdown" ; type: "text" } | { content: string | Uint8Array<ArrayBuffer> ; mimeType: string ; name: string ; size?: number ; type: "file" } | { content: Record<string, any> ; schema?: string ; type: "data" } | { content: string ; format: "plain" ; type: "heartbeat" }, void, unknown>

AsyncGenerator yielding message parts as they are processed

Implementation of

RequestHandler.handleStreamMessage

Overrides

DefaultJsonRpcRequestHandler.handleStreamMessage


handleTaskResubscription

handleTaskResubscription(taskId): AsyncGenerator<{ content: string ; format: "plain" | "markdown" ; type: "text" } | { content: string | Uint8Array<ArrayBuffer> ; mimeType: string ; name: string ; size?: number ; type: "file" } | { content: Record<string, any> ; schema?: string ; type: "data" } | { content: string ; format: "plain" ; type: "heartbeat" }, void, unknown>

Resubscribes to a task’s message stream

Parameters

NameTypeDescription
taskIdstringID of the task

Returns

AsyncGenerator<{ content: string ; format: "plain" | "markdown" ; type: "text" } | { content: string | Uint8Array<ArrayBuffer> ; mimeType: string ; name: string ; size?: number ; type: "file" } | { content: Record<string, any> ; schema?: string ; type: "data" } | { content: string ; format: "plain" ; type: "heartbeat" }, void, unknown>

AsyncGenerator yielding message parts for the task

Implementation of

RequestHandler.handleTaskResubscription

Overrides

DefaultJsonRpcRequestHandler.handleTaskResubscription


normalizeError

normalizeError(err): A2AError

Normalizes errors to A2AError format

Converts various error types to the standardized A2AError format used throughout the A2A protocol.

Parameters

NameTypeDescription
errunknownError to normalize

Returns

A2AError

Normalized A2AError

Example

try {
  // Some operation that might fail
  throw new Error('Something went wrong');
} catch (error) {
  // Normalize the error to A2AError format
  const normalizedError = requestHandler.normalizeError(error);
  console.error('Normalized error:', normalizedError);
  console.error('Error code:', normalizedError.code);
}

Implementation of

RequestHandler.normalizeError

Overrides

DefaultJsonRpcRequestHandler.normalizeError


use

use(middleware): void

Adds middleware to the request handler

This method adds a middleware function to the request handler’s middleware stack. Middleware functions are executed in the order they are added.

Parameters

NameTypeDescription
middlewareMiddlewareMiddleware function to add

Returns

void

Example

// Add error handling middleware
jsonRpcHandler.use(jsonRpcHandler.handleErrors());
 
// Add custom logging middleware
jsonRpcHandler.use(async (req, res, next) => {
  console.log(`${req.method} ${req.path}`);
  await next();
});

Inherited from

DefaultJsonRpcRequestHandler.use


validateRequest

validateRequest(schema): Middleware

Creates middleware for validating request body against a schema

This method returns a middleware function that validates the request body against a Zod schema. If validation fails, it responds with a 400 Bad Request and a JSON-RPC error response.

Parameters

NameTypeDescription
schemaZodType<any, ZodTypeDef, any>Zod schema to validate against

Returns

Middleware

Middleware function that validates requests

Example

// Create a schema for validating sendMessage requests
const sendMessageSchema = z.object({
  jsonrpc: z.literal('2.0'),
  method: z.literal('sendMessage'),
  params: z.object({
    parts: z.array(z.object({
      type: z.string(),
      content: z.string()
    })),
    agentId: z.string()
  }),
  id: z.string().optional()
});
 
// Add validation middleware
jsonRpcHandler.use(jsonRpcHandler.validateRequest(sendMessageSchema));

Inherited from

DefaultJsonRpcRequestHandler.validateRequest