title: Core

A2A Node SDK - v0.1.0 / Modules / Core

Module: Core

Description

Core types, utilities, and validation for the A2A protocol

This package provides the foundational types and utilities for working with the Agent-to-Agent (A2A) protocol. It includes JSON-RPC implementations, protocol-specific types, validation utilities, and error handling.

Table of contents

References

Namespaces

Enumerations

Classes

Interfaces

Type Aliases

Variables

Functions

References

A2AErrorType

Renames and re-exports A2AError

Type Aliases

Artifact

Ƭ Artifact: TypeOf<typeof ArtifactSchema>

Type representing an artifact produced by a task


JsonRpcMessage

Ƭ JsonRpcMessage: TypeOf<typeof JsonRpcMessageSchema>

Base JSON-RPC message type


JsonRpcRequest

Ƭ JsonRpcRequest: TypeOf<typeof JsonRpcRequestSchema>

JSON-RPC request type

This type represents a JSON-RPC 2.0 request message, including the jsonrpc version, request id, method name, and optional parameters.

Example

// Create a JSON-RPC request
const request: JsonRpcRequest = {
  jsonrpc: '2.0',
  id: 'request-123',
  method: 'getTaskStatus',
  params: { taskId: 'task-456' }
};

JsonRpcResponse

Ƭ JsonRpcResponse<T>: TypeOf<typeof JsonRpcResponseSchema> & JsonRpcResponseBase<T>

JSON-RPC response type

This type represents a JSON-RPC 2.0 response message, parameterized by the result type for type safety. It extends the base response interface and is used for standard (non-streaming) JSON-RPC responses.

Example

// Create a JSON-RPC response with a string result
const response: JsonRpcResponse<string> = {
  jsonrpc: '2.0',
  id: 'request-123',
  result: 'task-456'
};
 
// Create a JSON-RPC error response
const errorResponse: JsonRpcResponse<never> = {
  jsonrpc: '2.0',
  id: 'request-123',
  error: {
    code: -32602,
    message: 'Invalid params'
  }
};

Type parameters

NameTypeDescription
TanyResponse result type

JsonRpcStreamResponse

Ƭ JsonRpcStreamResponse<T>: TypeOf<typeof JsonRpcStreamResponseSchema> & JsonRpcResponseBase<T>

JSON-RPC streaming response type

This type represents a JSON-RPC 2.0 streaming response message, parameterized by the data type for type safety. It’s used for responses that stream data over time, such as task message streams.

Example

// Create a JSON-RPC streaming response with a MessagePart
const streamResponse: JsonRpcStreamResponse<MessagePart> = {
  jsonrpc: '2.0',
  id: 'request-123',
  result: {
    type: 'text',
    content: 'Hello, world!',
    format: 'markdown'
  }
};

Type parameters

NameTypeDescription
TanyResponse data type

MessagePart

Ƭ MessagePart: TypeOf<typeof MessagePartSchema>

Type representing a part of a message


TaskState

Ƭ TaskState: TypeOf<typeof TaskStateSchema>

Type representing the possible states of a task

Variables

A2AErrorSchema

Const A2AErrorSchema: ZodObject<{ code: ZodNumber ; data: ZodOptional<ZodRecord<ZodString, ZodAny>> ; message: ZodString }, "strip", ZodTypeAny, { code: number ; data?: Record<string, any> ; message: string }, { code: number ; data?: Record<string, any> ; message: string }>

Schema defining standardized errors in the A2A protocol

Remarks

Error codes follow JSON-RPC error code conventions


ArtifactSchema

Const ArtifactSchema: ZodObject<{ content: ZodRecord<ZodString, ZodAny> ; createdAt: ZodString ; id: ZodString ; type: ZodEnum<["text", "file", "data"]> ; updatedAt: ZodString }, "strip", ZodTypeAny, { content: Record<string, any> ; createdAt: string ; id: string ; type: "text" | "file" | "data" ; updatedAt: string }, { content: Record<string, any> ; createdAt: string ; id: string ; type: "text" | "file" | "data" ; updatedAt: string }>

Schema defining artifacts produced during task execution

Remarks

Artifacts are persistent outputs from tasks that can be referenced later


ERROR_CODES

Const ERROR_CODES: Object

Standard error codes for the A2A protocol

These error codes are standardized across all A2A SDK implementations (JavaScript, Python, etc.) to ensure consistent error handling.

Error code ranges:

  • Task errors: -32000 to -32049
  • Queue errors: -32050 to -32099

Example

// Check for a specific error code
if (error.code === ERROR_CODES.TASK_NOT_FOUND) {
  console.log('The requested task does not exist');
}

