A2A Protocol
A2A Java Sample

Clone Code

git clone https://github.com/google-a2a/a2a-samples
cd a2a-samples/samples/java

This project is a Java implementation example of the Agent-to-Agent (A2A) protocol, providing complete client and server SDKs, along with an AI-powered translation service demonstration application.

Project Architecture

This project uses a Maven multi-module architecture, containing the following three core modules:

samples/java/
├── model/          # A2A Protocol Data Models
├── server/         # A2A Server SDK & Translation Service
├── client/         # A2A Client SDK & Example Code
└── pom.xml         # Parent Maven Configuration File

Module Details

🎯 Model Module (model/)

Core data models for the A2A protocol, providing complete data structures for JSON-RPC 2.0 and A2A protocol:

  • Message Models: Message, Part, TextPart, Artifact
  • Task Models: Task, TaskStatus, TaskState
  • Agent Models: AgentCard, AgentCapabilities, AgentSkill
  • JSON-RPC Models: JSONRPCRequest, JSONRPCResponse, JSONRPCError
  • Event Models: TaskStatusUpdateEvent, TaskArtifactUpdateEvent

🚀 Server Module (server/)

Spring Boot-based A2A server SDK, integrated with Spring AI framework:

  • Core Components:

    • A2AServer: Main server class managing agent behavior
    • A2AController: REST controller implementing A2A protocol endpoints
    • TaskHandler: Task processing interface
    • A2AServerConfiguration: AI translation bot configuration
  • Key Features:

    • Complete JSON-RPC 2.0 support
    • Agent card publishing (/.well-known/agent-card)
    • Task management (send, query, cancel)
    • Streaming response support (Server-Sent Events)
    • Spring AI integration supporting OpenAI and other models

📱 Client Module (client/)

Pure Java A2A client SDK with translation client examples:

  • Core Components:

    • A2AClient: Main client class handling all A2A operations
    • StreamingEventListener: Streaming event listener interface
    • A2AClientException: A2A-specific exception handling
    • A2AClientExample: Complete translation client example
  • Key Features:

    • JSON-RPC 2.0 client implementation
    • Agent discovery and capability querying
    • Synchronous/asynchronous task operations
    • Streaming response handling
    • Connection pooling and error recovery

Core Functionality Implementation

🤖 AI Translation Service

The project implements an intelligent translation agent supporting multi-language translation:

Translation Logic:

  • Chinese → English
  • English → Chinese
  • Other languages → English

Technical Features:

  • Based on Spring AI ChatClient
  • Supports OpenAI, Azure OpenAI, and other models
  • Context-aware natural language translation
  • Real-time streaming responses

🔄 A2A Protocol Implementation

Complete implementation of A2A protocol specifications:

Core Operations:

  • tasks/send: Send task messages
  • tasks/get: Query task status
  • tasks/cancel: Cancel task execution

Protocol Features:

  • JSON-RPC 2.0 communication
  • Agent capability discovery
  • Task status tracking
  • Streaming event push
  • Standardized error codes

📡 Communication Mechanisms

Synchronous Communication:

  • HTTP POST /a2a - Standard JSON-RPC requests
  • HTTP GET /.well-known/agent-card - Agent information retrieval

Streaming Communication:

  • HTTP POST /a2a/stream - Server-Sent Events
  • Real-time task status updates
  • Automatic reconnection and error recovery

How to Run

Requirements

  • Java: 17 or higher

Step 1: Compile the Project

Execute compilation in the project root directory:

cd samples/java
./mvnw clean install -DskipTests

Step 2: Configure Environment Variables

Set AI model-related environment variables (required for translation functionality):

# OpenAI Configuration
export OPENAI_API_KEY="your-openai-api-key"
export OPENAI_BASE_URL="https://api.openai.com"
export OPENAI_CHAT_MODEL="gpt-4o"

# Or GCP OpenAI Configuration
export OPENAI_API_KEY="your-gcp-api-key"
export OPENAI_BASE_URL="https://{location}-aiplatform.googleapis.com/v1/projects/{project_id}/locations/{location}/endpoints/openapi"
export OPENAI_CHAT_MODEL="gemini-2.5-pro-preview-05-06"

OpenRouter Configuration

export OPENAI_API_KEY="sk-or-v1-"
export OPENAI_BASE_URL="https://openrouter.ai/api"
export OPENAI_CHAT_MODEL="openai/gpt-4o-2024-11-20"

Pay attention to OPENAI_BASE_URL, there is no /v1 in the URL.

Step 3: Start the Translation Server

Start the A2A translation server:

cd server
../mvnw spring-boot:run

The server will start at http://localhost:8080, providing the following endpoints:

  • http://localhost:8080/.well-known/agent-card - Agent information
  • http://localhost:8080/a2a - A2A protocol endpoint
  • http://localhost:8080/a2a/stream - Streaming endpoint

Validate the Agent Card:

Step 4: Run the Translation Client

In a new terminal window, run the client example:

cd client
../mvnw exec:java -Dexec.mainClass="com.google.a2a.client.A2AClientExample"

Sequence Diagram

