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

+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());
}