Type declaration

NameTypeDescription
INVALID_TASK_STATE-32010Error code for invalid task state transitions (-32010)
NO_QUEUE-32051Error code for when a required queue doesn’t exist (-32051)
QUEUE_EXISTS-32050Error code for when a queue already exists (-32050)
TASK_ALREADY_COMPLETED-32012Error code for attempting to modify a completed task (-32012)
TASK_CANCELED-32013Error code for attempting to work with a canceled task (-32013)
TASK_FAILED-32014Error code for a task that failed to complete (-32014)
TASK_NOT_FOUND-32011Error code for task not found (-32011)

JsonRpcMessageSchema

Const JsonRpcMessageSchema: ZodObject<{ id: ZodOptional<ZodUnion<[ZodString, ZodNumber]>> ; jsonrpc: ZodLiteral<"2.0"> }, "strip", ZodTypeAny, { id?: string | number ; jsonrpc: "2.0" }, { id?: string | number ; jsonrpc: "2.0" }>

Base JSON-RPC 2.0 message schema

This schema defines the base structure for all JSON-RPC 2.0 messages, including the required jsonrpc field and optional id field. All JSON-RPC requests and responses extend this base schema.

See

https://www.jsonrpc.org/specification

Example

// Validate a JSON-RPC message
const message = {
  jsonrpc: '2.0',
  id: 'request-123'
};
 
const result = JsonRpcMessageSchema.safeParse(message);
if (result.success) {
  console.log('Valid JSON-RPC message');
} else {
  console.error('Invalid JSON-RPC message:', result.error);
}

JsonRpcRequestSchema

Const JsonRpcRequestSchema: ZodObject<{ id: ZodOptional<ZodUnion<[ZodString, ZodNumber]>> ; jsonrpc: ZodLiteral<"2.0"> } & { method: ZodString ; params: ZodOptional<ZodRecord<ZodString, ZodAny>> }, "strip", ZodTypeAny, { id?: string | number ; jsonrpc: "2.0" ; method: string ; params?: Record<string, any> }, { id?: string | number ; jsonrpc: "2.0" ; method: string ; params?: Record<string, any> }>

JSON-RPC request schema

This schema defines the structure for JSON-RPC 2.0 request messages, extending the base message schema with required method and optional params fields. The method field specifies the operation to be performed, and the params field contains the arguments for that operation.

Example

// Create and validate a JSON-RPC request
const request = {
  jsonrpc: '2.0',
  id: 'request-123',
  method: 'sendMessage',
  params: {
    agentId: 'assistant-agent',
    parts: [{ type: 'text', content: 'Hello, world!' }]
  }
};
 
const result = JsonRpcRequestSchema.safeParse(request);
if (result.success) {
  console.log('Valid JSON-RPC request');
} else {
  console.error('Invalid JSON-RPC request:', result.error);
}

JsonRpcResponseSchema

Const JsonRpcResponseSchema: ZodObject<{ id: ZodOptional<ZodUnion<[ZodString, ZodNumber]>> ; jsonrpc: ZodLiteral<"2.0"> } & { error: ZodOptional<ZodObject<{ code: ZodNumber ; data: ZodOptional<ZodAny> ; message: ZodString }, "strip", ZodTypeAny, { code: number ; data?: any ; message: string }, { code: number ; data?: any ; message: string }>> ; result: ZodOptional<ZodAny> }, "strip", ZodTypeAny, { error?: { code: number ; data?: any ; message: string } ; id?: string | number ; jsonrpc: "2.0" ; result?: any }, { error?: { code: number ; data?: any ; message: string } ; id?: string | number ; jsonrpc: "2.0" ; result?: any }>

JSON-RPC response schema

This schema defines the structure for JSON-RPC 2.0 response messages, extending the base message schema with optional result and error fields. A successful response includes a result field, while an error response includes an error field with code, message, and optional data properties.

Example

// Create and validate a successful JSON-RPC response
const successResponse = {
  jsonrpc: '2.0',
  id: 'request-123',
  result: { taskId: 'task-456' }
};
 
// Create and validate an error JSON-RPC response
const errorResponse = {
  jsonrpc: '2.0',
  id: 'request-123',
  error: {
    code: -32602,
    message: 'Invalid params',
    data: { details: 'Missing required field: agentId' }
  }
};

JsonRpcStreamResponseSchema

