欢迎光临
我们一直在努力

小智AI完整的MCP交互流程,超详细

1. 初始化阶段 – 设备与AI服务器建立连接

// ESP32设备启动时
void Application::Initialize() {


// …其他初始化

#if CONFIG_IOT_PROTOCOL_MCP
McpServer::GetInstance().AddCommonTools(); // 注册MCP工具
#endif

// 建立与小智AI的连接
protocol_->Connect(); // WebSocket连接到小智AI
}

连接建立过程:

ESP32设备 → 小智AI服务器 WebSocket连接: wss://api.xiaozhi.me/mcp/device/{device_id}

2. 工具注册阶段 – AI获取设备能力

当连接建立后,小智AI会查询设备的MCP工具列表:

AI服务器发送工具列表请求:

{


\”jsonrpc\”: \”2.0\”,
\”id\”: 1,
\”method\”: \”tools/list\”,
\”params\”: {

}
}

ESP32设备响应(基于mcp_server.cc):

// 在McpServer::HandleRequest中处理
void McpServer::HandleRequest(const std::string& request) {


cJSON* json = cJSON_Parse(request.c_str());
auto method = cJSON_GetObjectItem(json, \”method\”);

if (strcmp(method->valuestring, \”tools/list\”) == 0) {


// 返回工具列表
cJSON* response = cJSON_CreateObject();
cJSON* result = cJSON_CreateObject();
cJSON* tools = cJSON_CreateArray();

// 添加音量控制工具
cJSON* volume_tool = cJSON_CreateObject();
cJSON_AddStringToObject(volume_tool, \”name\”, \”self.audio_speaker.set_volume\”);
cJSON_AddStringToObject(volume_tool, \”description\”,
\”Set the volume of the audio speaker. If the current volume is unknown, you must call `self.get_device_status` tool first and then call this tool.\”);

// 添加工具参数schema
cJSON* input_schema = cJSON_CreateObject();
cJSON_AddStringToObject(input_schema, \”type\”, \”object\”);
cJSON* properties = cJSON_CreateObject();
cJSON* volume_prop = cJSON_CreateObject();
cJSON_AddStringToObject(volume_prop, \”type\”, \”integer\”

赞(0)
未经允许不得转载:171主机测评 » 小智AI完整的MCP交互流程,超详细
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址