The following sequence diagram illustrates the complete interaction flow of the A2A Java sample application, based on the A2AClientExample.java:

sequenceDiagram
    participant Example as A2AClientExample
    participant Client as A2AClient
    participant Server as A2A Server<br/>(localhost:8080)
    
    Note over Example,Server: A2A Java Sample Sequence Diagram
    
    %% 1. Initialize Client
    Example->>Client: new A2AClient("http://localhost:8080")
    activate Client
    
    %% 2. Get Agent Card
    Example->>Client: getAgentCard()
    Client->>Server: GET /.well-known/agent-card
    Server-->>Client: AgentCard (name, description, version, skills)
    Client-->>Example: AgentCard
    Note over Example: Print agent information
    
    %% 3. French to Chinese Translation
    Example->>Client: sendTask(frenchToChineseParams)
    Note right of Example: TextPart: "Bonjour le monde!<br/>Comment allez-vous?"
    Client->>Server: POST /a2a<br/>JSON-RPC: tasks/send
    Server-->>Client: Task (id, status, history)
    Client-->>Example: JSONRPCResponse<Task>
    Note over Example: Print translation result
    
    %% 4. Chinese to English Translation
    Example->>Client: sendTask(chineseParams)
    Note right of Example: TextPart: "你好,世界!<br/>欢迎使用AI翻译机器人。"
    Client->>Server: POST /a2a<br/>JSON-RPC: tasks/send
    Server-->>Client: Task (id, status, history)
    Client-->>Example: JSONRPCResponse<Task>
    Note over Example: Print translation result
    
    %% 5. Streaming Translation
    Example->>Client: sendTaskStreaming(frenchParams, StreamingEventListener)
    Note right of Example: TextPart: "Bonjour le monde!<br/>Comment allez-vous?"
    Client->>Server: POST /a2a/stream<br/>Server-Sent Events
    activate Server
    
    loop Streaming Response
        Server-->>Client: SSE Event (translation progress)
        Client-->>Example: onEvent(event)
        Note over Example: Print real-time translation events
    end
    
    Server-->>Client: SSE Complete
    deactivate Server
    Client-->>Example: onComplete()
    Note over Example: Streaming translation completed
    
    %% 6. Query Task Status
    Example->>Client: getTask(queryParams)
    Note right of Example: Query French translation task status
    Client->>Server: POST /a2a<br/>JSON-RPC: tasks/get
    Server-->>Client: Task (updated status)
    Client-->>Example: JSONRPCResponse<Task>
    Note over Example: Print task status
    
    %% 7. Send Task to be Canceled
    Example->>Client: sendTask(cancelParams)
    Note right of Example: TextPart: "Diese Übersetzung<br/>wird abgebrochen." (German)
    Client->>Server: POST /a2a<br/>JSON-RPC: tasks/send
    Server-->>Client: Task (id, status)
    Client-->>Example: JSONRPCResponse<Task>
    
    %% 8. Cancel Task
    Example->>Client: cancelTask(cancelTaskParams)
    Client->>Server: POST /a2a<br/>JSON-RPC: tasks/cancel
    Server-->>Client: Task (canceled status)
    Client-->>Example: JSONRPCResponse<Task>
    Note over Example: Print cancellation result
    
    deactivate Client
    Note over Example,Server: Example program execution completed

Key Interaction Patterns

The sequence diagram demonstrates the following core interaction patterns:

  1. Client Initialization: Creating an A2AClient instance connected to the local server
  2. Agent Discovery: Retrieving agent information via the /.well-known/agent-card endpoint
  3. Multi-language Translation Examples:
    • French → Chinese translation
    • Chinese → English translation
    • German → English streaming translation
  4. Task Management:
    • Querying task status
    • Canceling task execution

Communication Mechanisms

  • Synchronous Translation: Using POST /a2a endpoint with JSON-RPC requests
  • Streaming Translation: Using POST /a2a/stream endpoint with Server-Sent Events (SSE)
  • Status Queries: Using tasks/get method to check task execution status
  • Task Cancellation: Using tasks/cancel method to cancel running tasks

API Usage Examples

Get Agent Information

curl -X GET http://localhost:8080/.well-known/agent-card \
  -H "Accept: application/json"

Send Translation Task

curl -X POST http://localhost:8080/a2a \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "id": "request-1",
    "method": "tasks/send",
    "params": {
      "id": "translation-task-1",
      "message": {
        "messageId": "msg-1",
        "kind": "message",
        "role": "user",
        "parts": [
          {
            "kind": "text",
            "text": "Hello, world!"
          }
        ]
      }
    }
  }'

Streaming Translation

curl -X POST http://localhost:8080/a2a/stream \
  -H "Content-Type: application/json" \
  -H "Accept: text/event-stream" \
  -d '{
    "jsonrpc": "2.0",
    "id": "stream-request-1",
    "method": "tasks/send",
    "params": {
      "id": "streaming-translation-task",
      "message": {
        "messageId": "stream-msg-1",
        "kind": "message",
        "role": "user",
        "parts": [
          {
            "kind": "text",
            "text": "Hello world!"
          }
        ]
      }
    }
  }'