Const JsonRpcStreamResponseSchema: ZodObject<{ id: ZodOptional<ZodUnion<[ZodString, ZodNumber]>> ; jsonrpc: ZodLiteral<"2.0"> } & { data: ZodOptional<ZodAny> ; event: ZodOptional<ZodString> ; result: ZodOptional<ZodAny> }, "strip", ZodTypeAny, { data?: any ; event?: string ; id?: string | number ; jsonrpc: "2.0" ; result?: any }, { data?: any ; event?: string ; id?: string | number ; jsonrpc: "2.0" ; result?: any }>

JSON-RPC streaming response schema

Example

{
 *   jsonrpc: '2.0',
 *   event: 'update',
 *   data: { progress: 50 }
 * }

MessagePartSchema

Const MessagePartSchema: ZodDiscriminatedUnion<"type", [ZodObject<{ content: ZodString ; format: ZodDefault<ZodEnum<["plain", "markdown"]>> ; type: ZodLiteral<"text"> }, "strip", ZodTypeAny, { content: string ; format: "plain" | "markdown" ; type: "text" }, { content: string ; format?: "plain" | "markdown" ; type: "text" }>, ZodObject<{ content: ZodUnion<[ZodString, ZodType<Uint8Array<ArrayBuffer>, ZodTypeDef, Uint8Array<ArrayBuffer>>]> ; mimeType: ZodString ; name: ZodString ; size: ZodOptional<ZodNumber> ; type: ZodLiteral<"file"> }, "strip", ZodTypeAny, { content: string | Uint8Array<ArrayBuffer> ; mimeType: string ; name: string ; size?: number ; type: "file" }, { content: string | Uint8Array<ArrayBuffer> ; mimeType: string ; name: string ; size?: number ; type: "file" }>, ZodObject<{ content: ZodRecord<ZodString, ZodAny> ; schema: ZodOptional<ZodString> ; type: ZodLiteral<"data"> }, "strip", ZodTypeAny, { content: Record<string, any> ; schema?: string ; type: "data" }, { content: Record<string, any> ; schema?: string ; type: "data" }>, ZodObject<{ content: ZodString ; format: ZodDefault<ZodLiteral<"plain">> ; type: ZodLiteral<"heartbeat"> }, "strip", ZodTypeAny, { content: string ; format: "plain" ; type: "heartbeat" }, { content: string ; format?: "plain" ; type: "heartbeat" }>]>

Schema defining the different types of message parts in the A2A protocol

Remarks

Uses a discriminated union based on the ‘type’ field


TaskStateSchema

Const TaskStateSchema: ZodEnum<["submitted", "working", "input_required", "completed", "failed", "canceled"]>

Schema defining the possible states of a task in the A2A protocol

Remarks

This is used for validation with Zod


schemas

Const schemas: Object

Collection of all schema definitions for A2A protocol objects

This object provides access to all the Zod schemas defined in this module, allowing them to be used directly for validation or type inference.

Example

// Use a schema directly for validation
const result = schemas.Message.safeParse(data);
 
// Create a type from a schema
type MessageType = z.infer<typeof schemas.Message>;

Type declaration

NameType
A2AErrorZodObject<{ code: ZodNumber ; data: ZodOptional<ZodRecord<ZodString, ZodAny>> ; message: ZodString }, "strip", ZodTypeAny, { code: number ; data?: Record<string, any> ; message: string }, { code: number ; data?: Record<string, any> ; message: string }>
AgentCardZodType<AgentCard, ZodTypeDef, AgentCard>
ArtifactZodObject<{ content: ZodRecord<ZodString, ZodAny> ; createdAt: ZodString ; id: ZodString ; type: ZodEnum<["text", "file", "data"]> ; updatedAt: ZodString }, "strip", ZodTypeAny, { content: Record<string, any> ; createdAt: string ; id: string ; type: "text" | "file" | "data" ; updatedAt: string }, { content: Record<string, any> ; createdAt: string ; id: string ; type: "text" | "file" | "data" ; updatedAt: string }>
DiscoverRequestZodType<DiscoverRequest, ZodTypeDef, DiscoverRequest>
DiscoverResponseZodType<DiscoverResponse, ZodTypeDef, DiscoverResponse>
MessageZodType<Message, ZodTypeDef, Message>
MessagePartZodDiscriminatedUnion<"type", [ZodObject<{ content: ZodString ; format: ZodDefault<ZodEnum<["plain", "markdown"]>> ; type: ZodLiteral<"text"> }, "strip", ZodTypeAny, { content: string ; format: "plain" | "markdown" ; type: "text" }, { content: string ; format?: "plain" | "markdown" ; type: "text" }>, ZodObject<{ content: ZodUnion<[ZodString, ZodType<Uint8Array<ArrayBuffer>, ZodTypeDef, Uint8Array<ArrayBuffer>>]> ; mimeType: ZodString ; name: ZodString ; size: ZodOptional<ZodNumber> ; type: ZodLiteral<"file"> }, "strip", ZodTypeAny, { content: string | Uint8Array<ArrayBuffer> ; mimeType: string ; name: string ; size?: number ; type: "file" }, { content: string | Uint8Array<ArrayBuffer> ; mimeType: string ; name: string ; size?: number ; type: "file" }>, ZodObject<{ content: ZodRecord<ZodString, ZodAny> ; schema: ZodOptional<ZodString> ; type: ZodLiteral<"data"> }, "strip", ZodTypeAny, { content: Record<string, any> ; schema?: string ; type: "data" }, { content: Record<string, any> ; schema?: string ; type: "data" }>, ZodObject<{ content: ZodString ; format: ZodDefault<ZodLiteral<"plain">> ; type: ZodLiteral<"heartbeat"> }, "strip", ZodTypeAny, { content: string ; format: "plain" ; type: "heartbeat" }, { content: string ; format?: "plain" ; type: "heartbeat" }>]>
MessageSendConfigurationZodType<MessageSendConfiguration, ZodTypeDef, MessageSendConfiguration>
PushNotificationConfigZodType<PushNotificationConfig, ZodTypeDef, PushNotificationConfig>
TaskZodType<Task, ZodTypeDef, Task>
TaskTransitionZodType<TaskTransition, ZodTypeDef, TaskTransition>

