协议解析
AI 时代,协议解析能力决定了智能系统的开放性与协作深度。掌握主流协议,是打造高效 AI 应用的关键起点。
本文将介绍一些常见的 AI 协议解析方法和工具,帮助开发者理解和实现 AI 交互协议。我们将涵盖以下内容:
- 协议解析方法:介绍如何解析和处理 AI 协议,包括 JSON-RPC、MCP 等常见格式。
- 协议解析工具:推荐一些开源工具和库,帮助快速实现协议解析功能。
- 协议示例:提供一些常见 AI 协议的示例和解析方法。
- 最佳实践:分享一些协议解析的最佳实践和注意事项。
SSE
SSE(Server-Sent Events)是一种服务器向客户端单向推送数据的技术,常用于实时更新应用。它基于 HTTP 协议,允许服务器主动向客户端发送事件。
协议解析
SSE 协议解析相对简单,主要通过监听服务器发送的事件流来实现。以下是一个基本的 SSE 协议解析示例:
const eventSource = new EventSource('https://example.com/sse');
eventSource.onmessage = function(event) {
console.log('New message:', event.data);
};
eventSource.onerror = function(error) {
console.error('SSE error:', error);
};MQTT
MQTT(Message Queuing Telemetry Transport)是一种轻量级的消息传输协议,适用于低带宽、高延迟或不可靠网络环境。它基于发布/订阅模型,允许设备之间进行高效的消息传递。
协议解析
MQTT 协议解析通常使用现有的 MQTT 客户端库,如 Paho MQTT、Mosquitto 等。这些库提供了简单的 API 来连接到 MQTT 代理并处理消息。
以下是一个使用 Paho MQTT 的基本示例:
const mqtt = require('mqtt');
const client = mqtt.connect('mqtt://broker.hivemq.com');
client.on('connect', function () {
console.log('MQTT connected');
client.subscribe('test/topic', function (err) {
if (!err) {
client.publish('test/topic', 'Hello MQTT');
}
});
});
client.on('message', function (topic, message) {
console.log('MQTT message received:', topic, message.toString());
});
client.on('error', function (error) {
console.error('MQTT error:', error);
});WebSocket
WebSocket 是一种双向通信协议,允许客户端和服务器之间建立持久连接。与传统的 HTTP 请求 - 响应模型不同,WebSocket 允许实时数据交换,适用于需要低延迟和高频率更新的应用场景。
协议解析
WebSocket 协议解析通常使用现有的 WebSocket 客户端库,如浏览器内置的 WebSocket API 或 Node.js 的 ws 模块。以下是一个基本的 WebSocket 协议解析示例:
const WebSocket = require('ws');
const ws = new WebSocket('wss://example.com/socket');
ws.on('open', function () {
console.log('WebSocket connected');
ws.send('Hello WebSocket');
});
ws.on('message', function (message) {
console.log('WebSocket message received:', message);
});
ws.on('error', function (error) {
console.error('WebSocket error:', error);
});A2A
A2A(Agent2Agent)是让不同框架、不同厂商构建的智能体互相发现并协作的开放协议。它由 Google 于 2025 年 4 月发布,同年 6 月捐赠给 Linux Foundation 托管,规范于 2026 年 3 月发布 1.0 版本。A2A 解决的是“智能体与智能体”之间的互操作,协作双方不需要暴露各自的内部状态、记忆或工具。
协议解析
按照 A2A 规范,协议围绕以下几个对象展开:
- Agent Card:服务端发布的 JSON 元数据文档,描述智能体的身份、能力、技能、服务端点与认证要求,约定的发现地址是
/.well-known/agent-card.json。 - Message:客户端与智能体之间的一轮消息,带
role、messageId和若干parts。 - Task:智能体为处理请求创建的有状态工作单元,带
id、contextId与status。 - Artifact:任务产出的结果。
同一套操作有三种官方协议绑定:JSON-RPC、gRPC 和 HTTP+JSON/REST,智能体在 Agent Card 的 supportedInterfaces 中声明自己支持哪些。以下示例使用 JSON-RPC 绑定,先读取 Agent Card,再调用 SendMessage:
// 1. 发现:读取对方的 Agent Card,找到 JSON-RPC 绑定的端点
const card = await (
await fetch('https://agent.example.com/.well-known/agent-card.json')
).json();
const endpoint = card.supportedInterfaces.find(
(i) => i.protocolBinding === 'JSONRPC'
).url;
// 2. 调用:发送一条消息,客户端需在每个请求中带上 A2A-Version
const response = await fetch(endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'A2A-Version': '1.0',
},
body: JSON.stringify({
jsonrpc: '2.0',
id: 1,
method: 'SendMessage',
params: {
message: {
role: 'ROLE_USER',
parts: [{ text: 'What is the weather today?' }],
messageId: 'msg-uuid',
},
},
}),
});
// 3. 结果:result 中是 task 或 message 二者之一
const { result } = await response.json();
if (result.task) {
console.log('Task state:', result.task.status.state); // 例如 TASK_STATE_COMPLETED
console.log('Artifacts:', result.task.artifacts);
} else {
console.log('Message:', result.message);
}示例省略了认证;实际使用时按 Agent Card 声明的认证方式携带凭据。
MCP
MCP(Model Context Protocol,模型上下文协议)是连接 AI 应用与外部工具、数据源的开放协议,由 Anthropic 于 2024 年 11 月发布。MCP 服务器向客户端(宿主应用中的模型或智能体)暴露工具(Tools)、资源(Resources)和提示模板(Prompts),消息采用 JSON-RPC 2.0 编码,标准传输为 stdio 和 Streamable HTTP。协议细节见本书 MCP 一章。
协议解析
解析 MCP 就是解析 JSON-RPC 消息。按照 2026-07-28 版规范,协议不再有 initialize 握手和会话,每个请求都在 params._meta 中自带协议版本与客户端能力;走 Streamable HTTP 时,还要把协议版本、方法名和工具名镜像到 HTTP 标头,便于网关不解析消息体就能路由。以下示例调用服务器上的一个工具:
const response = await fetch('https://mcp.example.com/mcp', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json, text/event-stream',
'MCP-Protocol-Version': '2026-07-28',
'Mcp-Method': 'tools/call',
'Mcp-Name': 'get_weather',
},
body: JSON.stringify({
jsonrpc: '2.0',
id: 1,
method: 'tools/call',
params: {
name: 'get_weather',
arguments: { location: 'Beijing' },
_meta: {
'io.modelcontextprotocol/protocolVersion': '2026-07-28',
'io.modelcontextprotocol/clientInfo': { name: 'my-client', version: '1.0.0' },
'io.modelcontextprotocol/clientCapabilities': {},
},
},
}),
});
// 示例假设服务器直接返回 JSON;服务器也可能以 SSE 流(text/event-stream)作答
const { result, error } = await response.json();
if (error) {
console.error('MCP error:', error.code, error.message);
} else {
console.log('Tool result:', result.content);
}仍在使用 2025-11-25 及更早版本的服务器需要先完成 initialize 握手,写法见 JSON-RPC 协议解析。
JSON-RPC
JSON-RPC 是一种轻量级的远程过程调用(RPC)协议,使用 JSON 作为数据格式。它允许客户端和服务器之间通过简单的请求和响应机制进行通信,适用于需要快速、简单交互的应用场景。
协议解析
JSON-RPC 协议解析通常涉及定义请求和响应的格式。以下是一个简单的 JSON-RPC 协议解析示例:
class JSONRPC {
constructor() {
this.methods = {};
}
registerMethod(name, method) {
this.methods[name] = method;
}
callMethod(name, params) {
if (this.methods[name]) {
return this.methods[name](...params);
} else {
throw new Error(`Method ${name} not found`);
}
}
}
const rpc = new JSONRPC();
rpc.registerMethod('add', (a, b) => a + b);
const result = rpc.callMethod('add', [1, 2]);
console.log('RPC result:', result);参考资料
- Model Context Protocol Specification (2026-07-28) - modelcontextprotocol.io
- Agent2Agent (A2A) Protocol Specification - a2a-protocol.org
- JSON-RPC 2.0 Specification - jsonrpc.org
下午技术分享,晚上酒会。免费参加,报名需审核。