Repository navigation
Install and Integrate A2A Protocol (@a2a-js/sdk) #804
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
ngoiyaeric
wants to merge
5
commits into
main
Choose a base branch
from
feat/a2a-protocol-integration-2202132869284846478
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
8e204d2
feat: install and integrate Agent-to-Agent (A2A) protocol
ngoiyaeric 0f8499a
feat: install and integrate Agent-to-Agent (A2A) protocol and resolve…
ngoiyaeric 9ef577e
fix: address A2A integration review feedback
1b66b96
feat: enable real-time token streaming for A2A client tool
ngoiyaeric 79f33be
fix A2A SDK build type errors
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,91 @@ | ||
| # Agent-to-Agent (A2A) Protocol Configuration & Usage Guide | ||
|
|
||
| This repository integrates the official **Agent-to-Agent (A2A) Protocol** ([a2a-protocol.org](https://a2a-protocol.org)) using [`@a2a-js/sdk`](https://github.com/a2aproject/a2a-js). QCX-Terra can act both as an **A2A Client** (invoking specialized remote agents on other systems) and as an **A2A Server** (allowing external agentic systems to discover and send tasks to QCX-Terra). | ||
|
|
||
| --- | ||
|
|
||
| ## 1. Environment Configuration | ||
|
|
||
| ### Remote Agents (`A2A_REMOTE_AGENTS`) | ||
|
|
||
| Configure remote A2A agents that QCX-Terra can communicate with using the `A2A_REMOTE_AGENTS` environment variable in `.env.local` or your runtime environment: | ||
|
|
||
| ```env | ||
| A2A_REMOTE_AGENTS='[ | ||
| { | ||
| "name": "weather-agent", | ||
| "url": "https://weather.example.com", | ||
| "apiKey": "sk_live_12345" | ||
| }, | ||
| { | ||
| "name": "satellite-imagery-agent", | ||
| "url": "https://sat.example.com" | ||
| } | ||
| ]' | ||
| ``` | ||
|
|
||
| - **`name`**: Friendly identifier for the remote agent (used by internal agents for routing). | ||
| - **`url`**: The base HTTP/HTTPS URL of the remote agent serving `/.well-known/agent-card.json`. | ||
| - **`apiKey`** *(optional)*: Bearer token or authorization token injected into the `Authorization` request header. | ||
|
|
||
| --- | ||
|
|
||
| ## 2. A2A Client Capabilities | ||
|
|
||
| QCX-Terra's multi-agent system (`lib/agents/researcher.tsx`) includes the `a2aQueryTool` tool. | ||
|
|
||
| When a user asks QCX-Terra to consult or delegate sub-tasks to external agents (e.g., *"Ask the weather agent for the atmospheric forecast in Oregon"* or *"Delegate satellite task to https://sat.example.com"*), the agent automatically uses `a2aQueryTool` to: | ||
|
|
||
| 1. Resolve the remote agent's URL and credentials from `A2A_REMOTE_AGENTS` or prompt argument. | ||
| 2. Fetch the remote agent card via `@a2a-js/sdk` `ClientFactory`. | ||
| 3. Negotiate transport (JSON-RPC or HTTP REST). | ||
| 4. Stream or send the request message and return the synthesized result to the user interface. | ||
|
|
||
| --- | ||
|
|
||
| ## 3. A2A Server Endpoints | ||
|
|
||
| QCX-Terra exposes compliant A2A v1.0 server endpoints: | ||
|
|
||
| ### Agent Card Discovery | ||
| - **Endpoint**: `GET /.well-known/agent-card.json` | ||
| - **Description**: Returns QCX-Terra's agent card, detailing supported interfaces (`JSON-RPC`, `HTTP+REST`), streaming capabilities, and available skills (`geospatial-analysis`, `satellite-embeddings`, `planet-computer`). | ||
|
|
||
| ### Message & Task Execution Endpoint | ||
| - **Endpoint**: `POST /api/a2a` | ||
| - **Description**: Handles inbound A2A v1.0 JSON-RPC requests (`SendMessage`, `SendStreamingMessage`, `GetTask`, `CancelTask`, etc.). | ||
|
|
||
| #### Example Inbound JSON-RPC Request: | ||
| ```bash | ||
| curl -X POST http://localhost:3000/api/a2a \ | ||
| -H "Content-Type: application/json" \ | ||
| -d '{ | ||
| "jsonrpc": "2.0", | ||
| "id": 1, | ||
| "method": "SendMessage", | ||
| "params": { | ||
| "message": { | ||
| "messageId": "msg-001", | ||
| "role": "ROLE_USER", | ||
| "parts": [ | ||
| { | ||
| "content": { | ||
| "$case": "text", | ||
| "value": "Query latest geospatial analysis for target region." | ||
| } | ||
| } | ||
| ] | ||
| } | ||
| } | ||
| }' | ||
| ``` | ||
|
|
||
| --- | ||
|
|
||
| ## 4. Testing & Verification | ||
|
|
||
| Run the A2A integration test suite using Bun: | ||
|
|
||
| ```bash | ||
| bun test tests-unit/a2a.test.ts | ||
| ``` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,65 @@ | ||
| import { NextResponse } from 'next/server' | ||
|
|
||
| export async function GET(request: Request) { | ||
| const host = request.headers.get('host') || 'localhost:3000' | ||
| const protocol = request.headers.get('x-forwarded-proto') || 'http' | ||
| const baseUrl = `${protocol}://${host}` | ||
|
|
||
| const agentCard = { | ||
| name: 'QCX-Terra Agent', | ||
| description: | ||
| 'Environment-aware planetary computer platform offering geospatial analysis, remote sensing satellite imagery processing, and multi-agent exploration.', | ||
| supportedInterfaces: [ | ||
| { | ||
| protocolBinding: 'JSON-RPC', | ||
| protocolVersion: '1.0', | ||
| url: `${baseUrl}/api/a2a` | ||
| }, | ||
| { | ||
| protocolBinding: 'HTTP+JSON/REST', | ||
| protocolVersion: '1.0', | ||
| url: `${baseUrl}/api/a2a` | ||
| } | ||
| ], | ||
| capabilities: { | ||
| streaming: true, | ||
| pushNotifications: false | ||
| }, | ||
| skills: [ | ||
| { | ||
| id: 'geospatial-analysis', | ||
| name: 'Geospatial Analysis & Mapping', | ||
| description: 'Perform spatial queries, location search, routing, and map feature analysis.' | ||
| }, | ||
| { | ||
| id: 'satellite-embeddings', | ||
| name: 'Satellite Image Vector Search', | ||
| description: 'Natural language and vector similarity search over satellite and aerial imagery.' | ||
| }, | ||
| { | ||
| id: 'planet-computer', | ||
| name: 'Planetary Computing & Forecasting', | ||
| description: 'Provide climate forecasting, planetary model exploration, and environmental insights.' | ||
| } | ||
| ] | ||
| } | ||
|
|
||
| return NextResponse.json(agentCard, { | ||
| headers: { | ||
| 'Access-Control-Allow-Origin': '*', | ||
| 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS', | ||
| 'Access-Control-Allow-Headers': 'Content-Type, Authorization, A2A-Version' | ||
| } | ||
| }) | ||
| } | ||
|
|
||
| export async function OPTIONS() { | ||
| return new Response(null, { | ||
| status: 204, | ||
| headers: { | ||
| 'Access-Control-Allow-Origin': '*', | ||
| 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS', | ||
| 'Access-Control-Allow-Headers': 'Content-Type, Authorization, A2A-Version' | ||
| } | ||
| }) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,177 @@ | ||
| import { NextResponse } from 'next/server' | ||
| import { | ||
| DefaultRequestHandler, | ||
| JsonRpcTransportHandler, | ||
| InMemoryTaskStore, | ||
| AgentEvent, | ||
| RequestContext, | ||
| ExecutionEventBus, | ||
| ServerCallContext | ||
| } from '@a2a-js/sdk/server' | ||
| import { Role, TaskState } from '@a2a-js/sdk' | ||
|
|
||
| const agentCard = { | ||
| name: 'QCX-Terra Agent', | ||
| description: | ||
| 'Environment-aware planetary computer platform offering geospatial analysis, remote sensing satellite imagery processing, and multi-agent exploration.', | ||
| supportedInterfaces: [ | ||
| { | ||
| protocolBinding: 'JSON-RPC', | ||
| protocolVersion: '1.0', | ||
| url: '/api/a2a', | ||
| tenant: '' | ||
| } | ||
| ], | ||
| provider: undefined, | ||
| version: '1.0.0', | ||
| capabilities: { | ||
| streaming: true, | ||
| pushNotifications: false, | ||
| extensions: [] | ||
| }, | ||
| securitySchemes: {}, | ||
| securityRequirements: [], | ||
| defaultInputModes: ['text/plain'], | ||
| defaultOutputModes: ['text/plain'], | ||
| skills: [], | ||
| signatures: [] | ||
| } | ||
|
|
||
| const taskStore = new InMemoryTaskStore() | ||
|
|
||
| const agentExecutor = { | ||
| async execute(requestContext: RequestContext, eventBus: ExecutionEventBus) { | ||
| const userMessage = requestContext.userMessage | ||
| let textPart = '' | ||
| if (userMessage.parts) { | ||
| for (const p of userMessage.parts) { | ||
| if (p.content?.$case === 'text') { | ||
| textPart += p.content.value | ||
| } | ||
| } | ||
| } | ||
|
|
||
| eventBus.publish( | ||
| AgentEvent.task({ | ||
| id: requestContext.taskId, | ||
| contextId: requestContext.contextId, | ||
| status: { | ||
| state: TaskState.TASK_STATE_WORKING, | ||
| message: undefined, | ||
| timestamp: undefined | ||
| }, | ||
| artifacts: [], | ||
| history: [userMessage], | ||
| metadata: undefined | ||
| }) | ||
| ) | ||
|
|
||
| const responseText = `QCX-Terra Agent received your request: "${textPart}". Processed via A2A Protocol.` | ||
|
|
||
| eventBus.publish( | ||
| AgentEvent.message({ | ||
| messageId: `msg-${Date.now()}`, | ||
| taskId: requestContext.taskId, | ||
| contextId: requestContext.contextId, | ||
| role: Role.ROLE_AGENT, | ||
| parts: [ | ||
| { | ||
| content: { | ||
| $case: 'text', | ||
| value: responseText | ||
| }, | ||
| metadata: undefined, | ||
| filename: '', | ||
| mediaType: 'text/plain' | ||
| } | ||
| ], | ||
| metadata: undefined, | ||
| extensions: [], | ||
| referenceTaskIds: [] | ||
| }) | ||
| ) | ||
|
|
||
| eventBus.publish( | ||
| AgentEvent.statusUpdate({ | ||
| taskId: requestContext.taskId, | ||
| contextId: requestContext.contextId, | ||
| status: { | ||
| state: TaskState.TASK_STATE_COMPLETED, | ||
| message: undefined, | ||
| timestamp: undefined | ||
| }, | ||
| metadata: undefined | ||
| }) | ||
| ) | ||
| }, | ||
| async cancelTask(_taskId: string, _eventBus: ExecutionEventBus) {} | ||
| } | ||
|
|
||
| const handler = new DefaultRequestHandler(agentCard, taskStore, agentExecutor) | ||
| const jsonRpcHandler = new JsonRpcTransportHandler(handler) | ||
|
|
||
| export async function POST(request: Request) { | ||
| try { | ||
| const body = await request.json() | ||
| const headers: Record<string, string> = {} | ||
| request.headers.forEach((value, key) => { | ||
| headers[key] = value | ||
| }) | ||
|
|
||
| const rpcResult = await jsonRpcHandler.handle( | ||
| body, | ||
| new ServerCallContext({ state: new Map([['headers', headers]]) }) | ||
| ) | ||
|
|
||
| if (rpcResult && typeof (rpcResult as any)[Symbol.asyncIterator] === 'function') { | ||
| const encoder = new TextEncoder() | ||
| const stream = new ReadableStream({ | ||
| async start(controller) { | ||
| for await (const chunk of rpcResult as AsyncGenerator<any>) { | ||
| controller.enqueue(encoder.encode(JSON.stringify(chunk) + '\n')) | ||
| } | ||
| controller.close() | ||
| } | ||
| }) | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
|
|
||
| return new Response(stream, { | ||
| headers: { | ||
| 'Content-Type': 'application/x-ndjson', | ||
| 'Access-Control-Allow-Origin': '*' | ||
| } | ||
| }) | ||
| } | ||
|
|
||
| return NextResponse.json(rpcResult, { | ||
| headers: { | ||
| 'Access-Control-Allow-Origin': '*', | ||
| 'Access-Control-Allow-Methods': 'POST, OPTIONS', | ||
| 'Access-Control-Allow-Headers': 'Content-Type, Authorization, A2A-Version' | ||
| } | ||
| }) | ||
| } catch (error: any) { | ||
| console.error('A2A Server POST Handler error:', error) | ||
| return NextResponse.json( | ||
| { | ||
| jsonrpc: '2.0', | ||
| id: null, | ||
| error: { | ||
| code: -32603, | ||
| message: error?.message || 'Internal error' | ||
| } | ||
| }, | ||
| { status: 500 } | ||
| ) | ||
| } | ||
| } | ||
|
|
||
| export async function OPTIONS() { | ||
| return new Response(null, { | ||
| status: 204, | ||
| headers: { | ||
| 'Access-Control-Allow-Origin': '*', | ||
| 'Access-Control-Allow-Methods': 'POST, OPTIONS', | ||
| 'Access-Control-Allow-Headers': 'Content-Type, Authorization, A2A-Version' | ||
| } | ||
| }) | ||
| } | ||
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Persist the agent reply in the completed task.
The completion status sets
messagetoundefined. The precedingAgentEvent.messagesupplies a reply to the current stream, but the SDK does not persist that event in task history. A client that later callsGetTaskreceives a completed task without the agent reply. Set the completion status message to the agent response, or publish a response artifact. (raw.githubusercontent.com)🤖 Prompt for AI Agents