Functions

Trace

Trace(nameOrOptions?): any

Method decorator that automatically creates a span for the decorated method

This decorator instruments methods with OpenTelemetry tracing, creating spans that track method execution, timing, and errors. It supports both synchronous and asynchronous methods.

Parameters

NameTypeDescription
nameOrOptions?string | TraceOptionsOptional span name or configuration object

Returns

any

Example

class UserService {
  // Basic usage
  @Trace()
  async getUser(id: string) {
    // Method implementation
  }
 
  // With custom span name
  @Trace('FetchUserDetails')
  async getUserDetails(id: string) {
    // Method implementation
  }
 
  // With options object
  @Trace({ name: 'UserAuthentication' })
  async authenticateUser(username: string, password: string) {
    // Method implementation
  }
}

TraceClass

TraceClass(name?): ClassDecorator

Class decorator to automatically trace all methods in a class

This decorator applies the Trace decorator to all methods in a class, making it easy to instrument an entire class without decorating each method individually.

Parameters

NameTypeDescription
name?stringOptional custom name prefix for the spans (defaults to class name)

Returns

ClassDecorator

A class decorator

Example

// Basic usage - traces all methods with ClassName.methodName
@TraceClass()
class UserService {
  async getUser(id: string) { 
    // Method implementation
  }
  async updateUser(id: string, data: any) { 
    // Method implementation
  }
}
 
// With custom name prefix
@TraceClass('Users')
class UserService {
  // Will be traced as 'Users.getUser'
  async getUser(id: string) { 
    // Method implementation
  }
}

agentCardToJson

agentCardToJson(agent): Record<string, any>

Converts an AgentCard to a JSON-serializable object

This function converts an AgentCard instance to a plain JavaScript object that can be safely serialized to JSON. It creates a deep copy of the agent’s capabilities array to prevent modifications to the original object.

Parameters

NameTypeDescription
agentAgentCardThe AgentCard to convert

Returns

Record<string, any>

A JSON-serializable representation of the agent

Example

const agent: AgentCard = {
  id: 'assistant-agent',
  name: 'Assistant',
  capabilities: ['chat', 'answer-questions'],
  endpoint: 'https://example.com/agents/assistant'
};
 
const json = agentCardToJson(agent);
const serialized = JSON.stringify(json);

createTransition

createTransition(from, to, reason?): TaskTransition

Creates a new task transition record

This function creates a transition record that documents a change in task state. Transition records include the starting state, ending state, timestamp, and an optional reason for the transition.

Parameters

NameTypeDescription
from"submitted" | "working" | "input_required" | "completed" | "failed" | "canceled"Starting task state
to"submitted" | "working" | "input_required" | "completed" | "failed" | "canceled"Ending task state
reason?stringOptional reason for the transition

Returns

TaskTransition

A new transition object with timestamp

Example

// Create a transition record when a task is completed
const transition = createTransition('working', 'completed');
console.log(transition);
// Output: {
//   from: 'working',
//   to: 'completed',
//   timestamp: '2023-05-26T12:34:56.789Z'
// }
 
