Feature: Add MCP cancellation, progress notifications and dry runs

P11 closes the plan's last batch, entirely on the server side: no client
change is required for any of it.

Long-running tools now expose a cancellation flag that every wait loop
checks in 500 ms slices. A cancelled tool returns through the cleanup
branch it already had (late first packets still get absorbed, sub
connections still get closed, pending entries still get deleted), so
there is no second cleanup path to keep in sync, and the host is released
within a second. Three sources set the flag: notifications/cancelled
(matched on the exact JSON-RPC id, with a fallback to the display form so
a request_id copied out of the session list round-trips), mcp_cancel_session
(by request_id, host id or session id), and a failed SSE write when the
client has gone away. The dispatcher rewrites a cancel-induced failure to
-32800 so callers do not mistake it for a host fault.

tools/call requests carrying _meta.progressToken are answered as
text/event-stream on the same POST: the tool runs on its own thread and
both the notifications/progress events and the final JSON-RPC response go
out through one chunked provider. Requests without a token are unchanged.
download_file reports files done vs. expected, upload_file reports bytes
sent vs. total.

Two new local-only tools, mcp_list_sessions and mcp_cancel_session, list
and cancel in-flight sessions (calls, pending one-shots, terminal, remote
control, file transfer, chat). They are deliberately not gated by the
feature switches or readonly mode, since that is the only way out of a
stuck request. The -32003 busy message now names the occupier:
"Device busy: ... (tool=download_file, elapsed=12s)".

power_action gains wait/wait_ms to verify the result against the main
connection's presence (went_offline, came_back, elapsed_ms); not seeing
the transition is reported as ok, not as a failure. kill_process,
operate_window and the four host_control_* tools accept dry_run, which
validates the target against one fresh snapshot and returns what would be
affected without sending anything. Validation rejections now use -32012;
-32008 stays as documented historical alias.

One implementation note worth recording: the per-thread call context uses
FLS, not thread_local. Any static thread_local in this server crashes the
process about a second after start, because some threads come from
shellcode/MemoryModule images that never ran PE TLS initialisation.

Verified against a real Debug server and a real Windows client over MCP:
the smoke test now passes 104 checks with 0 failures, including
cancellation releasing the host in under a second, the cancelled request
returning -32800, notifications/cancelled returning 202, 63 progress
events with exact byte counts for a 64 MB upload, and a cleanly
terminated SSE stream. Not exercised in this pass: power_action's
wait=true path (it would take the test host down) and the -32006
readonly/switch-off section (every switch was on during the run).

Co-Authored-By: deepseek-flash
This commit is contained in:
yuanyuanxianganddeepseek-flash committed 2026-10-28 21:25:49 +01:00
1 parent 3d388f8e45
commit 1c832ff7f2
10 files changed
+1855 -107

No files matched your search

