Fix(mcp): make terminal busy and cancel semantics usable by an agent
exec_command answered -32003 "device busy" with no way forward: the message named neither the occupying session nor how to free it, and mcp_cancel_session could only target in-flight calls, so a persistent terminal left behind by an earlier session blocked the host until its idle timer expired. An agent had no route back to a working state. Build the busy text from the live session table: terminal sessions now report parent session_id, idle and elapsed seconds, and point at terminal_exec (or terminal_close with id and session_id) when a persistent session holds the host, or at mcp_cancel_session(request_id) when the occupier is a running exec_command. exec_command sweeps idle terminals before it begins a pending wait, so a session abandoned after 300s does not require a terminal_* call first; SweepIdleTerminals now requires started so it cannot reclaim a session that is still in BeginTermPending and hand the device to a second caller. Cancel becomes addressable and honest. id=0 is rejected with -32602 instead of being treated as "all hosts", the calling request is excluded from matched and released (previously the poll saw itself and released was never true), rows carry cancellable, and when nothing was cancelled the reply lists what matched and which close tool takes it. Instructions, tool description, inputSchema (anyOf request_id/id/session_id) and the released description now agree: kind=call only, persistent sessions close by id+session_id, pending and file_transfer entries are released by cancelling the call that owns them. tools.json is regenerated for the schema and description changes. Debug server builds, check_platform_table.py and gen_go_tools.py --check pass; the Release instance was not rebuilt or restarted. Co-Authored-By: deepseek-flash
This commit is contained in:
1 parent
3d18b2119a
commit
42dd70fe20
2 files changed
+109
-12
No files matched your search
+19
-2
@@ -1255,7 +1255,7 @@
|
||||
},
|
||||
{
|
||||
"name": "mcp_cancel_session",
|
||||
"description": "取消在飞请求并尽快释放主机占用。给 request_id(tools/call 的 JSON-RPC id,类型要与调用时一致)精确取消一次调用,或按 id(主机)与 session_id 取消匹配的调用(两个都给则必须同时匹配)。工具层的等待在 ≤500ms 内退出并走既有清理路径;本工具最多等 2s,返回 cancelled(取消个数)、released(是否已释放占用)、waited_ms 与 matched(匹配到的会话)。被取消的请求以 -32800 结束。等价于对 SSE 流发 notifications/cancelled。",
|
||||
"description": "取消在飞请求并尽快释放主机占用。只能取消 kind=call 的在飞调用:给 request_id(tools/call 的 JSON-RPC id,类型要与调用时一致)精确取消一次,或按 id(主机,必须非 0)/ session_id 取消匹配的调用(两个都给则必须同时匹配)。取消一次卡住的调用会连带释放它持有的 pending / file_transfer 等待;持久会话本身不会被关闭,terminal / remote_control / chat 分别用 terminal_close / remote_close / chat_close(两者都要同时给 id 与 session_id)。工具层的等待在 ≤500ms 内退出并走既有清理路径;本工具最多等 2s,返回 cancelled(真正取消的调用个数,不含本工具自身)、released(这些调用是否已释放占用)、waited_ms 与 matched(匹配到的所有会话,每项带 cancellable)。被取消的请求以 -32800 结束。等价于对 SSE 流发 notifications/cancelled。",
|
||||
"gate": null,
|
||||
"platforms": [
|
||||
"win",
|
||||
@@ -1265,6 +1265,23 @@
|
||||
],
|
||||
"impl": "mfc",
|
||||
"inputSchema": {
|
||||
"anyOf": [
|
||||
{
|
||||
"required": [
|
||||
"request_id"
|
||||
]
|
||||
},
|
||||
{
|
||||
"required": [
|
||||
"id"
|
||||
]
|
||||
},
|
||||
{
|
||||
"required": [
|
||||
"session_id"
|
||||
]
|
||||
}
|
||||
],
|
||||
"properties": {
|
||||
"id": {
|
||||
"description": "主机 id:取消该主机上所有在飞请求",
|
||||
@@ -1296,7 +1313,7 @@
|
||||
"type": "array"
|
||||
},
|
||||
"released": {
|
||||
"description": "2s 内匹配的会话是否已从服务端表中消失(主机已松开)",
|
||||
"description": "2s 内被取消的在飞调用(kind=call,不含本工具自身)是否已从服务端表中消失(主机已松开)",
|
||||
"type": "boolean"
|
||||
},
|
||||
"waited_ms": {
|
||||
|
||||
@@ -298,7 +298,9 @@ const char* kServerInstructions =
|
||||
u8"-32002 主机离线或不存在:先刷新主机列表再选,不要拿旧快照反复重试。\n"
|
||||
u8"-32003 主机忙:同一台主机同一时刻只允许一个请求在飞(列表、截屏、文件、管理动作共用这一道锁,"
|
||||
u8"文件传输会话另有一道互斥),并发重试只会继续被拒;message 末尾会点名占用者与已持续时长,"
|
||||
u8"用 mcp_list_sessions 可看全部会话,确需打断(例如上一条请求已无意义)用 mcp_cancel_session 释放。\n"
|
||||
u8"用 mcp_list_sessions 可看全部会话。确需打断用 mcp_cancel_session,但它只能取消在飞调用(kind=call);"
|
||||
u8"持久会话要按类型关闭(id 与 session_id 都要给):terminal → terminal_close,remote_control → remote_close,"
|
||||
u8"chat → chat_close。pending / file_transfer 是某次在飞调用的等待态,取消那次调用就一并释放。\n"
|
||||
u8"-32004 命令未能送达主机:多半是链路瞬断,可重试一次。\n"
|
||||
u8"-32005 该主机不支持这项能力:换主机或换工具,改参数没有用。\n"
|
||||
u8"-32006 策略拒绝:开关未开或只读模式,重试无效,需要管理员改服务端配置。\n"
|
||||
@@ -328,7 +330,9 @@ const char* kServerInstructions =
|
||||
u8"remote_mouse / remote_keyboard 用归一化坐标(0..1)操作 → 必须 remote_close 释放会话,闲置会话会被回收。"
|
||||
u8"要防止真人操作打断自动化时用 remote_block_input 锁定对端键鼠(Windows/Android;必须带 max_block_ms,到期自动解除;"
|
||||
u8"客户端无管理员权限时 Windows 会让 BlockInput 静默失败,成功只代表命令已送达)。\n"
|
||||
u8"命令执行:exec_command 一次性取输出(受白名单约束)。terminal_exec 无需先 terminal_open:带 command 时"
|
||||
u8"命令执行:exec_command 一次性取输出(受白名单约束);同一主机已有持久终端会话时它会被 -32003 拒绝"
|
||||
u8"(改用 terminal_exec 复用该会话,或 terminal_close(id, session_id) 立刻关掉;空闲会话 300s 后会在下一次"
|
||||
u8" exec_command / terminal_* 调用时自动回收)。terminal_exec 无需先 terminal_open:带 command 时"
|
||||
u8"自动复用或创建该主机的持久会话(cwd/环境变量跨命令保持,闲置 300 秒回收),结果里带回 session_id,"
|
||||
u8"后续轮询用它;只有需要显式管理会话时才用 terminal_open / terminal_close。\n"
|
||||
u8"HTTP 探测:探主机本机或同网段的接口用 http_probe(只收私网/回环 IP 与 localhost,不给域名,"
|
||||
@@ -2405,7 +2409,7 @@ std::string BuildToolsListResult(const Json::Value& id) {
|
||||
{
|
||||
Json::Value tool(Json::objectValue);
|
||||
tool["name"] = "mcp_cancel_session";
|
||||
tool["description"] = u8"取消在飞请求并尽快释放主机占用。给 request_id(tools/call 的 JSON-RPC id,类型要与调用时一致)精确取消一次调用,或按 id(主机)与 session_id 取消匹配的调用(两个都给则必须同时匹配)。工具层的等待在 ≤500ms 内退出并走既有清理路径;本工具最多等 2s,返回 cancelled(取消个数)、released(是否已释放占用)、waited_ms 与 matched(匹配到的会话)。被取消的请求以 -32800 结束。等价于对 SSE 流发 notifications/cancelled。";
|
||||
tool["description"] = u8"取消在飞请求并尽快释放主机占用。只能取消 kind=call 的在飞调用:给 request_id(tools/call 的 JSON-RPC id,类型要与调用时一致)精确取消一次,或按 id(主机,必须非 0)/ session_id 取消匹配的调用(两个都给则必须同时匹配)。取消一次卡住的调用会连带释放它持有的 pending / file_transfer 等待;持久会话本身不会被关闭,terminal / remote_control / chat 分别用 terminal_close / remote_close / chat_close(两者都要同时给 id 与 session_id)。工具层的等待在 ≤500ms 内退出并走既有清理路径;本工具最多等 2s,返回 cancelled(真正取消的调用个数,不含本工具自身)、released(这些调用是否已释放占用)、waited_ms 与 matched(匹配到的所有会话,每项带 cancellable)。被取消的请求以 -32800 结束。等价于对 SSE 流发 notifications/cancelled。";
|
||||
|
||||
Json::Value inputSchema(Json::objectValue);
|
||||
inputSchema["type"] = "object";
|
||||
@@ -2426,6 +2430,17 @@ std::string BuildToolsListResult(const Json::Value& id) {
|
||||
sidProp["description"] = u8"会话 id(terminal/remote_control/chat 的 session_id):只取消该会话上的在飞请求";
|
||||
props["session_id"] = sidProp;
|
||||
inputSchema["properties"] = props;
|
||||
// 三个选择器至少给一个:原 schema 是 required:[],模型发 {} 才会在 handler 里被 -32602 打回。
|
||||
Json::Value anyOf(Json::arrayValue);
|
||||
const char* selectors[] = { "request_id", "id", "session_id" };
|
||||
for (const char* sel : selectors) {
|
||||
Json::Value alt(Json::objectValue);
|
||||
Json::Value req(Json::arrayValue);
|
||||
req.append(sel);
|
||||
alt["required"] = req;
|
||||
anyOf.append(alt);
|
||||
}
|
||||
inputSchema["anyOf"] = anyOf;
|
||||
inputSchema["required"] = Json::Value(Json::arrayValue);
|
||||
tool["inputSchema"] = inputSchema;
|
||||
|
||||
@@ -2436,7 +2451,7 @@ std::string BuildToolsListResult(const Json::Value& id) {
|
||||
outProps["cancelled"] = cancelledProp;
|
||||
Json::Value releasedProp(Json::objectValue);
|
||||
releasedProp["type"] = "boolean";
|
||||
releasedProp["description"] = u8"2s 内匹配的会话是否已从服务端表中消失(主机已松开)";
|
||||
releasedProp["description"] = u8"2s 内被取消的在飞调用(kind=call,不含本工具自身)是否已从服务端表中消失(主机已松开)";
|
||||
outProps["released"] = releasedProp;
|
||||
Json::Value waitedProp(Json::objectValue);
|
||||
waitedProp["type"] = "integer";
|
||||
@@ -4059,6 +4074,34 @@ static bool HasPosixBackgroundAmpersand(const std::string& s) {
|
||||
return false;
|
||||
}
|
||||
|
||||
static const int kTermIdleTimeoutSec = 300; // 持久终端 idle 回收超时(秒)
|
||||
|
||||
// 终端会话的简短标签(-32003 与 mcp_list_sessions 共用同一写法,避免两处漂移)。
|
||||
static std::string TerminalLabel(const std::string& sessionId) {
|
||||
return sessionId.empty() ? std::string("exec_command")
|
||||
: std::string("terminal session_id=") + sessionId;
|
||||
}
|
||||
|
||||
// exec_command 被终端挡住时的完整报错:带会话名/session_id 与闲置/已跑时长,并给出正确出路。
|
||||
// 不复用 BusyMessage:那边的描述顺序会优先报 pending/文件传输,可能把别的占用者算到终端头上。
|
||||
static std::string TerminalBusyMessage(uint64_t devId) {
|
||||
for (const auto& s : CMcpServer::Instance().ListSessions()) {
|
||||
if (s.kind != "terminal" || s.device != devId) continue;
|
||||
std::string detail = " (" + TerminalLabel(s.sessionId);
|
||||
if (s.idleMs >= 0) detail += ", idle=" + std::to_string(s.idleMs / 1000) + "s";
|
||||
if (s.elapsedMs >= 0) detail += ", elapsed=" + std::to_string(s.elapsedMs / 1000) + "s";
|
||||
detail += ")";
|
||||
if (s.tool == "exec_command") {
|
||||
return "Device busy: another exec_command is still running for this host" + detail +
|
||||
"; wait for it to finish, or cancel that call with mcp_cancel_session(request_id)";
|
||||
}
|
||||
return "Device busy: a persistent terminal session is already open for this host" + detail +
|
||||
"; reuse it with terminal_exec, or close it with terminal_close(id, session_id); "
|
||||
"idle sessions are reclaimed after 300s";
|
||||
}
|
||||
return "Device busy: a terminal session is already active for this host";
|
||||
}
|
||||
|
||||
// tools/call:exec_command(Windows/Linux 一次性远程命令:主连接 COMMAND_SHELL → 子连接终端 →
|
||||
// 哨兵命令行 → 收集 stdout + exit_code → 关子链接)。安全门:只读默认 + 白名单 + 审计。
|
||||
std::string BuildExecCommand(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) {
|
||||
@@ -4112,8 +4155,12 @@ std::string BuildExecCommand(const Json::Value& id, const Json::Value& args, CMy
|
||||
|
||||
std::string nonce = GenerateRandomToken().substr(0, 8);
|
||||
|
||||
// 持久终端闲置回收原先只在 terminal_open/exec/close/http_probe 入口触发;exec_command
|
||||
// 不走这些入口,于是「开过一次 terminal_exec → 之后 exec_command 永远 -32003」。
|
||||
// 这里补一次 sweep,并让报错带上 session_id 与替代路径。
|
||||
mcp.SweepIdleTerminals(kTermIdleTimeoutSec);
|
||||
if (!mcp.BeginTermPending(devId, command, nonce))
|
||||
return BuildError(id, -32003, "Device busy: a terminal session is already active for this host");
|
||||
return BuildError(id, -32003, TerminalBusyMessage(devId));
|
||||
|
||||
// 主连接下发 COMMAND_SHELL,客户端建立 shell 子连接并回 TOKEN_*_START。
|
||||
BYTE cmd = COMMAND_SHELL;
|
||||
@@ -4587,6 +4634,10 @@ static std::string BuildMcpCancelSession(const Json::Value& id, const Json::Valu
|
||||
const bool hasDev = args.isObject() && args.isMember("id");
|
||||
if (hasDev && !ReadUInt64Arg(args, "id", devId))
|
||||
return BuildError(id, -32602, "id must be a decimal host id string");
|
||||
// "0" 能通过整数校验,但会让设备过滤失效(matches 里 devId!=0 才比),
|
||||
// 变成「取消全服所有在飞调用」——宁可拒绝。
|
||||
if (hasDev && devId == 0)
|
||||
return BuildError(id, -32602, "id must be a non-zero host id string");
|
||||
const std::string sessionId = GetStringArg(args, "session_id");
|
||||
|
||||
if (reqIdKey.empty() && !hasDev && sessionId.empty())
|
||||
@@ -4603,8 +4654,10 @@ static std::string BuildMcpCancelSession(const Json::Value& id, const Json::Valu
|
||||
};
|
||||
|
||||
CMcpServer& srv = CMcpServer::Instance();
|
||||
const auto self = CurrentMcpCall(); // 取消工具自身也在这张表里,不算「匹配到」也不取消
|
||||
Json::Value matched(Json::arrayValue);
|
||||
for (const auto& s : srv.ListSessions()) {
|
||||
if (self && s.kind == "call" && s.idKey == self->idKey) continue;
|
||||
if (!matches(s)) continue;
|
||||
Json::Value o(Json::objectValue);
|
||||
if (s.device != 0) o["host_id"] = std::to_string(s.device);
|
||||
@@ -4612,6 +4665,7 @@ static std::string BuildMcpCancelSession(const Json::Value& id, const Json::Valu
|
||||
o["tool"] = s.tool;
|
||||
if (!s.sessionId.empty()) o["session_id"] = s.sessionId;
|
||||
if (!s.requestId.empty()) o["request_id"] = s.requestId;
|
||||
o["cancellable"] = (s.kind == "call"); // 本工具只能打断在飞调用
|
||||
matched.append(o);
|
||||
}
|
||||
|
||||
@@ -4626,6 +4680,10 @@ static std::string BuildMcpCancelSession(const Json::Value& id, const Json::Valu
|
||||
while (waitedMs < kCancelWaitMs) {
|
||||
bool stillThere = false;
|
||||
for (const auto& s : srv.ListSessions()) {
|
||||
// 只轮询 kind=call:取消动不到持久会话,它们赖在表里不代表「在收尾」。
|
||||
// 也要跳过取消工具自身——它一直在表里,否则 released 永远等不到 true。
|
||||
if (s.kind != "call") continue;
|
||||
if (self && s.idKey == self->idKey) continue;
|
||||
if (matches(s)) { stillThere = true; break; }
|
||||
}
|
||||
if (!stillThere) { released = true; break; }
|
||||
@@ -4642,7 +4700,23 @@ static std::string BuildMcpCancelSession(const Json::Value& id, const Json::Valu
|
||||
|
||||
std::string text;
|
||||
if (cancelled == 0) {
|
||||
text = u8"没有匹配的在飞请求:可能已经结束,或 request_id 与列表里的值不一致。";
|
||||
if (matched.empty()) {
|
||||
text = u8"没有匹配的在飞请求:可能已经结束,或 request_id 与列表里的值不一致。";
|
||||
} else {
|
||||
// 只匹配到持久会话/挂起表项:本工具只能取消 kind=call,说清楚下一步该用哪个工具。
|
||||
std::string kinds;
|
||||
for (const auto& m : matched) {
|
||||
const std::string k = m["kind"].asString();
|
||||
if (kinds.find(k) == std::string::npos) {
|
||||
if (!kinds.empty()) kinds += "/";
|
||||
kinds += k;
|
||||
}
|
||||
}
|
||||
text = u8"匹配到 " + std::to_string((int)matched.size()) + u8" 个会话(kind=" + kinds +
|
||||
u8"),但都不是可取消的在飞调用(kind=call)。持久会话请按类型关闭(id 与 session_id 都要给):"
|
||||
u8"terminal → terminal_close,remote_control → remote_close,chat → chat_close;"
|
||||
u8"pending / file_transfer 是所属在飞调用的等待态,取消那次调用即可一并释放。";
|
||||
}
|
||||
} else if (released) {
|
||||
text = std::string(u8"已取消 ") + std::to_string(cancelled) + u8" 个在飞请求," +
|
||||
std::to_string(waitedMs) + u8" ms 内已释放占用;被取消的请求会收到 -32800。";
|
||||
@@ -4666,7 +4740,6 @@ static std::string BuildMcpCancelSession(const Json::Value& id, const Json::Valu
|
||||
|
||||
// ===== P4:持久远程终端(terminal_open / terminal_exec / terminal_close)=====
|
||||
|
||||
static const int kTermIdleTimeoutSec = 300; // 持久终端 idle 回收超时(秒)
|
||||
static const int kTermTombstoneSec = 600; // 「终端被销毁」墓碑保留时长(秒),供后续报错文案用
|
||||
// 超时轮询(P0-2):超时不再销毁会话,改为返回部分输出 + 可继续轮询,因此需要三个上限。
|
||||
static const int kTermMaxDataBytes = 8 * 1024 * 1024; // 单条命令原始输出硬上限(超出丢最旧字节)
|
||||
@@ -12715,7 +12788,9 @@ int CMcpServer::SweepIdleTerminals(time_t idleTimeoutSec) {
|
||||
const auto steadyNow = std::chrono::steady_clock::now();
|
||||
for (auto it = m_TermSessions.begin(); it != m_TermSessions.end(); ) {
|
||||
TermSession& s = it->second;
|
||||
const bool idle = s.persistent && !s.busy &&
|
||||
// started 条件不能省:尚未 START 的会话可能正被 WaitTerminalReady 等着,
|
||||
// 回收它会把自己的新会话暴露给等待线程(抢到/被误删),等它自己的超时分支清理。
|
||||
const bool idle = s.persistent && s.started && !s.busy &&
|
||||
difftime(now, s.lastActiveAt) > (double)idleTimeoutSec;
|
||||
// busy 兜底(P0-2):超时轮询下会话一直 busy,调用方若再也不回来,该主机的终端槽
|
||||
// 会永远返回 -32003。跑满 1 小时强制回收(等待函数会重新查表,不会悬空)。
|
||||
@@ -13169,14 +13244,18 @@ void CMcpServer::EndCall(const std::shared_ptr<McpCallContext>& call) {
|
||||
|
||||
bool CMcpServer::CancelCallById(const std::string& idKey, const std::string& idText) {
|
||||
std::lock_guard<std::mutex> lk(m_CallMutex);
|
||||
// 取消工具自己也是一次在飞调用;request_id 指到自己时不能把自己算成「被取消」。
|
||||
const McpCallContext* self = CurrentMcpCall().get();
|
||||
// 先按精确写法找:"41"(字符串)与 41(数字)是两个不同的 id,不能混。
|
||||
for (const auto& c : m_Calls) {
|
||||
if (c.get() == self) continue;
|
||||
if (c->idKey == idKey) { c->cancelled.store(true); return true; }
|
||||
}
|
||||
// 再退回展示文本:调用方常把列表里的 request_id 当字符串原样传回来,
|
||||
// 而原调用用的是数字 id —— 这是同一意图,容忍。
|
||||
if (!idText.empty()) {
|
||||
for (const auto& c : m_Calls) {
|
||||
if (c.get() == self) continue;
|
||||
if (c->idText == idText) { c->cancelled.store(true); return true; }
|
||||
}
|
||||
}
|
||||
@@ -13186,7 +13265,9 @@ bool CMcpServer::CancelCallById(const std::string& idKey, const std::string& idT
|
||||
int CMcpServer::CancelCalls(uint64_t device, const std::string& sessionId) {
|
||||
int n = 0;
|
||||
std::lock_guard<std::mutex> lk(m_CallMutex);
|
||||
const McpCallContext* self = CurrentMcpCall().get();
|
||||
for (const auto& c : m_Calls) {
|
||||
if (c.get() == self) continue; // 不把取消工具自身计入 cancelled
|
||||
if (device != 0 && c->device != device) continue;
|
||||
if (!sessionId.empty() && c->sessionId != sessionId) continue;
|
||||
c->cancelled.store(true);
|
||||
@@ -13318,8 +13399,7 @@ std::string CMcpServer::DescribeBusy(uint64_t device_id) {
|
||||
std::lock_guard<std::mutex> lk(m_TermMutex);
|
||||
auto it = m_TermSessions.find(device_id);
|
||||
if (it != m_TermSessions.end() && it->second.busy)
|
||||
return describe(it->second.sessionId.empty() ? "exec_command" : "terminal",
|
||||
ElapsedMsSince(it->second.startedAt));
|
||||
return describe(TerminalLabel(it->second.sessionId), ElapsedMsSince(it->second.startedAt));
|
||||
}
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(m_ScreenCtrlMutex);
|
||||
|
||||
Reference in new issue
Block a user