// Create a transition record with a reason
const failedTransition = createTransition(
  'working',
  'failed',
  'API request timeout'
);
console.log(failedTransition);
// Output: {
//   from: 'working',
//   to: 'failed',
//   timestamp: '2023-05-26T12:35:12.345Z',
//   reason: 'API request timeout'
// }

createValidator

createValidator<T>(schema): Object

Creates a reusable validator from a JSON Schema definition

This function converts a JSON Schema to a Zod validator and returns an object with a validate function and the schema. The validate function can be used to validate data against the schema multiple times without recreating the validator.

Type parameters

Name
T

Parameters

NameTypeDescription
schemaRecord<string, any>JSON Schema definition

Returns

Object

An object with a validate function and the Zod schema

NameType
schemaZodObject<Record<string, ZodTypeAny>, "strip", ZodTypeAny, , >
validate(data: unknown) => SafeParseReturnType<unknown, T>

Example

// Create a reusable validator
const userValidator = createValidator<User>({
  type: 'object',
  properties: {
    name: { type: 'string' },
    email: { type: 'string', format: 'email' },
    age: { type: 'number', minimum: 18 }
  },
  required: ['name', 'email']
});
 
// Validate multiple users
const user1Result = userValidator.validate({
  name: 'John Doe',
  email: 'john@example.com',
  age: 25
});
 
const user2Result = userValidator.validate({
  name: 'Jane Smith',
  email: 'jane@example.com',
  age: 30
});
 
// You can also access the Zod schema directly
type UserType = z.infer<typeof userValidator.schema>;

deserializeArtifact

deserializeArtifact(data): Artifact

Deserializes an artifact from a JSON string

This function converts a JSON string representation back into an Artifact object. It handles error cases by throwing appropriate A2AError instances.

Parameters

NameTypeDescription
datastringJSON encoded artifact data

Returns

Artifact

Deserialized Artifact object

Throws

If deserialization fails

Example

try {
  const artifactJson = '{"id":"artifact-123","type":"text","content":"This is a text artifact"}';
  const artifact = deserializeArtifact(artifactJson);
  console.log('Artifact type:', artifact.type);
  console.log('Artifact content:', artifact.content);
} catch (error) {
  console.error('Failed to deserialize:', error);
}

extractTextContent

extractTextContent(parts): string

Extracts and combines text content from message parts

This function filters message parts to include only those with type ‘text’, extracts their content, and combines them with double newlines between each part. It’s useful for getting a plain text representation of a message that might include multiple types of content.

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 process

Returns

string

Combined text content from all text parts, separated by double newlines

Example

const messageParts = [
  { type: 'text', content: 'Hello, world!' },
  { type: 'file', content: 'base64-encoded-content', name: 'image.png', mimeType: 'image/png' },
  { type: 'text', content: 'This is a second text part.' }
];
 
const textContent = extractTextContent(messageParts);
console.log(textContent);
// Output:
// Hello, world!
//
// This is a second text part.

formatValidationError

formatValidationError(error): string

Formats a Zod validation error into a human-readable string

This function takes a Zod error object and converts it into a string representation, with each issue formatted as “path: message” and joined with semicolons.

Parameters

NameTypeDescription
errorZodError<any>The Zod error to format

Returns

string

A formatted error string

Example

const result = validateTask(invalidTask);
 
if (!result.success) {
  const errorMessage = formatValidationError(result.error);
  console.error('Validation failed:', errorMessage);
  // Example output: "name: Required; status: Invalid enum value"
}

fromJsonRpcResponse

fromJsonRpcResponse<T>(response): T

Extracts the result from a JSON-RPC response

This function extracts the result from a JSON-RPC response, throwing an error if the response contains an error. It’s a type-safe way to handle JSON-RPC responses in the A2A protocol.

Type parameters

NameDescription
TThe expected type of the result

Parameters

NameTypeDescription
responseJsonRpcResponseThe JSON-RPC response to extract the result from

Returns

T

The result from the JSON-RPC response, cast to type T

Throws

Error if the response contains an error

Example

try {
  // Extract agents from a discover response
  const agents = fromJsonRpcResponse<AgentCard[]>(response);
  console.log(`Found ${agents.length} agents`);
} catch (error) {
  console.error('Error in JSON-RPC response:', error.message);
}

isAgentCard

isAgentCard(data): data is AgentCard

Checks if the provided data is a valid AgentCard

Parameters

NameTypeDescription
dataunknownThe data to check

Returns

data is AgentCard

True if the data is a valid AgentCard, false otherwise

Example

const data = getAgentFromSomewhere();
 
