Các agent không nói cùng một ngôn ngữ thì chẳng phải một đội. Chúng chỉ là những người lạ đang hét vào khoảng không.
Mục tiêu bài học
- Triển khai việc khám phá và gọi tool qua MCP để agent dùng được các tool do server bên ngoài cung cấp
- Xây dựng một Agent Card và endpoint xử lý task theo A2A, cho phép một agent giao việc cho agent khác qua HTTP
- So sánh MCP (truy cập tool), A2A (giao tiếp giữa các agent), ACP (kiểm toán trong doanh nghiệp) và ANP (định danh và tin cậy phi tập trung), rồi giải thích mỗi giao thức giải quyết vấn đề gì
- Kết nối nhiều giao thức trong một hệ thống, nơi các agent khám phá tool qua MCP và giao task qua A2A
Vấn đề
Bạn chia hệ thống thành nhiều agent. Một agent nghiên cứu, một agent viết code, một agent review. Từng agent đều làm tốt việc của mình. Nhưng giờ bạn cần chúng thực sự nói chuyện với nhau.
Cách thử đầu tiên rất hiển nhiên: truyền các chuỗi qua lại. Agent nghiên cứu trả về một khối văn bản, agent viết code cố phân tích nó theo cách mình có thể. Cách này chạy được cho đến khi agent viết code hiểu sai bản tóm tắt nghiên cứu, hoặc hai agent mắc kẹt vì chờ nhau, hoặc bạn cần các agent do những nhóm khác nhau xây dựng cùng làm việc. Bỗng nhiên, cách “cứ truyền chuỗi là được” sụp đổ.
Đây là vấn đề về giao thức giao tiếp. Nếu không có một quy ước chung về cách các agent trao đổi thông tin, hệ thống nhiều agent sẽ mong manh, khó kiểm toán và không thể mở rộng quá một nhóm nhỏ agent do chính bạn viết.
Hệ sinh thái AI đã đưa ra bốn giao thức, mỗi giao thức giải quyết một phần khác nhau của vấn đề:
- MCP để truy cập tool
- A2A để các agent cộng tác với nhau
- ACP để đáp ứng nhu cầu kiểm toán trong doanh nghiệp
- ANP để định danh và thiết lập sự tin cậy theo cách phi tập trung
Bài này sẽ đi sâu vào từng giao thức. Bạn sẽ đọc định dạng dữ liệu trao đổi thực tế trong từng đặc tả, xây dựng các bản triển khai chạy được và kết nối cả bốn vào một hệ thống thống nhất.
Khái niệm
Bức tranh các giao thức
Hãy xem bốn giao thức này như các layer, mỗi layer trả lời một câu hỏi khác nhau:
Chúng không cạnh tranh với nhau. Chúng giải quyết những vấn đề khác nhau ở những cấp độ khác nhau.
MCP (Nhắc lại)
MCP đã được trình bày kỹ trong Phase 13. Nhắc lại nhanh: MCP chuẩn hóa cách một LLM kết nối với tool và nguồn dữ liệu bên ngoài. Đây là giao thức client-server, trong đó agent (client) khám phá và gọi các tool do server cung cấp.
MCP dùng để giao tiếp giữa agent và tool. Nó không giúp các agent nói chuyện với nhau.
A2A (Agent2Agent Protocol)
A2A là giao thức để các agent ngang hàng cộng tác với nhau. MCP kết nối agent với tool, còn A2A kết nối agent với những agent khác. Mỗi agent công bố một Agent Card tại một URL được quy định trước. Các agent khác dùng nó để tìm, thương lượng và giao task cho agent đó.
A2A hoạt động như thế nào
Agent Card thực tế
Đây là hình dạng thực tế của một A2A Agent Card. Nó được trả về tại GET /.well-known/agent-card.json:
{
"name": "Research Agent",
"description": "Searches documentation and summarizes findings",
"version": "1.0.0",
"supportedInterfaces": [
{
"url": "https://research-agent.example.com/a2a/v1",
"protocolBinding": "JSONRPC",
"protocolVersion": "1.0"
},
{
"url": "https://research-agent.example.com/a2a/rest",
"protocolBinding": "HTTP+JSON",
"protocolVersion": "1.0"
}
],
"provider": {
"organization": "Your Company",
"url": "https://example.com"
},
"capabilities": {
"streaming": true,
"pushNotifications": false
},
"defaultInputModes": ["text/plain", "application/json"],
"defaultOutputModes": ["text/plain", "application/json"],
"skills": [
{
"id": "web-research",
"name": "Web Research",
"description": "Searches the web and synthesizes findings",
"tags": ["research", "search", "summarization"],
"examples": ["Research the latest changes in React 19"]
},
{
"id": "doc-analysis",
"name": "Documentation Analysis",
"description": "Reads and analyzes technical documentation",
"tags": ["docs", "analysis"],
"inputModes": ["text/plain", "application/pdf"],
"outputModes": ["application/json"]
}
],
"securitySchemes": {
"bearer": {
"httpAuthSecurityScheme": {
"scheme": "Bearer",
"bearerFormat": "JWT"
}
}
},
"securityRequirements": [{ "schemes": { "bearer": { "list": [] } } }]
}Những điểm cần chú ý:
- Skills cho biết agent làm được gì. Mỗi skill có ID, các tag và những MIME type đầu vào/đầu ra được hỗ trợ. Dựa vào đó, agent phía client quyết định agent ở xa có xử lý được yêu cầu của mình hay không.
- supportedInterfaces liệt kê nhiều cách kết nối theo giao thức. Một agent có thể hỗ trợ JSON-RPC, REST và gRPC cùng lúc.
- Security được khai báo ngay trong card:
securitySchemesđặt tên cho từng cơ chế, cònsecurityRequirementscho biết cần dùng cơ chế nào. Client biết mình cần xác thực ra sao trước khi gửi yêu cầu đầu tiên.
Vòng đời của task
Task là đơn vị công việc cốt lõi trong A2A. Task chuyển qua các trạng thái đã được định nghĩa (sơ đồ lược bỏ tiền tố TASK_STATE_ mà mọi trạng thái đều có trong dữ liệu trao đổi):
Cả 8 trạng thái (đặc tả còn định nghĩa UNSPECIFIED làm giá trị đánh dấu, nhưng không liệt kê ở đây):
| Trạng thái | Kết thúc? | Ý nghĩa |
|---|---|---|
TASK_STATE_SUBMITTED | Không | Đã được ghi nhận, chưa bắt đầu xử lý |
TASK_STATE_WORKING | Không | Đang được xử lý |
TASK_STATE_INPUT_REQUIRED | Không | Agent cần thêm thông tin từ client |
TASK_STATE_AUTH_REQUIRED | Không | Cần xác thực |
TASK_STATE_COMPLETED | Có | Hoàn thành thành công |
TASK_STATE_FAILED | Có | Kết thúc do lỗi |
TASK_STATE_CANCELED | Có | Bị hủy trước khi hoàn thành |
TASK_STATE_REJECTED | Có | Agent từ chối task |
Khi task đã đến trạng thái kết thúc, nó không thể thay đổi nữa. Không thể gửi thêm message. Muốn tiếp tục, bạn tạo một task mới trong cùng contextId.
Định dạng dữ liệu trao đổi
A2A dùng JSON-RPC 2.0. Đây là một lượt trao đổi message thực tế:
Client gửi một message:
{
"jsonrpc": "2.0",
"id": 1,
"method": "SendMessage",
"params": {
"message": {
"messageId": "msg-001",
"role": "ROLE_USER",
"parts": [{ "text": "Research React 19 compiler features" }]
},
"configuration": {
"acceptedOutputModes": ["text/plain", "application/json"],
"historyLength": 10
}
}
}Agent trả về một task:
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"task": {
"id": "task-abc-123",
"contextId": "ctx-xyz-789",
"status": {
"state": "TASK_STATE_COMPLETED",
"timestamp": "2026-03-27T10:30:00Z"
},
"artifacts": [
{
"artifactId": "art-001",
"name": "research-results",
"parts": [{
"data": {
"findings": [
"React 19 compiler auto-memoizes components",
"No more manual useMemo/useCallback needed",
"Compiler runs at build time, not runtime"
]
},
"mediaType": "application/json"
}]
}
]
}
}
}Streaming qua SSE:
POST /message:stream HTTP/1.1
Content-Type: application/a2a+json
A2A-Version: 1.0
data: {"task":{"id":"task-123","contextId":"ctx-123","status":{"state":"TASK_STATE_WORKING"}}}
data: {"statusUpdate":{"taskId":"task-123","contextId":"ctx-123","status":{"state":"TASK_STATE_WORKING","message":{"messageId":"msg-002","role":"ROLE_AGENT","parts":[{"text":"Searching documentation..."}]}}}}
data: {"artifactUpdate":{"taskId":"task-123","contextId":"ctx-123","artifact":{"artifactId":"art-1","parts":[{"text":"partial findings..."}]},"append":true,"lastChunk":false}}
data: {"statusUpdate":{"taskId":"task-123","contextId":"ctx-123","status":{"state":"TASK_STATE_COMPLETED"}}}ACP (Agent Communication Protocol)
ACP là giao thức dành cho doanh nghiệp. Trái với nhiều bản tóm tắt, ACP không dùng JSON-LD. Đây là một API REST/JSON đơn giản, được định nghĩa bằng OpenAPI. Điểm đặc biệt của nó là TrajectoryMetadata: mỗi phản hồi của agent có thể mang theo log chi tiết về các bước suy luận và những lần gọi tool đã tạo ra phản hồi đó.
Khám phá agent trong ACP
ACP định nghĩa bốn cách khám phá:
AgentManifest đơn giản hơn Agent Card của A2A:
{
"name": "summarizer",
"description": "Summarizes documents with source citations",
"input_content_types": ["text/plain", "application/pdf"],
"output_content_types": ["text/plain", "application/json"],
"metadata": {
"tags": ["summarization", "RAG"],
"framework": "BeeAI",
"capabilities": [
{
"name": "Document Summarization",
"description": "Condenses long documents into key points"
}
],
"recommended_models": ["llama3.3:70b-instruct-fp16"],
"license": "Apache-2.0",
"programming_language": "Python"
}
}Vòng đời của Run
ACP dùng “Runs” thay cho “Tasks”. Một Run là một lần thực thi agent, với ba chế độ:
| Chế độ | Cách hoạt động |
|---|---|
sync | Chờ đến khi xong. Phản hồi chứa kết quả hoàn chỉnh. |
async | Trả về 202 ngay lập tức. Thăm dò GET /runs/{id} để biết trạng thái. |
stream | Luồng SSE. Các event được gửi ra trong lúc agent làm việc. |
TrajectoryMetadata (Dấu vết kiểm toán)
Đây là điểm khác biệt quan trọng nhất của ACP. Mỗi phần của message có thể chứa metadata cho biết chính xác agent đã làm gì:
{
"role": "agent/researcher",
"parts": [
{
"content_type": "text/plain",
"content": "The weather in San Francisco is 72F and sunny.",
"metadata": {
"kind": "trajectory",
"message": "I need to check the weather for this location",
"tool_name": "weather_api",
"tool_input": { "location": "San Francisco, CA" },
"tool_output": { "temperature": 72, "condition": "sunny" }
}
}
]
}Với các ngành chịu quản lý chặt chẽ, điều này cực kỳ quý giá. Mỗi câu trả lời đều đi kèm một chuỗi bước suy luận có thể kiểm chứng: đã gọi tool nào, dùng đầu vào gì, nhận được đầu ra gì. Không còn hộp đen.
ACP cũng hỗ trợ CitationMetadata để ghi nguồn:
{
"kind": "citation",
"start_index": 0,
"end_index": 47,
"url": "https://weather.gov/sf",
"title": "NWS San Francisco Forecast"
}ANP (Agent Network Protocol)
ANP là giao thức định danh phi tập trung. Nó xây dựng sự tin cậy bằng W3C Decentralized Identifiers (DIDs) và mã hóa đầu cuối. Trong A2A, bạn khám phá agent qua các endpoint đã biết. Còn ANP cho phép agent chứng minh danh tính bằng mật mã.
ANP có ba layer:
DID Documents (Cấu trúc thực tế)
ANP dùng một phương thức DID riêng tên là did:wba (Web-Based Agent). DID did:wba:example.com:user:alice trỏ đến https://example.com/user/alice/did.json:
{
"@context": [
"https://www.w3.org/ns/did/v1",
"https://w3id.org/security/suites/jws-2020/v1",
"https://w3id.org/security/suites/secp256k1-2019/v1"
],
"id": "did:wba:example.com:user:alice",
"verificationMethod": [
{
"id": "did:wba:example.com:user:alice#key-1",
"type": "EcdsaSecp256k1VerificationKey2019",
"controller": "did:wba:example.com:user:alice",
"publicKeyJwk": {
"crv": "secp256k1",
"x": "NtngWpJUr-rlNNbs0u-Aa8e16OwSJu6UiFf0Rdo1oJ4",
"y": "qN1jKupJlFsPFc1UkWinqljv4YE0mq_Ickwnjgasvmo",
"kty": "EC"
}
},
{
"id": "did:wba:example.com:user:alice#key-x25519-1",
"type": "X25519KeyAgreementKey2019",
"controller": "did:wba:example.com:user:alice",
"publicKeyMultibase": "z9hFgmPVfmBZwRvFEyniQDBkz9LmV7gDEqytWyGZLmDXE"
}
],
"authentication": [
"did:wba:example.com:user:alice#key-1"
],
"keyAgreement": [
"did:wba:example.com:user:alice#key-x25519-1"
],
"humanAuthorization": [
"did:wba:example.com:user:alice#key-1"
],
"service": [
{
"id": "did:wba:example.com:user:alice#agent-description",
"type": "AgentDescription",
"serviceEndpoint": "https://example.com/agents/alice/ad.json"
}
]
}Những điểm cần chú ý:
- Tách biệt key là yêu cầu bắt buộc. Key dùng để ký (secp256k1) tách riêng khỏi key dùng để mã hóa (X25519).
humanAuthorizationlà điểm riêng của ANP. Trước khi dùng những key này, phải có sự chấp thuận rõ ràng của con người (sinh trắc học, mật khẩu, HSM). Các thao tác rủi ro cao như chuyển tiền đi qua cơ chế này.- Các key
keyAgreementđược dùng để mã hóa đầu cuối bằng HPKE (RFC 9180). - Phần service liên kết đến tài liệu Agent Description.
Sự tin cậy hoạt động thế nào trong ANP
ANP không dùng mạng lưới bảo chứng hay đồ thị xác nhận. Sự tin cậy được thiết lập giữa từng cặp agent và được kiểm tra trong từng lần tương tác:
Sự tin cậy đến từ ba nguồn:
- TLS ở cấp domain xác minh host chứa DID document
- Chữ ký mật mã của DID xác minh danh tính của agent
- Nguyên tắc tin cậy tối thiểu chỉ cấp quyền ở mức tối thiểu
Không có chuyện lan truyền sự tin cậy theo kiểu truyền miệng hay chấm điểm PageRank. Bạn xác minh trực tiếp từng agent qua DID của nó.
Thương lượng meta-protocol
Đây là tính năng mới lạ nhất của ANP. Khi hai agent từ hai hệ sinh thái khác nhau gặp nhau, chúng không cần thống nhất sẵn định dạng dữ liệu. Chúng thương lượng bằng ngôn ngữ tự nhiên:
{
"action": "protocolNegotiation",
"sequenceId": 0,
"candidateProtocols": "I can communicate using:\n1. JSON-RPC with hotel booking schema\n2. REST with OpenAPI 3.1 spec\n3. Natural language over HTTP",
"modificationSummary": "Initial proposal",
"status": "negotiating"
}Các agent trao đổi qua lại (tối đa 10 lượt) cho đến khi thống nhất một định dạng, rồi tự tạo code để xử lý định dạng đó. Các giá trị trạng thái là: negotiating, rejected, accepted, timeout.
Nhờ vậy, hai agent chưa từng gặp nhau vẫn có thể tìm ra cách giao tiếp mà không cần ai định nghĩa trước một schema chung.
So sánh (đã chỉnh lại)
| MCP | A2A | ACP | ANP | |
|---|---|---|---|---|
| Được tạo bởi | Anthropic | Google / Linux Foundation | IBM / BeeAI | Cộng đồng |
| Định dạng đặc tả | JSON-RPC | JSON-RPC / REST / gRPC | OpenAPI 3.1 (REST) | JSON-RPC |
| Cách dùng chính | Agent với Tool | Agent với Agent | Agent với Agent | Agent với Agent |
| Khám phá | Danh sách tool | /.well-known/agent-card.json | GET /agents, /.well-known/agent.yml | /.well-known/agent-descriptions, các endpoint dịch vụ DID |
| Định danh | Ngầm định (cục bộ) | Các cơ chế bảo mật (OAuth, mTLS) | Ở cấp server | W3C DID (did:wba) với E2EE |
| Dấu vết kiểm toán | Không áp dụng | Cơ bản (lịch sử task) | TrajectoryMetadata (lần gọi tool, quá trình suy luận) | Chưa được đặc tả chính thức |
| Máy trạng thái | Không áp dụng | 9 trạng thái task | 7 trạng thái run | Không áp dụng |
| Streaming | Không áp dụng | SSE | SSE | Không phụ thuộc vào cách truyền tải |
| Tính năng riêng | Schema của tool | Agent Cards + Skills | Dấu vết kiểm toán bằng TrajectoryMetadata | Thương lượng meta-protocol |
| Phù hợp nhất với | Tool và dữ liệu | Cộng tác linh hoạt | Ngành chịu quản lý chặt chẽ | Tin cậy giữa các tổ chức |
| Trạng thái | Ổn định | Ổn định (v1.0) | Đang hợp nhất vào A2A | Đang phát triển |
Chúng phối hợp với nhau như thế nào
Các giao thức này có thể dùng cùng nhau. Một hệ thống doanh nghiệp thực tế sẽ dùng nhiều giao thức:
- MCP kết nối từng agent với các tool của nó
- A2A xử lý việc cộng tác giữa các agent (nội bộ và bên ngoài)
- ACP bổ sung trajectory metadata vào phản hồi để phục vụ kiểm toán
- ANP xác minh danh tính của những agent không thuộc quyền kiểm soát của bạn
Tự xây dựng
Bước 1: Các kiểu message cốt lõi
Mọi hệ thống nhiều agent đều bắt đầu từ định dạng message. Chúng ta định nghĩa các kiểu tương ứng với những gì giao thức thực tế sử dụng:
import crypto from "node:crypto";
type MessageRole = "ROLE_USER" | "ROLE_AGENT";
type MessagePart =
| { text: string }
| { data: unknown; mediaType: string }
| { url: string; filename: string; mediaType: string };
type TrajectoryEntry = {
reasoning: string;
toolName?: string;
toolInput?: unknown;
toolOutput?: unknown;
timestamp: number;
};
type AgentMessage = {
id: string;
role: MessageRole;
parts: MessagePart[];
trajectory?: TrajectoryEntry[];
replyTo?: string;
timestamp: number;
};
function createMessage(
role: MessageRole,
parts: MessagePart[],
replyTo?: string
): AgentMessage {
return {
id: crypto.randomUUID(),
role,
parts,
replyTo,
timestamp: Date.now(),
};
}
function textMessage(role: MessageRole, text: string): AgentMessage {
return createMessage(role, [{ text }]);
}Lưu ý: MessagePart hỗ trợ nhiều modality (văn bản, dữ liệu có cấu trúc, file), giống đặc tả A2A và ACP thực tế. Như trong A2A 1.0, trường nào xuất hiện (text, data hoặc url) sẽ cho biết phần đó là gì; không có tag kind. TrajectoryEntry ghi lại chuỗi bước suy luận, tương ứng với TrajectoryMetadata của ACP.
Bước 2: A2A Agent Card và Registry
Xây dựng cơ chế khám phá agent theo đúng đặc tả A2A thực tế:
type Skill = {
id: string;
name: string;
description: string;
tags: string[];
inputModes: string[];
outputModes: string[];
};
type AgentInterface = {
url: string;
protocolBinding: string;
protocolVersion: string;
};
type AgentCard = {
name: string;
description: string;
version: string;
supportedInterfaces: AgentInterface[];
capabilities: {
streaming: boolean;
pushNotifications: boolean;
};
defaultInputModes: string[];
defaultOutputModes: string[];
skills: Skill[];
};
class AgentRegistry {
private cards: Map<string, AgentCard> = new Map();
register(card: AgentCard) {
this.cards.set(card.name, card);
}
discoverBySkillTag(tag: string): AgentCard[] {
return [...this.cards.values()].filter((card) =>
card.skills.some((skill) => skill.tags.includes(tag))
);
}
discoverByInputMode(mimeType: string): AgentCard[] {
return [...this.cards.values()].filter(
(card) =>
card.defaultInputModes.includes(mimeType) ||
card.skills.some((skill) => skill.inputModes.includes(mimeType))
);
}
resolve(name: string): AgentCard | undefined {
return this.cards.get(name);
}
listAll(): AgentCard[] {
return [...this.cards.values()];
}
}Cơ chế này phong phú hơn nhiều so với một bảng ánh xạ đơn giản từ tên sang khả năng. Bạn có thể khám phá agent theo tag của skill, theo MIME type đầu vào hoặc theo tên, đúng như đặc tả A2A thực tế hỗ trợ.
Bước 3: Vòng đời của A2A task
Xây dựng đầy đủ máy trạng thái của task:
type TaskState =
| "TASK_STATE_SUBMITTED"
| "TASK_STATE_WORKING"
| "TASK_STATE_INPUT_REQUIRED"
| "TASK_STATE_AUTH_REQUIRED"
| "TASK_STATE_COMPLETED"
| "TASK_STATE_FAILED"
| "TASK_STATE_CANCELED"
| "TASK_STATE_REJECTED";
const TERMINAL_STATES: TaskState[] = [
"TASK_STATE_COMPLETED",
"TASK_STATE_FAILED",
"TASK_STATE_CANCELED",
"TASK_STATE_REJECTED",
];
type TaskStatus = {
state: TaskState;
message?: AgentMessage;
timestamp: number;
};
type Artifact = {
id: string;
name: string;
parts: MessagePart[];
};
type Task = {
id: string;
contextId: string;
status: TaskStatus;
artifacts: Artifact[];
history: AgentMessage[];
};
type TaskEvent =
| { statusUpdate: { taskId: string; status: TaskStatus } }
| {
artifactUpdate: {
taskId: string;
artifact: Artifact;
append: boolean;
lastChunk: boolean;
};
};
type TaskHandler = (
task: Task,
message: AgentMessage
) => AsyncGenerator<TaskEvent>;
class TaskManager {
private tasks: Map<string, Task> = new Map();
private handlers: Map<string, TaskHandler> = new Map();
private listeners: Map<string, ((event: TaskEvent) => void)[]> = new Map();
registerHandler(agentName: string, handler: TaskHandler) {
this.handlers.set(agentName, handler);
}
subscribe(taskId: string, listener: (event: TaskEvent) => void) {
const existing = this.listeners.get(taskId) ?? [];
existing.push(listener);
this.listeners.set(taskId, existing);
}
async sendMessage(
agentName: string,
message: AgentMessage,
contextId?: string
): Promise<Task> {
const handler = this.handlers.get(agentName);
if (!handler) {
const task = this.createTask(contextId);
task.status = {
state: "TASK_STATE_REJECTED",
timestamp: Date.now(),
message: textMessage("ROLE_AGENT", `No handler for ${agentName}`),
};
return task;
}
const task = this.createTask(contextId);
task.history.push(message);
task.status = { state: "TASK_STATE_SUBMITTED", timestamp: Date.now() };
this.processTask(task, handler, message).catch((err) => {
task.status = {
state: "TASK_STATE_FAILED",
timestamp: Date.now(),
message: textMessage("ROLE_AGENT", String(err)),
};
});
return task;
}
getTask(taskId: string): Task | undefined {
return this.tasks.get(taskId);
}
cancelTask(taskId: string): boolean {
const task = this.tasks.get(taskId);
if (!task || TERMINAL_STATES.includes(task.status.state)) return false;
task.status = { state: "TASK_STATE_CANCELED", timestamp: Date.now() };
this.emit(taskId, {
statusUpdate: { taskId, status: task.status },
});
return true;
}
private createTask(contextId?: string): Task {
const task: Task = {
id: crypto.randomUUID(),
contextId: contextId ?? crypto.randomUUID(),
status: { state: "TASK_STATE_SUBMITTED", timestamp: Date.now() },
artifacts: [],
history: [],
};
this.tasks.set(task.id, task);
return task;
}
private async processTask(
task: Task,
handler: TaskHandler,
message: AgentMessage
) {
task.status = { state: "TASK_STATE_WORKING", timestamp: Date.now() };
this.emit(task.id, {
statusUpdate: { taskId: task.id, status: task.status },
});
try {
for await (const event of handler(task, message)) {
if (TERMINAL_STATES.includes(task.status.state)) break;
if ("statusUpdate" in event) {
task.status = event.statusUpdate.status;
}
if ("artifactUpdate" in event) {
const update = event.artifactUpdate;
const existing = task.artifacts.find(
(a) => a.id === update.artifact.id
);
if (existing && update.append) {
existing.parts.push(...update.artifact.parts);
} else {
task.artifacts.push(update.artifact);
}
}
this.emit(task.id, event);
}
} catch (err) {
task.status = {
state: "TASK_STATE_FAILED",
timestamp: Date.now(),
message: textMessage("ROLE_AGENT", String(err)),
};
this.emit(task.id, {
statusUpdate: { taskId: task.id, status: task.status },
});
}
}
private emit(taskId: string, event: TaskEvent) {
for (const listener of this.listeners.get(taskId) ?? []) {
listener(event);
}
}
}Phần này triển khai vòng đời thực tế của A2A task: TASK_STATE_SUBMITTED, TASK_STATE_WORKING, TASK_STATE_INPUT_REQUIRED, rồi đến một trạng thái kết thúc. Handler là các async generator tạo ra event statusUpdate và artifactUpdate, với cùng cấu trúc bao ngoài mà luồng SSE mang theo.
Bước 4: Dấu vết kiểm toán kiểu ACP
Bổ sung cơ chế theo dõi trajectory cho quá trình giao tiếp:
type AuditEntry = {
runId: string;
agentName: string;
input: AgentMessage[];
output: AgentMessage[];
trajectory: TrajectoryEntry[];
status: "created" | "in-progress" | "completed" | "failed" | "awaiting";
startedAt: number;
completedAt?: number;
sessionId?: string;
};
class AuditableRunner {
private log: AuditEntry[] = [];
private handlers: Map<
string,
(input: AgentMessage[]) => Promise<{
output: AgentMessage[];
trajectory: TrajectoryEntry[];
}>
> = new Map();
registerAgent(
name: string,
handler: (input: AgentMessage[]) => Promise<{
output: AgentMessage[];
trajectory: TrajectoryEntry[];
}>
) {
this.handlers.set(name, handler);
}
async run(
agentName: string,
input: AgentMessage[],
sessionId?: string
): Promise<AuditEntry> {
const entry: AuditEntry = {
runId: crypto.randomUUID(),
agentName,
input: structuredClone(input),
output: [],
trajectory: [],
status: "created",
startedAt: Date.now(),
sessionId,
};
this.log.push(entry);
const handler = this.handlers.get(agentName);
if (!handler) {
entry.status = "failed";
return entry;
}
entry.status = "in-progress";
try {
const result = await handler(input);
entry.output = structuredClone(result.output);
entry.trajectory = structuredClone(result.trajectory);
entry.status = "completed";
entry.completedAt = Date.now();
} catch (err) {
entry.status = "failed";
entry.trajectory.push({
reasoning: `Error: ${String(err)}`,
timestamp: Date.now(),
});
entry.completedAt = Date.now();
}
return entry;
}
getFullAuditLog(): AuditEntry[] {
return structuredClone(this.log);
}
getAuditLogForAgent(agentName: string): AuditEntry[] {
return structuredClone(
this.log.filter((e) => e.agentName === agentName)
);
}
getAuditLogForSession(sessionId: string): AuditEntry[] {
return structuredClone(
this.log.filter((e) => e.sessionId === sessionId)
);
}
getTrajectoryForRun(runId: string): TrajectoryEntry[] {
const entry = this.log.find((e) => e.runId === runId);
return entry ? structuredClone(entry.trajectory) : [];
}
}Mỗi lần agent thực thi đều tạo ra một bản ghi kiểm toán đầy đủ: đầu vào là gì, đầu ra là gì, và toàn bộ trajectory gồm các lần gọi tool cùng các bước suy luận ở giữa. Bạn có thể truy vấn theo agent, theo session hoặc theo từng run.
Bước 5: Xác minh danh tính kiểu ANP
Xây dựng cơ chế định danh và xác minh dựa trên DID:
type VerificationMethod = {
id: string;
type: string;
controller: string;
publicKeyDer: string;
};
type DIDDocument = {
id: string;
verificationMethod: VerificationMethod[];
authentication: string[];
keyAgreement: string[];
humanAuthorization: string[];
service: { id: string; type: string; serviceEndpoint: string }[];
};
type AgentIdentity = {
did: string;
document: DIDDocument;
privateKey: crypto.KeyObject;
publicKey: crypto.KeyObject;
};
class IdentityRegistry {
private documents: Map<string, DIDDocument> = new Map();
publish(doc: DIDDocument) {
this.documents.set(doc.id, doc);
}
resolve(did: string): DIDDocument | undefined {
return this.documents.get(did);
}
verify(did: string, signature: string, payload: string): boolean {
const doc = this.documents.get(did);
if (!doc) return false;
const authKeyIds = doc.authentication;
const authKeys = doc.verificationMethod.filter((vm) =>
authKeyIds.includes(vm.id)
);
for (const key of authKeys) {
const publicKey = crypto.createPublicKey({
key: Buffer.from(key.publicKeyDer, "base64"),
format: "der",
type: "spki",
});
const isValid = crypto.verify(
null,
Buffer.from(payload),
publicKey,
Buffer.from(signature, "hex")
);
if (isValid) return true;
}
return false;
}
requiresHumanAuth(did: string, operationKeyId: string): boolean {
const doc = this.documents.get(did);
if (!doc) return false;
return doc.humanAuthorization.includes(operationKeyId);
}
}
function createIdentity(domain: string, agentName: string): AgentIdentity {
const did = `did:wba:${domain}:agent:${agentName}`;
const { publicKey, privateKey } = crypto.generateKeyPairSync("ed25519");
const publicKeyDer = publicKey
.export({ format: "der", type: "spki" })
.toString("base64");
const keyId = `${did}#key-1`;
const encKeyId = `${did}#key-x25519-1`;
const document: DIDDocument = {
id: did,
verificationMethod: [
{
id: keyId,
type: "Ed25519VerificationKey2020",
controller: did,
publicKeyDer,
},
{
id: encKeyId,
type: "X25519KeyAgreementKey2019",
controller: did,
publicKeyDer,
},
],
authentication: [keyId],
keyAgreement: [encKeyId],
humanAuthorization: [],
service: [
{
id: `${did}#agent-description`,
type: "AgentDescription",
serviceEndpoint: `https://${domain}/agents/${agentName}/ad.json`,
},
],
};
return { did, document, privateKey, publicKey };
}
function signPayload(identity: AgentIdentity, payload: string): string {
return crypto
.sign(null, Buffer.from(payload), identity.privateKey)
.toString("hex");
}Phần này mô phỏng mô hình định danh thực tế của ANP: agent có DID document với các key riêng cho xác thực, thỏa thuận key và sự chấp thuận của con người. IdentityRegistry mô phỏng việc phân giải DID (trong production, hệ thống sẽ gửi HTTP request đến domain của agent để lấy tài liệu).
Bước 6: Protocol Gateway
Kết nối cả bốn giao thức vào một hệ thống thống nhất:
class ProtocolGateway {
private registry: AgentRegistry;
private taskManager: TaskManager;
private auditRunner: AuditableRunner;
private identityRegistry: IdentityRegistry;
constructor(
registry: AgentRegistry,
taskManager: TaskManager,
auditRunner: AuditableRunner,
identityRegistry: IdentityRegistry
) {
this.registry = registry;
this.taskManager = taskManager;
this.auditRunner = auditRunner;
this.identityRegistry = identityRegistry;
}
async delegateTask(
fromDid: string,
signature: string,
targetAgent: string,
message: AgentMessage,
sessionId?: string
): Promise<{ task: Task; audit: AuditEntry } | { error: string }> {
if (!this.identityRegistry.verify(fromDid, signature, message.id)) {
return { error: "Identity verification failed" };
}
const card = this.registry.resolve(targetAgent);
if (!card) {
return { error: `Agent ${targetAgent} not found in registry` };
}
const audit = await this.auditRunner.run(
targetAgent,
[message],
sessionId
);
const task = await this.taskManager.sendMessage(targetAgent, message);
return { task, audit };
}
discoverAndDelegate(
fromDid: string,
signature: string,
skillTag: string,
message: AgentMessage
): Promise<{ task: Task; audit: AuditEntry } | { error: string }> {
const candidates = this.registry.discoverBySkillTag(skillTag);
if (candidates.length === 0) {
return Promise.resolve({
error: `No agents found with skill tag: ${skillTag}`,
});
}
return this.delegateTask(
fromDid,
signature,
candidates[0].name,
message
);
}
}Gateway làm bốn việc trong một lần gọi:
- ANP: Xác minh danh tính của bên gọi bằng chữ ký DID
- A2A: Khám phá agent đích và kiểm tra khả năng của nó
- ACP: Ghi lại quá trình thực thi trong một dấu vết kiểm toán có trajectory
- A2A: Tạo task và theo dõi đầy đủ vòng đời của nó
Bước 7: Kết nối tất cả
async function protocolDemo() {
const registry = new AgentRegistry();
registry.register({
name: "researcher",
description: "Searches and summarizes findings",
version: "1.0.0",
supportedInterfaces: [
{
url: "https://researcher.local/a2a/v1",
protocolBinding: "JSONRPC",
protocolVersion: "1.0",
},
],
capabilities: { streaming: true, pushNotifications: false },
defaultInputModes: ["text/plain"],
defaultOutputModes: ["text/plain", "application/json"],
skills: [
{
id: "web-research",
name: "Web Research",
description: "Searches the web",
tags: ["research", "search", "summarization"],
inputModes: ["text/plain"],
outputModes: ["application/json"],
},
],
});
registry.register({
name: "coder",
description: "Writes code from specs",
version: "1.0.0",
supportedInterfaces: [
{
url: "https://coder.local/a2a/v1",
protocolBinding: "JSONRPC",
protocolVersion: "1.0",
},
],
capabilities: { streaming: false, pushNotifications: false },
defaultInputModes: ["text/plain", "application/json"],
defaultOutputModes: ["text/plain"],
skills: [
{
id: "code-gen",
name: "Code Generation",
description: "Generates code",
tags: ["coding", "generation"],
inputModes: ["text/plain", "application/json"],
outputModes: ["text/plain"],
},
],
});
const taskManager = new TaskManager();
const auditRunner = new AuditableRunner();
const researchTrajectory: TrajectoryEntry[] = [];
taskManager.registerHandler(
"researcher",
async function* (task, message) {
yield {
statusUpdate: {
taskId: task.id,
status: {
state: "TASK_STATE_WORKING" as const,
timestamp: Date.now(),
},
},
};
researchTrajectory.push({
reasoning: "Searching for React 19 documentation",
toolName: "web_search",
toolInput: { query: "React 19 compiler features" },
toolOutput: {
results: ["react.dev/blog/react-19", "github.com/react/react"],
},
timestamp: Date.now(),
});
researchTrajectory.push({
reasoning: "Extracting key findings from search results",
toolName: "doc_analysis",
toolInput: { url: "react.dev/blog/react-19" },
toolOutput: {
summary:
"React 19 compiler auto-memoizes, no manual useMemo needed",
},
timestamp: Date.now(),
});
yield {
artifactUpdate: {
taskId: task.id,
artifact: {
id: crypto.randomUUID(),
name: "research-results",
parts: [
{
data: {
findings: [
"React 19 compiler auto-memoizes components",
"No more manual useMemo/useCallback needed",
"Compiler runs at build time, not runtime",
],
sources: ["react.dev/blog/react-19"],
},
mediaType: "application/json",
},
],
},
append: false,
lastChunk: true,
},
};
yield {
statusUpdate: {
taskId: task.id,
status: {
state: "TASK_STATE_COMPLETED" as const,
timestamp: Date.now(),
},
},
};
}
);
auditRunner.registerAgent("researcher", async () => ({
output: [
textMessage("ROLE_AGENT", "React 19 compiler auto-memoizes components"),
],
trajectory: researchTrajectory,
}));
const identityRegistry = new IdentityRegistry();
const coderIdentity = createIdentity("coder.local", "coder");
const researcherIdentity = createIdentity("researcher.local", "researcher");
identityRegistry.publish(coderIdentity.document);
identityRegistry.publish(researcherIdentity.document);
const gateway = new ProtocolGateway(
registry,
taskManager,
auditRunner,
identityRegistry
);
console.log("=== Protocol Demo ===\n");
console.log("1. Agent Discovery (A2A)");
const researchAgents = registry.discoverBySkillTag("research");
console.log(
` Found ${researchAgents.length} agent(s):`,
researchAgents.map((a) => a.name)
);
console.log("\n2. Identity Verification (ANP)");
const message = textMessage("ROLE_USER", "Research React 19 compiler features");
const signature = signPayload(coderIdentity, message.id);
const verified = identityRegistry.verify(
coderIdentity.did,
signature,
message.id
);
console.log(` Coder DID: ${coderIdentity.did}`);
console.log(` Signature verified: ${verified}`);
console.log("\n3. Task Delegation (A2A + ACP + ANP)");
const result = await gateway.delegateTask(
coderIdentity.did,
signature,
"researcher",
message,
"session-001"
);
if ("error" in result) {
console.log(` Error: ${result.error}`);
return;
}
console.log(` Task ID: ${result.task.id}`);
console.log(` Task state: ${result.task.status.state}`);
console.log(` Artifacts: ${result.task.artifacts.length}`);
console.log("\n4. Audit Trail (ACP)");
console.log(` Run ID: ${result.audit.runId}`);
console.log(` Status: ${result.audit.status}`);
console.log(` Trajectory steps: ${result.audit.trajectory.length}`);
for (const step of result.audit.trajectory) {
console.log(` - ${step.reasoning}`);
if (step.toolName) {
console.log(` Tool: ${step.toolName}`);
}
}
console.log("\n5. Full Audit Log");
const fullLog = auditRunner.getFullAuditLog();
console.log(` Total runs: ${fullLog.length}`);
for (const entry of fullLog) {
const duration = entry.completedAt
? `${entry.completedAt - entry.startedAt}ms`
: "in-progress";
console.log(` ${entry.agentName}: ${entry.status} (${duration})`);
}
}
protocolDemo().catch((err) => {
console.error("Protocol demo failed:", err);
process.exitCode = 1;
});Những lỗi thường gặp
Các giao thức giúp xử lý luồng hoạt động suôn sẻ. Đây là những gì có thể hỏng trong production:
Schema thay đổi lệch nhau. Agent A công bố một Agent Card, cho biết đầu ra là application/json. Nhưng JSON schema thay đổi giữa các phiên bản. Agent B phân tích theo định dạng cũ và nhận được dữ liệu vô nghĩa. Cách khắc phục: đặt phiên bản cho skills và schema đầu ra. Đó là lý do đặc tả A2A hỗ trợ version trên Agent Cards.
Vi phạm máy trạng thái. Một handler của agent tạo ra status update TASK_STATE_COMPLETED, rồi lại cố tạo thêm artifacts. Task lúc này không thể thay đổi. Code của bạn âm thầm bỏ các update đó hoặc báo lỗi. Cách khắc phục: kiểm tra trạng thái kết thúc trước khi tạo update. TaskManager ở trên thực thi quy tắc này bằng lệnh break sau các trạng thái kết thúc.
Không xác minh được danh tính. Agent A cố xác minh DID của Agent B, nhưng domain của Agent B đang ngừng hoạt động. Không thể lấy DID document. Bạn sẽ chấp nhận agent chưa được xác minh hay từ chối tất cả? ANP khuyến nghị từ chối theo nguyên tắc tin cậy tối thiểu.
Trajectory quá lớn. Việc ghi log trajectory của ACP rất hữu ích nhưng tốn kém. Một agent phức tạp gọi tool 200 lần trong mỗi run sẽ tạo ra bản ghi kiểm toán khổng lồ. Cách khắc phục: cho phép cấu hình mức độ chi tiết của log trajectory. Ghi tên tool cùng đầu vào và đầu ra để đáp ứng yêu cầu tuân thủ; bỏ qua các bước suy luận với những tác vụ không chịu quản lý chặt chẽ.
Quá nhiều yêu cầu khám phá cùng lúc. 50 agent đồng thời truy vấn GET /agents khi khởi động. Cách khắc phục: cache Agent Cards với TTL, giãn thời điểm khám phá, hoặc để agent chủ động đăng ký thay vì liên tục thăm dò.
Dùng thực tế
Các bản triển khai thực tế
A2A hoàn thiện nhất. Đặc tả chính thức của Google là mã nguồn mở dưới Linux Foundation. Có SDK cho Python và TypeScript. Nếu các agent của bạn cần khám phá lẫn nhau và cộng tác linh hoạt, hãy bắt đầu từ đây.
ACP đang được hợp nhất vào A2A. Dự án BeeAI của IBM tạo ra ACP như một phương án ưu tiên REST, nhưng ý tưởng trajectory metadata đang được đưa vào hệ sinh thái A2A. Hãy dùng các cách làm của ACP (ghi log trajectory, vòng đời run), kể cả khi bạn dùng A2A để truyền dữ liệu.
ANP còn mang tính thử nghiệm nhất. Repo của cộng đồng có Python SDK (AgentConnect). Ý tưởng thương lượng meta-protocol thực sự mới lạ. Đáng theo dõi nếu bạn triển khai agent giữa nhiều tổ chức.
MCP đã được trình bày trong Phase 13. Nếu bạn muốn agent dùng tool, MCP là tiêu chuẩn.
Chọn giao thức phù hợp
Đưa vào sản phẩm
Bài này tạo ra:
code/main.ts-- bản triển khai đầy đủ các cách áp dụng cả bốn giao thứcoutputs/prompt-protocol-selector.md-- một prompt giúp bạn chọn giao thức cho hệ thống của mình
Bài tập
- Giao task qua nhiều chặng. Mở rộng
TaskManagerđể handler của một agent có thể giao các task con cho agent khác. Agent nghiên cứu nhận một task, giao hai task con “tìm kiếm” và “tóm tắt” cho hai agent chuyên trách, chờ cả hai hoàn thành, rồi gộp kết quả vào artifacts của mình. - Streaming dấu vết kiểm toán. Sửa
AuditableRunnerđể hỗ trợ chế độ streaming. Thay vì chờ kết quả hoàn chỉnh, hãy tạo các updateAuditEntrytheo thời gian thực khi có thêm trajectory entry. Dùng một async generator tạo ra các bản ghi trạng thái kiểm toán tại từng thời điểm. - Xoay vòng DID. Thêm khả năng xoay vòng key vào
IdentityRegistry. Một agent phải có thể công bố DID document mới với các key đã cập nhật, đồng thời giữ tham chiếupreviousDid. Trong một khoảng thời gian chuyển tiếp, bên xác minh phải chấp nhận chữ ký từ cả key hiện tại lẫn key trước đó. - Thương lượng giao thức. Triển khai ý tưởng meta-protocol của ANP. Hai agent trao đổi các message
protocolNegotiationvới những định dạng đề xuất (ví dụ: “Tôi dùng được JSON-RPC” và “Tôi thích REST hơn”). Sau tối đa 3 lượt, chúng thống nhất một định dạng hoặc hết thời gian. Định dạng được chọn quyết định chúng sẽ dùngTaskManagerhayAuditableRunnernào. - Giới hạn tốc độ khám phá. Thêm một lớp bao
RateLimitedRegistryđể cache kết quả tra cứu Agent Card với TTL có thể cấu hình và giới hạn số truy vấn khám phá mỗi giây của từng agent. Mô phỏng 100 agent đồng loạt khám phá lẫn nhau khi khởi động và đo mức chênh lệch.
Thuật ngữ chính
| Thuật ngữ | Người ta hay nói | Nghĩa thật sự |
|---|---|---|
| MCP | “Giao thức cho các tool AI” | Giao thức client-server để agent khám phá và dùng tool. Giao tiếp giữa agent và tool, không phải giữa các agent. |
| A2A | “Giao thức agent của Google” | Giao thức ngang hàng để các agent cộng tác, thuộc Linux Foundation. Khám phá qua Agent Cards, vòng đời task có 9 trạng thái, streaming qua SSE. Hỗ trợ các cách kết nối JSON-RPC, REST và gRPC. |
| ACP | “Nhắn tin giữa các agent trong doanh nghiệp” | REST API của IBM/BeeAI cho các lần chạy agent, với TrajectoryMetadata: mỗi phản hồi mang theo toàn bộ chuỗi bước suy luận và các lần gọi tool. Đang được hợp nhất vào A2A. |
| ANP | “Định danh agent phi tập trung” | Giao thức cộng đồng dùng did:wba (DID) để định danh bằng mật mã, HPKE để mã hóa E2EE, và cơ chế thương lượng meta-protocol dựa trên AI cho những agent chưa từng gặp nhau. |
| Agent Card | “Danh thiếp của agent” | Tài liệu JSON tại /.well-known/agent-card.json, mô tả skills, các MIME type được hỗ trợ, cơ chế bảo mật và cách kết nối theo giao thức. |
| DID | “ID phi tập trung” | Tiêu chuẩn W3C cho danh tính có thể xác minh bằng mật mã, được lưu trên domain của chính agent. ANP dùng phương thức did:wba. |
| TrajectoryMetadata | “Biên nhận kiểm toán” | Cơ chế của ACP để đính kèm các bước suy luận, lần gọi tool cùng đầu vào/đầu ra của chúng vào mỗi phản hồi của agent. |
| Meta-protocol | “Các agent thương lượng cách nói chuyện” | Cách tiếp cận của ANP: agent dùng ngôn ngữ tự nhiên để tự thống nhất định dạng dữ liệu, rồi tạo code xử lý định dạng đó. |
| Task | “Một đơn vị công việc” | Đối tượng có trạng thái của A2A, theo dõi công việc từ lúc được gửi đến khi hoàn thành. Không thể thay đổi khi đã đến trạng thái kết thúc. |
Đọc thêm
- Đặc tả Google A2A -- đặc tả chính thức và các SDK (v1.0.1, Linux Foundation)
- Đặc tả IBM/BeeAI ACP -- đặc tả OpenAPI 3.1 cho các lần chạy agent và trajectory metadata
- Agent Network Protocol -- định danh dựa trên DID, E2EE, thương lượng meta-protocol
- Tài liệu Model Context Protocol -- đặc tả MCP của Anthropic (được trình bày trong Phase 13)
- W3C Decentralized Identifiers -- tiêu chuẩn định danh làm nền tảng cho ANP
- RFC 9180 (HPKE) -- cơ chế mã hóa ANP dùng cho E2EE
- FIPA Agent Communication Language -- tiền thân trong giới học thuật của các giao thức agent hiện đại