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:
1 parent
3d388f8e45
commit
1c832ff7f2
10 files changed
+1855
-107
No files matched your search
@@ -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;
|
||||
|
||||
Reference in new issue
Block a user