if (isAgentCard(data)) {
  // TypeScript now knows that data is an AgentCard
  console.log('Agent capabilities:', data.capabilities);
}

isMessage

isMessage(data): data is Message

Checks if the provided data is a valid Message

Parameters

NameTypeDescription
dataunknownThe data to check

Returns

data is Message

True if the data is a valid Message, false otherwise

Example

const data = { parts: [{ type: 'text', content: 'Hello' }] };
 
if (isMessage(data)) {
  // TypeScript now knows that data is a Message
  console.log('Message parts:', data.parts.length);
}

isPushNotificationConfig

isPushNotificationConfig(data): data is PushNotificationConfig

Checks if the provided data is a valid PushNotificationConfig

Parameters

NameTypeDescription
dataunknownThe data to check

Returns

data is PushNotificationConfig

True if the data is a valid PushNotificationConfig, false otherwise

Example

const data = getConfigFromSomewhere();
 
if (isPushNotificationConfig(data)) {
  // TypeScript now knows that data is a PushNotificationConfig
  console.log('Push notifications enabled:', data.enabled);
}

isTask

isTask(data): data is Task

Checks if the provided data is a valid Task

Parameters

NameTypeDescription
dataunknownThe data to check

Returns

data is Task

True if the data is a valid Task, false otherwise

Example

const data = getTaskFromSomewhere();
 
if (isTask(data)) {
  // TypeScript now knows that data is a Task
  console.log('Task status:', data.status);
}

jsonToAgentCard

jsonToAgentCard(json): AgentCard

Converts a JSON object to an AgentCard

This function converts a plain JavaScript object (typically parsed from JSON) into an AgentCard instance. It validates that the required fields are present and ensures the capabilities array is properly formatted.

Parameters

NameTypeDescription
jsonRecord<string, any>The JSON object to convert

Returns

AgentCard

An AgentCard instance

Example

// Parse JSON from an API response
const responseData = JSON.parse(responseText);
 
// Convert to an AgentCard
const agent = jsonToAgentCard(responseData);
console.log(`Agent: ${agent.name} (${agent.id})`);
console.log(`Capabilities: ${agent.capabilities.join(', ')}`);

jsonToTask

jsonToTask(json): Task

Converts a JSON object to a Task

This function converts a plain JavaScript object (typically parsed from JSON) into a Task instance. It validates that the required fields are present and sets default values for missing fields. By default, new tasks are created with a ‘submitted’ status.

Parameters

NameTypeDescription
jsonRecord<string, any>The JSON object to convert

Returns

Task

A Task instance

Example

// Parse JSON from an API response
const responseData = JSON.parse(responseText);
 
// Convert to a Task
const task = jsonToTask(responseData);
console.log(`Task: ${task.name} (${task.id})`);
console.log(`Status: ${task.status}`);
console.log(`Created: ${new Date(task.createdAt).toLocaleString()}`);

serializeArtifact

serializeArtifact(artifact): string

Serializes an artifact to a JSON string

This function converts an Artifact object to a JSON string representation that can be stored or transmitted. It handles error cases by throwing appropriate A2AError instances.

Parameters

NameTypeDescription
artifactObjectArtifact object to serialize
artifact.contentRecord<string, any>The actual content of the artifact
artifact.createdAtstringISO timestamp when the artifact was created
artifact.idstringUnique identifier for the artifact
artifact.type"text" | "file" | "data"The type of content this artifact contains
artifact.updatedAtstringISO timestamp when the artifact was last updated

Returns

string

JSON string representation of the artifact

Throws

If serialization fails

Example

const artifact: Artifact = {
  id: 'artifact-123',
  type: 'text',
  content: 'This is a text artifact',
  metadata: { created: new Date().toISOString() }
};
 
try {
  const serialized = serializeArtifact(artifact);
  console.log('Serialized artifact:', serialized);
} catch (error) {
  console.error('Failed to serialize:', error);
}

taskToJson

taskToJson(task): Record<string, any>

Converts a Task to a JSON-serializable object

This function converts a Task instance to a plain JavaScript object that can be safely serialized to JSON. It creates deep copies of the task’s input and output schemas to prevent modifications to the original object.

Parameters

NameTypeDescription
taskTaskThe Task to convert

Returns

Record<string, any>

A JSON-serializable representation of the task

Example

const task: Task = {
  id: 'task-123',
  name: 'Answer Question',
  status: 'completed',
  createdAt: new Date().toISOString(),
  updatedAt: new Date().toISOString(),
  inputSchema: { type: 'object', properties: { question: { type: 'string' } } },
  outputSchema: { type: 'object', properties: { answer: { type: 'string' } } }
};
 