+15 -1
View File
@@ -490,6 +490,10 @@ static std::string BuildChatWait(const Json::Value& id, const Json::Value& args,
case CMcpServer::ChatWaitResult::Busy:
return BuildError(id, kErrBusy,
"Another chat_wait is already pending for this session");
case CMcpServer::ChatWaitResult::Cancelled:
// 会话本身仍然有效;回 -32800 让调用方知道是自己取消了等待。
return BuildError(id, kErrCancelled,
"Waiting cancelled by client; the chat session is still open");
case CMcpServer::ChatWaitResult::Closed:
case CMcpServer::ChatWaitResult::Timeout:
case CMcpServer::ChatWaitResult::Ok:
@@ -867,10 +871,14 @@ CMcpServer::ChatReadyResult CMcpServer::WaitChatReady(uint64_t device_id,
if (s->closed) return ChatReadyResult::Closed;
if (s->started && now >= s->readyAt) return ChatReadyResult::Ok;
if (now >= deadline) return ChatReadyResult::Timeout;
if (McpCallCancelled()) return ChatReadyResult::Timeout; // P11:取消按超时收尾
// 绑定通知到达后只需等到 readyAt,不要一直睡到整个 open 超时。
steady_clock::time_point wake = deadline;
if (s->started && s->readyAt < wake) wake = s->readyAt;
// 500ms 上限:唤醒即可响应取消。
const steady_clock::time_point slice = now + std::chrono::milliseconds(500);
if (slice < wake) wake = slice;
m_ChatCv.wait_until(lk, wake);
}
}
@@ -923,7 +931,11 @@ CMcpServer::ChatWaitResult CMcpServer::WaitChatMessages(
while (s->inbox.empty() && !s->closed) {
if (timeoutMs <= 0 || steady_clock::now() >= deadline) break;
m_ChatCv.wait_until(lk, deadline);
if (McpCallCancelled()) break; // P11:≤500ms 内响应取消
// 500ms 一片:允许取消及时生效;无取消时与整段等待等价。
auto until = steady_clock::now() + std::chrono::milliseconds(500);
if (until > deadline) until = deadline;
m_ChatCv.wait_until(lk, until);
}
while (!s->inbox.empty() && out.size() < maxMessages) {
@@ -939,6 +951,8 @@ CMcpServer::ChatWaitResult CMcpServer::WaitChatMessages(
s->waitBusy = false;
if (!s->closed) s->lastActiveAt = time(nullptr);
// 取消优先于「等到超时」:没有消息且是被取消唤醒的,如实回报(会话本身不受影响)。
if (out.empty() && McpCallCancelled() && !closed) return ChatWaitResult::Cancelled;
return timedOut ? ChatWaitResult::Timeout : ChatWaitResult::Ok;
}
+4
View File
@@ -383,6 +383,10 @@ const ToolHints kToolHints[] = {
{ "get_activity_history", true, false, true, true },
{ "get_audit_log", true, false, true, false },
{ "get_server_status", true, false, true, false },
// P11:在飞会话的观测与取消。取消只改服务端自己的等待状态(被取消的请求立即走既有
// 清理路径),不改主机数据;按 request_id/session_id 取消天然幂等,故非破坏且幂等。
{ "mcp_list_sessions", true, false, true, false },
{ "mcp_cancel_session", false, false, true, false },
// --- 主机只读 ---
{ "list_processes", true, false, true, true },
{ "list_windows", true, false, true, true },
+12
View File
@@ -20,6 +20,18 @@ class context;
namespace McpInternal {
// ===== 错误码(-32000 系列,见 docs/Mcp_Design.md §12)=====
//
// -32012 参数被校验拒绝:参数内容非法、按 message 改正后重试即可(shell 元字符、
// 控制字符之类)。-32008 是同一语义的历史别名:早期实现用它,已发布的文档与客户端
// 可能仍在匹配,故保留不改;新代码一律用 -32012。
const int kErrValidation = -32012;
const int kErrValidationOld = -32008; // 历史别名,勿新增使用
// -32800 请求被客户端取消:收到 notifications/cancelled 或 mcp_cancel_session 后,
// 在飞的工具提前退出(走各自的超时清理路径),结果统一以这个码回报。
const int kErrCancelled = -32800;
// Json::Value → 紧凑 JSON 字符串
std::string JsonToString(const Json::Value& v);
+81 -9
View File
@@ -260,6 +260,11 @@ Json::Value ActionOutputSchema() {
props["state"] = PropStr(u8"复核时观测到的状态");
props["reason"] = PropStr(u8"ok=false 时的原因");
props["message"] = PropStr(u8"人类可读的说明");
props["dry_run"] = PropBool(u8"true 表示只是试运行,没有下发动作");
Json::Value detail(Json::objectValue);
detail["type"] = "object";
detail["description"] = u8"dry_run 时目标对象的完整字段";
props["detail"] = detail;
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
@@ -303,6 +308,24 @@ std::string BuildListResult(const Json::Value& id, const char* arrayKey,
return BuildStructuredResult(id, sc, text);
}
// dry_run 的公共结果(§5.5):目标已在最新快照里校验存在,但没有下发任何动作。
// 字段与 ActionOutputSchema 一致(ok/dry_run/action/target/state/detail),
// changed/verified 不适用故省略。
std::string BuildDryRunResult(const Json::Value& id, const std::string& action,
const std::string& target, const std::string& state,
const Json::Value& detail) {
Json::Value sc(Json::objectValue);
sc["ok"] = true;
sc["dry_run"] = true;
sc["action"] = action;
sc["target"] = target;
sc["state"] = state;
sc["detail"] = detail;
std::string text = std::string(u8"试运行:目标已确认存在(") + target +
u8"),未下发任何动作;当前状态 state=" + state;
return BuildStructuredResult(id, sc, text);
}
std::string BuildActionResult(const Json::Value& id, bool ok, bool verified, bool changed,
const std::string& action, const std::string& target,
const std::string& state, const std::string& reason,
@@ -860,7 +883,7 @@ public:
: mcp.BeginMachineSession(m_dev, tool, ht.mainCtx);
if (!began) {
errJson = BuildError(id, kErrBusy,
"Device busy: another MCP request is pending for this host");
BusyMessage("Device busy: another MCP request is pending for this host", m_dev));
return false;
}
m_open = true;
@@ -1042,8 +1065,13 @@ CMcpServer::KeylogWaitResult CMcpServer::WaitKeylogData(uint64_t device_id, std:
if (r.closed) return KeylogWaitResult::Closed;
if (deadline > r.deadline) deadline = r.deadline;
if (std::chrono::steady_clock::now() >= deadline) return KeylogWaitResult::Timeout;
m_PendingCv.wait_until(lk, deadline);
const auto now = std::chrono::steady_clock::now();
if (now >= deadline) return KeylogWaitResult::Timeout;
if (McpCallCancelled()) return KeylogWaitResult::Timeout; // P11:取消按超时收尾
// 500ms 一片:取消后才能及时回到调用方的清理分支。
auto until = now + std::chrono::milliseconds(500);
if (until > deadline) until = deadline;
m_PendingCv.wait_until(lk, until);
}
}
@@ -1099,7 +1127,11 @@ CMcpServer::ManagedWaitResult CMcpServer::WaitManagedPacket(uint64_t device_id,
if (waitUntil > r.deadline) waitUntil = r.deadline;
auto now = std::chrono::steady_clock::now();
if (now >= waitUntil) return ManagedWaitResult::Timeout;
m_PendingCv.wait_until(lk, waitUntil);
if (McpCallCancelled()) return ManagedWaitResult::Timeout; // P11:取消按超时收尾
// 500ms 一片:取消后才能及时回到调用方的清理分支。
auto until = now + std::chrono::milliseconds(500);
if (until > waitUntil) until = waitUntil;
m_PendingCv.wait_until(lk, until);
}
}
@@ -2141,6 +2173,15 @@ static std::string BuildHostControlProcess(const Json::Value& id, const Json::Va
proc->get("name", Json::Value("")).asString() + ")");
}
// dry_run(§5.5):目标已在最新进程列表里核实,就此返回,不下发冻结/解冻。
if (GetBoolArg(args, "dry_run", false)) {
session.Finish();
AuditManageAction(parent, ht.dev, "host_control_process",
action + " pid=" + std::to_string(pidFilter) + " result=dry_run");
return BuildDryRunResult(id, action, "pid=" + std::to_string(pidFilter),
proc->get("name", Json::Value("")).asString(), *proc);
}
std::vector<BYTE> pkt(5);
pkt[0] = (action == "freeze") ? (BYTE)COMMAND_PROCESS_FREEZING
: (BYTE)COMMAND_PROCESS_THAW;
@@ -2209,12 +2250,21 @@ static std::string BuildHostControlWindow(const Json::Value& id, const Json::Val
Json::Value pre;
std::string perr;
if (!ParseWindows(data, 936, pre, perr)) return ParseErrorToJson(id, "window list", perr);
if (!FindWindow(pre, hwnd)) {
const Json::Value* win = FindWindow(pre, hwnd);
if (!win) {
AuditManageAction(parent, ht.dev, "host_control_window",
action + " hwnd=" + std::to_string(hwnd) + " result=not_found");
return NotFoundJson(id, "window hwnd=" + std::to_string(hwnd));
}
// dry_run(§5.5):hwnd 在最新可见窗口列表里,就此返回,不下发窗口操作。
if (GetBoolArg(args, "dry_run", false)) {
session.Finish();
AuditManageAction(parent, ht.dev, "host_control_window",
action + " hwnd=" + std::to_string(hwnd) + " result=dry_run");
return BuildDryRunResult(id, action, "hwnd=" + std::to_string(hwnd), "visible", *win);
}
// [11][hwnd][SW_*] + 零填充到 20 字节(与 MFC 下发格式一致;客户端只读前 9 字节)
std::vector<BYTE> pkt(20, 0);
pkt[0] = (BYTE)COMMAND_WINDOW_OPERATE;
@@ -2304,6 +2354,15 @@ static std::string BuildHostControlService(const Json::Value& id, const Json::Va
std::string initial = svc->get("state", Json::Value("")).asString();
// dry_run(§5.5):服务已在最新列表里核实,返回当前状态后收手(不判断是否 no-op,
// 由调用方看到 state 自行决定)。
if (GetBoolArg(args, "dry_run", false)) {
session.Finish();
AuditManageAction(parent, ht.dev, "host_control_service",
action + " " + serviceName + " result=dry_run");
return BuildDryRunResult(id, action, serviceName, initial, *svc);
}
// 客户端只在状态满足时才真正动作:先按同样的规则判断,避免把 no-op 报成成功。
auto stateIs = [](const std::string& s, const char* want) { return EqualsCI(s, want); };
if (action == "start" && stateIs(initial, "Running")) {
@@ -2459,6 +2518,15 @@ static std::string BuildHostControlTask(const Json::Value& id, const Json::Value
std::string folder = hits[0]->get("folder", Json::Value("\\")).asString();
if (folder.empty()) folder = "\\";
// dry_run(§5.5):任务已在最新列表里核实(含同名歧义检查),返回当前状态后收手。
if (GetBoolArg(args, "dry_run", false)) {
session.Finish();
AuditManageAction(parent, ht.dev, "host_control_task",
action + " " + taskName + " result=dry_run");
return BuildDryRunResult(id, action, taskName + " folder=" + folder,
hits[0]->get("status", Json::Value("")).asString(), *hits[0]);
}
std::string ansiFolder, ansiName;
if (!Utf8ToCpExact(folder, 936, ansiFolder) || !Utf8ToCpExact(taskName, 936, ansiName)) {
return BuildError(id, -32602,
@@ -2837,8 +2905,9 @@ void AppendTools(Json::Value& tools) {
props["action"] = PropStrEnum(u8"freeze=挂起进程,thaw=恢复进程", { "freeze", "thaw" });
props["pid"] = PropInt(u8"目标进程 PID");
props["name"] = PropStr(u8"可选:校验进程名,防止 PID 被系统复用后误操作");
props["dry_run"] = PropBool(u8"true 时只校验 PID/名称存在并返回目标进程,不冻结/解冻,默认 false");
AddTool(tools, "host_control_process",
u8"挂起或恢复在线 Windows 主机上的一个进程(对应主机管理「进程」右键的冻结/解冻)。可能导致目标进程超时或崩溃,故归入危险操作:需要同时开启 McpMachineDangerous。动作没有回执,客户端也不回报结果;工具会在动作后重新拉取进程列表确认目标仍存在。",
u8"挂起或恢复在线 Windows 主机上的一个进程(对应主机管理「进程」右键的冻结/解冻)。可能导致目标进程超时或崩溃,故归入危险操作:需要同时开启 McpMachineDangerous。动作没有回执,客户端也不回报结果;工具会在动作后重新拉取进程列表确认目标仍存在。dry_run=true 只核实目标并返回它,不下发动作。",
MakeSchema(props, { "id", "action", "pid" }),
ActionOutputSchema());
}
@@ -2854,8 +2923,9 @@ void AppendTools(Json::Value& tools) {
hwnd["type"] = types;
hwnd["description"] = u8"窗口句柄,取 host_list_windows 的 hwnd;整数或 0x 前缀字符串";
props["hwnd"] = hwnd;
props["dry_run"] = PropBool(u8"true 时只校验 hwnd 仍在可见窗口列表里并返回该窗口,不下发操作,默认 false");
AddTool(tools, "host_control_window",
u8"对在线 Windows 主机的窗口执行可恢复操作:restore(还原)/hide(隐藏)/maximize(最大化)/minimize(最小化)。hwnd 取 host_list_windows 或 list_windows 返回的 hwnd。动作后重新枚举可见窗口复核:hide 后 hwnd 应消失,其余动作后仍应存在。不提供关闭窗口——需要 close / show 时改用 operate_window。",
u8"对在线 Windows 主机的窗口执行可恢复操作:restore(还原)/hide(隐藏)/maximize(最大化)/minimize(最小化)。hwnd 取 host_list_windows 或 list_windows 返回的 hwnd。动作后重新枚举可见窗口复核:hide 后 hwnd 应消失,其余动作后仍应存在。不提供关闭窗口——需要 close / show 时改用 operate_window。dry_run=true 只核实 hwnd 并返回窗口信息。",
MakeSchema(props, { "id", "action", "hwnd" }),
ActionOutputSchema());
}
@@ -2865,8 +2935,9 @@ void AppendTools(Json::Value& tools) {
props["action"] = PropStrEnum(u8"start/stop/pause/continue/restart",
{ "start", "stop", "pause", "continue", "restart" });
props["name"] = PropStr(u8"服务名(ServiceName,不是显示名),取 host_list_*_services 的 name");
props["dry_run"] = PropBool(u8"true 时只校验服务存在并返回当前状态,不下发控制命令,默认 false");
AddTool(tools, "host_control_service",
u8"控制在线 Windows 主机的服务:start/stop/pause/continue/restart。客户端对每次控制都会自动回一份刷新后的服务列表,工具据此复核状态并如实返回 ok;stop 与 restart 归入危险操作,需要同时开启 McpMachineDangerous。restart 先 stop 再 start。不提供删除服务。",
u8"控制在线 Windows 主机的服务:start/stop/pause/continue/restart。客户端对每次控制都会自动回一份刷新后的服务列表,工具据此复核状态并如实返回 ok;stop 与 restart 归入危险操作,需要同时开启 McpMachineDangerous。restart 先 stop 再 start。不提供删除服务。dry_run=true 只核实服务并返回当前状态,不下发命令(是否已是目标状态由你按 state 判断)。",
MakeSchema(props, { "id", "action", "name" }),
ActionOutputSchema());
}
@@ -2876,8 +2947,9 @@ void AppendTools(Json::Value& tools) {
props["action"] = PropStrEnum(u8"run=立即运行,stop=停止正在运行的任务", { "run", "stop" });
props["name"] = PropStr(u8"任务名,取 host_list_scheduled_tasks 的 name");
props["folder"] = PropStr(u8"可选:任务所在文件夹;同名任务存在多个时必填");
props["dry_run"] = PropBool(u8"true 时只校验任务存在(含同名歧义检查)并返回当前状态,不下发 run/stop,默认 false");
AddTool(tools, "host_control_task",
u8"运行或停止在线 Windows 主机的计划任务(主机管理「计划任务」右键)。客户端无回执,工具只复核任务仍存在并报告当前状态,不声称任务一定执行成功。不提供创建/删除任务。",
u8"运行或停止在线 Windows 主机的计划任务(主机管理「计划任务」右键)。客户端无回执,工具只复核任务仍存在并报告当前状态,不声称任务一定执行成功。不提供创建/删除任务。dry_run=true 只核实任务并返回当前状态。",
MakeSchema(props, { "id", "action", "name" }),
ActionOutputSchema());
}
File diff suppressed because it is too large. Load diff
+97 -2
View File
@@ -50,6 +50,55 @@ struct ChatMessage {
std::string text;
};
// ===== P11:tools/call 的在飞上下文(progress / cancelled / 会话观测)=====
//
// 每一次 tools/call 都在服务端登记一个 McpCallContext(见 CMcpServer::BeginCall),
// 工具实现通过 CurrentMcpCall() 拿到它(实现是 FLS 每线程槽,不是 thread_local:
// 本工程有 shellcode 线程,thread_local 会让服务端启动即崩,原因见 McpServer.cpp):
// - 长任务在等待循环里调用 McpCallProgress(),按 1s 节流把
// notifications/progress 推给带 _meta.progressToken 的请求;
// - 等待循环用 McpCallCancelled() 尽早返回(notifications/cancelled 或
// mcp_cancel_session 置位后 ≤1 个等待切片退出,走既有的超时清理路径);
// - mcp_list_sessions 用它回答「谁占着这台主机」。
// channel 只在 SSE 请求上非空:进度通知随该请求自己的流下发,不需要额外的 GET 流。
struct McpProgressChannel; // 定义见 McpServer.cpp
struct McpCallContext {
std::string idKey; // JSON-RPC id 的紧凑序列化(字符串带引号;"41" 与 41 不混同)
std::string idText; // 同一 id 的展示文本(字符串取原文、整数取十进制),
// 与 mcp_list_sessions 的 request_id 一致,可按它回传取消
std::string tool;
uint64_t device = 0; // 参数里的 id(没有则为 0)
std::string sessionId; // 参数里的 session_id(没有则空)
std::chrono::steady_clock::time_point startedAt;
// 取消位:取消后工具层的等待按超时返回,服务端把最终错误统一改写成 -32800。
std::atomic<bool> cancelled{false};
// 进度通道:hasProgressToken=false 时一切进度调用都是空操作。
bool hasProgressToken = false;
std::string progressTokenJson; // progressToken 的 JSON 文本(原样回显)
std::shared_ptr<McpProgressChannel> channel;
std::mutex progressMu;
std::chrono::steady_clock::time_point lastProgressAt{};
// 节流(约 1s)后投递一条 progress 通知;没有 token/通道时直接返回。
void EmitProgress(double current, double total, bool hasTotal);
bool IsCancelled() const { return cancelled.load(std::memory_order_relaxed); }
};
// 当前工具调用的上下文(每线程槽;非 MCP 工具线程返回 nullptr)。
std::shared_ptr<McpCallContext> CurrentMcpCall();
// 当前调用是否已被取消(没有上下文时为 false)。
bool McpCallCancelled();
// 报告进度:McpCallProgress(n) 表示「进度 n、无总量」;带 total 的重载给出总量。
void McpCallProgress(double current);
void McpCallProgress(double current, double total);
// -32003 的正文:在通用句后附上「谁占着这台主机、已持续多久」(没有占用信息时原样返回
// base)。占着主机的是别的一次调用——当前这次 tools/call 自己会被排除。
std::string BusyMessage(const std::string& base, uint64_t devId);
// MCP (Model Context Protocol) 服务端:httplib 封装 + JSON-RPC 2.0 分发 + 静态 token 校验。
// 与 CWebService 平级、互不依赖;默认禁用,经「扩展 → MCP设置」开启后监听
// (默认 127.0.0.1:6544,仅本机回环)。见 docs/Mcp_Design.md。
@@ -531,8 +580,8 @@ public:
// 工具线程:发送结束(清 sendBusy)。closed 期间发送失败时调用方仍须调用。
void FinishChatSend(uint64_t device_id, const std::string& sessionId);
// 工具线程:取走最多 maxMessages 条;inbox 为空则等到 deadline / closed。
enum class ChatWaitResult { Ok, Timeout, Closed, NotFound, Mismatch, Busy };
// 工具线程:取走最多 maxMessages 条;inbox 为空则等到 deadline / closed / 取消。
enum class ChatWaitResult { Ok, Timeout, Closed, NotFound, Mismatch, Busy, Cancelled };
ChatWaitResult WaitChatMessages(uint64_t device_id, const std::string& sessionId,
int timeoutMs, size_t maxMessages,
std::vector<ChatMessage>& out, bool& timedOut,
@@ -565,6 +614,39 @@ public:
void GetRuntimeCounters(int& pending, int& terminal, int& screenCtrl,
int& fileXfer, int& chat, int& blockedIps);
// ===== P11:在飞调用登记(progress / cancelled / mcp_list_sessions)=====
// 每次 tools/call 登记一个上下文;EndCall 必须在工具返回后调用(幂等)。
// idKey / idText 是同一个 JSON-RPC id 的两种写法(紧凑 JSON / 展示文本),
// 匹配一律先按 idKey 精确比(区分 "41" 与 41),再退回 idText。
std::shared_ptr<McpCallContext> BeginCall(const std::string& idKey, const std::string& idText,
const std::string& tool,
uint64_t device, const std::string& sessionId);
void EndCall(const std::shared_ptr<McpCallContext>& call);
// notifications/cancelled:按 JSON-RPC id 匹配在飞调用,置取消位。返回是否命中。
bool CancelCallById(const std::string& idKey, const std::string& idText);
// mcp_cancel_session:按主机(device=0 表示任意)与会话 id(空表示任意)匹配在飞调用。
// 返回被取消的数量;工具层的等待会在 ≤1s 内退出并走既有清理路径。
int CancelCalls(uint64_t device, const std::string& sessionId);
// mcp_list_sessions 的快照条目(一把锁一次拷贝,不跨表保持一致性)。
struct SessionSnapshot {
uint64_t device = 0;
std::string kind; // pending / call / terminal / remote_control / file_transfer / chat
std::string tool;
std::string sessionId;
std::string idKey; // kind=call:JSON-RPC id 的紧凑序列化(匹配用,"41" 与 41 不同)
std::string requestId; // kind=call:同一 id 的展示文本(列表输出用,可直接回传 request_id)
bool busy = false;
long long elapsedMs = -1; // 会话已持续(<0 未知)
long long idleMs = -1; // 距最后一次活动(<0 未知)
};
std::vector<SessionSnapshot> ListSessions();
// -32003 文案后缀:说明该主机正被哪个工具占着、已持续多久;没有占用信息时返回空串。
std::string DescribeBusy(uint64_t device_id);
private:
CMcpServer();
~CMcpServer();
@@ -626,6 +708,8 @@ private:
struct PendingRequest {
std::string tool;
std::string path; // list_files:目录路径;list_registry:rootToken(1B)+相对子键路径
// P11:mcp_list_sessions 展示用。默认取构造时刻,所有 Begin* 都不必显式设置。
std::chrono::steady_clock::time_point startedAt = std::chrono::steady_clock::now();
uint16_t expectedReqId = 0; // get_screenshot:期望的预览 reqId(0 = 未设置)
std::vector<BYTE> data;
std::vector<BYTE> regPath; // list_registry:TOKEN_REG_PATH 子键包(含 token 字节)
@@ -664,6 +748,11 @@ private:
std::condition_variable m_PendingCv;
std::map<uint64_t, PendingRequest> m_Pending;
// ===== P11:在飞 tools/call 上下文(受 m_CallMutex 保护)=====
// 向量足够:同时在飞的调用只有个位数,取消/列举都是全表扫描。
std::mutex m_CallMutex;
std::vector<std::shared_ptr<McpCallContext>> m_Calls;
// ===== P8:子连接路由(受 m_PendingMutex 保护)=====
// 已绑定子连接 → device(该子连接的一切包都由 MCP 消费)。
std::map<context*, uint64_t> m_SubCtxToDevice;
@@ -717,6 +806,7 @@ private:
bool persistent = false;
bool busy = false; // 一条命令在飞(terminal_exec 复位→WaitTermCommand 返回)
time_t lastActiveAt = 0; // idle 回收用(秒)
std::chrono::steady_clock::time_point startedAt = std::chrono::steady_clock::now(); // P11
};
std::mutex m_TermMutex;
std::condition_variable m_TermCv;
@@ -740,6 +830,7 @@ private:
bool busy = false; // 一条注入在飞(BeginScreenCtrlAction→End 之间)
bool closed = false; // 注入期间屏幕子连接已断(由注入线程收尾)
time_t lastActiveAt = 0; // idle 回收用(秒)
std::chrono::steady_clock::time_point startedAt = std::chrono::steady_clock::now(); // P11
int screenW = 0; // 物理捕获分辨率(来自 TOKEN_BITMAPINFO)
int screenH = 0;
// P10-C 键鼠锁定:inputBlocked 是服务端认为的锁定状态(唯一真相,用于强制解锁);
@@ -785,6 +876,9 @@ private:
std::set<uint32_t> skipIndexes; // overwrite=false 跳过的 fileIndex
std::vector<FileTransferEntry> skipped; // 跳过的文件(供输出)
time_t startAt = 0;
std::chrono::steady_clock::time_point startedAt = std::chrono::steady_clock::now(); // P11
// P11:已收到的数据字节数(进度通知用;download 按 chunk 累加)
uint64_t bytesReceived = 0;
// 停滞看门狗:最后一次收到数据的时间。远程路径不存在时客户端一个包都不发,
// 旧实现只能干等满 timeout_ms(默认 600s,整台主机被单飞互斥锁住,评审 P2)。
std::chrono::steady_clock::time_point lastDataAt;
@@ -810,6 +904,7 @@ private:
bool waitBusy = false; // 同一会话只允许一个 chat_wait
std::chrono::steady_clock::time_point readyAt; // 建窗等待期满(绑定 + 1000ms)
time_t lastActiveAt = 0;
std::chrono::steady_clock::time_point startedAt = std::chrono::steady_clock::now(); // P11
std::deque<ChatMessage> inbox; // 未投递消息(UTF-8)
size_t inboxBytes = 0;
uint64_t nextMsgId = 1;