From 1858da4973702802758e34ba217d851d0717fb6b Mon Sep 17 00:00:00 2001 From: Terrence Date: Fri, 30 May 2025 00:52:50 +0800 Subject: [PATCH] Avoid tool call blocking main thread (dropping packets) --- main/mcp_server.cc | 12 +++++++++++- main/mcp_server.h | 2 ++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/main/mcp_server.cc b/main/mcp_server.cc index b5a114af..47945cba 100644 --- a/main/mcp_server.cc +++ b/main/mcp_server.cc @@ -8,6 +8,7 @@ #include #include #include +#include #include "application.h" #include "display.h" @@ -338,7 +339,15 @@ void McpServer::DoToolCall(int id, const std::string& tool_name, const cJSON* to return; } - Application::GetInstance().Schedule([this, id, tool_iter, arguments = std::move(arguments)]() { + // Start a task to receive data with stack size 4096 + esp_pthread_cfg_t cfg = esp_pthread_get_default_config(); + cfg.thread_name = "tool_call"; + cfg.stack_size = 4096; + cfg.prio = 1; + esp_pthread_set_cfg(&cfg); + + // Use a thread to call the tool to avoid blocking the main thread + tool_call_thread_ = std::thread([this, id, tool_iter, arguments = std::move(arguments)]() { try { ReplyResult(id, (*tool_iter)->Call(arguments)); } catch (const std::runtime_error& e) { @@ -346,4 +355,5 @@ void McpServer::DoToolCall(int id, const std::string& tool_name, const cJSON* to ReplyError(id, e.what()); } }); + tool_call_thread_.detach(); } \ No newline at end of file diff --git a/main/mcp_server.h b/main/mcp_server.h index a5e3bae0..a1564ae3 100644 --- a/main/mcp_server.h +++ b/main/mcp_server.h @@ -8,6 +8,7 @@ #include #include #include +#include #include @@ -274,6 +275,7 @@ private: void DoToolCall(int id, const std::string& tool_name, const cJSON* tool_arguments); std::vector tools_; + std::thread tool_call_thread_; }; #endif // MCP_SERVER_H