const json = taskToJson(task);
const serialized = JSON.stringify(json);

toJsonRpcRequest

toJsonRpcRequest(request): JsonRpcRequest

Converts an A2A protocol discover request to a JSON-RPC request

This function transforms an A2A protocol discover request into a standard JSON-RPC 2.0 request format, ensuring compatibility with JSON-RPC servers.

Parameters

NameTypeDescription
requestDiscoverRequestThe A2A protocol discover request to convert

Returns

JsonRpcRequest

A JSON-RPC 2.0 formatted request

Example

const discoverRequest: DiscoverRequest = {
  id: '123',
  method: 'discoverAgents',
  params: { capability: 'chat' }
};
 
const jsonRpcRequest = toJsonRpcRequest(discoverRequest);
// {
//   jsonrpc: '2.0',
//   id: '123',
//   method: 'discoverAgents',
//   params: { capability: 'chat' }
// }

validateAgentCard

validateAgentCard(data): SafeParseReturnType<unknown, AgentCard>

Validates an agent card object against the AgentCard schema

Parameters

NameTypeDescription
dataunknownThe data to validate

Returns

SafeParseReturnType<unknown, AgentCard>

A SafeParseReturnType containing either the validated AgentCard or validation errors

Example

const result = validateAgentCard({
  id: '123e4567-e89b-12d3-a456-426614174000',
  name: 'Weather Agent',
  capabilities: ['weather-forecasting', 'location-search'],
  endpoint: 'https://example.com/agents/weather'
});
 
if (result.success) {
  // Use the validated agent card
  console.log('Valid agent card:', result.data);
} else {
  // Handle validation errors
  console.error('Invalid agent card:', result.error);
}

validateArtifact

validateArtifact(artifact): boolean

Validates an artifact’s structure and content

This function checks that an artifact has the required fields and that the type is one of the supported values (‘text’, ‘file’, or ‘data’). It throws an appropriate error if validation fails.

Parameters

NameTypeDescription
artifactObjectArtifact object to validate
artifact.contentRecord<string, any>The actual content of the artifact
artifact.createdAtstringISO timestamp when the artifact was created
artifact.idstringUnique identifier for the artifact
artifact.type"text" | "file" | "data"The type of content this artifact contains
artifact.updatedAtstringISO timestamp when the artifact was last updated

Returns

boolean

True if the artifact is valid

Throws

If validation fails, with specific error codes

Example

try {
  // Valid artifact
  const valid = validateArtifact({
    id: 'artifact-123',
    type: 'file',
    content: 'base64-encoded-content',
    metadata: { filename: 'document.pdf', mimeType: 'application/pdf' }
  });
  console.log('Artifact is valid:', valid);
  
  // This would throw an error
  validateArtifact({
    id: 'invalid-artifact',
    type: 'unsupported-type', // Invalid type
    content: 'some-content'
  });
} catch (error) {
  console.error('Validation failed:', error);
}

validateDiscoverRequest

validateDiscoverRequest(data): SafeParseReturnType<unknown, DiscoverRequest>

Validates a discover request against the DiscoverRequest schema

Parameters

NameTypeDescription
dataunknownThe data to validate

Returns

SafeParseReturnType<unknown, DiscoverRequest>

A SafeParseReturnType containing either the validated DiscoverRequest or validation errors

Example

const result = validateDiscoverRequest({
  id: '1',
  method: 'discover',
  params: { capability: 'weather-forecasting' },
  jsonrpc: '2.0'
});
 
if (result.success) {
  // Use the validated request
  console.log('Valid discover request:', result.data);
} else {
  // Handle validation errors
  console.error('Invalid discover request:', result.error);
}

validateDiscoverResponse

validateDiscoverResponse(data): SafeParseReturnType<unknown, DiscoverResponse>

Validates a discover response against the DiscoverResponse schema

Parameters

NameTypeDescription
dataunknownThe data to validate

Returns

SafeParseReturnType<unknown, DiscoverResponse>

A SafeParseReturnType containing either the validated DiscoverResponse or validation errors

Example

const result = validateDiscoverResponse({
  id: '1',
  result: [
    {
      id: '123e4567-e89b-12d3-a456-426614174000',
      name: 'Weather Agent',
      capabilities: ['weather-forecasting'],
      endpoint: 'https://example.com/agents/weather'
    }
  ]
});
 
if (result.success) {
  // Use the validated response
  console.log('Valid discover response:', result.data);
} else {
  // Handle validation errors
  console.error('Invalid discover response:', result.error);
}

validateMessage

validateMessage(data): SafeParseReturnType<unknown, Message>

Validates a message object against the Message schema

Parameters

NameTypeDescription
dataunknownThe data to validate

Returns

SafeParseReturnType<unknown, Message>

A SafeParseReturnType containing either the validated Message or validation errors

Example

const result = validateMessage({
  parts: [{ type: 'text', content: 'Hello, world!' }]
});
 
if (result.success) {
  // Use the validated message
  console.log('Valid message:', result.data);
} else {
  // Handle validation errors
  console.error('Invalid message:', result.error);
}

validateMessageParts

validateMessageParts(parts): void

Validates message parts for compliance with the A2A protocol

This function checks that message parts are present, have content, and use supported types. It throws appropriate errors if validation fails, which can be caught and handled by the caller.

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 validate

Returns

void

Throws

If validation fails, with specific error codes

Example

try {
  // Valid message parts
  validateMessageParts([
    { type: 'text', content: 'Hello, world!' },
    { type: 'file', content: 'base64-encoded-content', name: 'document.pdf', mimeType: 'application/pdf' }
  ]);
  console.log('Message parts are valid');
  
  // This would throw an error
  validateMessageParts([
    { type: 'unknown', content: 'some content' } // Invalid type
  ]);
} catch (error) {
  console.error('Validation failed:', error);
}

validatePushNotificationConfig

validatePushNotificationConfig(data): SafeParseReturnType<unknown, PushNotificationConfig>

Validates a push notification configuration against the PushNotificationConfig schema

Parameters

NameTypeDescription
dataunknownThe data to validate

Returns

SafeParseReturnType<unknown, PushNotificationConfig>

A SafeParseReturnType containing either the validated PushNotificationConfig or validation errors

Example

const result = validatePushNotificationConfig({
  enabled: true,
  endpoint: 'https://example.com/webhooks/a2a',
  authToken: 'secret-token',
  events: ['taskCompleted', 'taskFailed']
});
 
if (result.success) {
  // Use the validated config
  console.log('Valid push config:', result.data);
} else {
  // Handle validation errors
  console.error('Invalid push config:', result.error);
}

validateTask

validateTask(data): SafeParseReturnType<unknown, Task>

Validates a task object against the Task schema

Parameters

NameTypeDescription
dataunknownThe data to validate

Returns

SafeParseReturnType<unknown, Task>

A SafeParseReturnType containing either the validated Task or validation errors

Example

const result = validateTask({
  id: '123e4567-e89b-12d3-a456-426614174000',
  name: 'Process Data',
  status: 'submitted',
  createdAt: new Date().toISOString(),
  updatedAt: new Date().toISOString()
});
 
if (result.success) {
  // Use the validated task
  console.log('Valid task:', result.data);
} else {
  // Handle validation errors
  console.error('Invalid task:', result.error);
}

validateTransition

validateTransition(current, next): void

Validates that a task state transition is allowed

This function checks if a proposed state transition follows the rules of the task state machine. It throws an error if the transition is not allowed.

Parameters

NameTypeDescription
current"submitted" | "working" | "input_required" | "completed" | "failed" | "canceled"Current task state
next"submitted" | "working" | "input_required" | "completed" | "failed" | "canceled"Proposed next state

Returns

void

Throws

If the transition is invalid

Example

try {
  // Valid transition
  validateTransition('submitted', 'working');
  console.log('Transition is valid');
  
  // Invalid transition
  validateTransition('completed', 'working');
} catch (error) {
  console.error('Invalid transition:', error.message);
  // Output: Invalid transition: Invalid transition from completed to working
}

validateWithSchema

validateWithSchema<T>(schema, data): SafeParseReturnType<unknown, T>

Validates data against a JSON Schema definition

This function converts a JSON Schema to a Zod validator and uses it to validate the provided data. It returns a SafeParseReturnType that contains either the validated data or validation errors.

Type parameters

Name
T

Parameters

NameTypeDescription
schemaRecord<string, any>JSON Schema definition
dataunknownData to validate against the schema

Returns

SafeParseReturnType<unknown, T>

A SafeParseReturnType containing either the validated data or validation errors

Example

const userSchema = {
  type: 'object',
  properties: {
    name: { type: 'string' },
    age: { type: 'number', minimum: 0 }
  },
  required: ['name']
};
 
const result = validateWithSchema<User>(userSchema, {
  name: 'John Doe',
  age: 30
});
 
if (result.success) {
  // Use the validated data
  console.log('Valid user:', result.data);
} else {
  // Handle validation errors
  console.error('Invalid user:', result.error);
}