Feature: Add MCP tools for remote chat with the client user

Add chat_open, chat_send, chat_wait and chat_close to the MCP tool set,
behind a new McpChat switch that defaults to off and is independent of
the read-only switch. The tools reuse the existing client chat link: the
main connection sends COMMAND_CHAT, the client opens a sub-connection
with TOKEN_CONN_AUTH and TOKEN_CHAT_START, the server answers with
COMMAND_NEXT_CHAT, and both directions then carry raw CP936 text.

Sessions are per host and held in shared pointers under their own mutex,
so a waiting chat_wait survives a close or a dropped sub-connection, and
chat_send is serialised per session. Text is converted strictly between
UTF-8 and CP936: invalid UTF-8, characters GBK cannot represent (emoji,
accented letters) and messages over the client's 4000-byte buffer are
rejected with -32602 instead of being mangled. A one-second settle delay
after the sub-connection binds keeps the first message from reaching the
client before its chat window exists.

The routing hooks run before the host-management hooks in MessageHandle
and clear the route in OfflineProc before the context leaves the list. A
five-second tombstone absorbs a late TOKEN_CHAT_START after a timeout, so
a failed chat_open does not pop the MFC chat dialog. Idle sessions are
swept on every tool call, and audit entries record the session id and
byte counts only, never message bodies.

The settings dialog gains the chat checkbox and the translated labels
for all three languages, and the strict UTF-8 to CP936 helpers move from
McpMachine.cpp to McpInternal so both tool families can share them.

Co-Authored-By: deepseek-flash
This commit is contained in:
yuanyuanxianganddeepseek-flash committed 2026-10-23 11:19:21 +02:00
1 parent fff7c67af6
commit c99a1c375e
17 files changed
+1519 -31

No files matched your search

+99
View File
@@ -10,6 +10,8 @@
#include <map>
#include <set>
#include <vector>
#include <deque>
#include <memory>
#include <cstdint>
#include <ctime>
@@ -37,6 +39,14 @@ struct FileTransferEntry {
std::string sha256;
};
// 远程交谈消息(chat_wait 输出 messages[] 的一项)。
// text 为 UTF-8;at 为收到消息的 Unix 秒;id 为会话内单调递增序号。
struct ChatMessage {
uint64_t id = 0;
int64_t at = 0;
std::string text;
};
// MCP (Model Context Protocol) 服务端:httplib 封装 + JSON-RPC 2.0 分发 + 静态 token 校验。
// 与 CWebService 平级、互不依赖;默认禁用,经「扩展 → MCP设置」开启后监听
// (默认 127.0.0.1:6544,仅本机回环)。见 docs/Mcp_Design.md。
@@ -305,6 +315,57 @@ public:
// (吸收迟到的 61/255,避免超时后弹出 MFC 对话框)。
void EndManagedSession(uint64_t device_id, bool cancelIo, bool markOrphan);
// ===== P9:远程交谈(chat_open / chat_send / chat_wait / chat_close)=====
// 复用 Windows 客户端既有「远程交谈」:主连接下发 COMMAND_CHAT(161) → 客户端新建子连接
// (先 TOKEN_CONN_AUTH(246) 再 TOKEN_CHAT_START(62))→ 服务端在该子连接回
// COMMAND_NEXT_CHAT(0) → 客户端弹 IDD_CHAT。之后双向文本为 raw CP936 + NUL。
// 协议不变(客户端聊天窗口已改为 Unicode 对话框,仅影响显示);独立 m_ChatMutex,
// 不与 P8 的 m_Pending 共享(不受单设备单飞行约束)。
// 见 docs/Mcp_Chat_Design.md。
void SetChatEnabled(bool enabled) { m_chatEnabled = enabled; }
bool IsChatEnabled() const { return m_chatEnabled; }
// MessageHandle 顶部钩子(MCP 终端之后、P8 之前:聊天文本首字节可能是 61/255/246)。
// true = 本包已由 MCP 消费。未绑定子连接上的 246(TOKEN_CONN_AUTH) 走快速路径返回
// false,交给认证分支;已绑定子连接上的 0xF6 前导字节文本则由本函数消费。
bool OnChatSubPacket(context* subCtx, const BYTE* data, ULONG len);
// OfflineProc 钩子:接管的子连接断开 → 会话 closed + 清路由 + 唤醒等待者(幂等)。
void OnChatContextClosed(context* subCtx);
// 工具线程:登记会话并发 COMMAND_CHAT 之后调用。false = 该设备已有未关闭会话(-32003)。
bool BeginChatOpen(uint64_t device_id, context* mainCtx, const std::string& sessionId);
// 工具线程:等待客户端子连接就绪且建窗等待期满(readyAt)。
enum class ChatReadyResult { Ok, Timeout, Closed, NotFound };
ChatReadyResult WaitChatReady(uint64_t device_id, const std::string& sessionId, int timeoutMs);
// 工具线程:发送前登记(校验 sessionId/started/readyAt/sendBusy)。输出 subCtx。
// 返回:0=ok;1=不存在/不匹配/未就绪/已关;2=忙。
int BeginChatSend(uint64_t device_id, const std::string& sessionId, context*& subCtx);
// 工具线程:发送结束(清 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 };
ChatWaitResult WaitChatMessages(uint64_t device_id, const std::string& sessionId,
int timeoutMs, size_t maxMessages,
std::vector<ChatMessage>& out, bool& timedOut,
bool& closed, int& dropped);
// 关闭会话(校验 sessionId;标记 closed + 清路由 + 唤醒)。返回 0=已关;1=不存在(幂等);
// 2=sessionId 不匹配。子连接 [1] 与 CancelIO 由调用方在锁外执行。
int CloseChatSession(uint64_t device_id, const std::string& sessionId,
context*& subCtxOut, bool& hadSession);
// chat_open 超时/失败收尾:标记 closed + 清路由;已绑定子连接写入 subCtxOut(调用方 CancelIO),
// 未绑定则打 device/peer 5s 墓碑,吸收迟到的 62(避免超时后弹出 MFC 对话框)。
void AbortChatOpen(uint64_t device_id, context*& subCtxOut, bool& hadSession);
// idle 回收:关闭 lastActiveAt 超时且无等待/无发送的会话。返回回收数量。
int SweepIdleChats(time_t idleTimeoutSec);
// 安全配置(启动时由 CMy2015RemoteDlg 读 THIS_CFG 后设置)。
void SetReadonly(bool readonly) { m_readonly = readonly; }
void SetCmdWhitelist(const std::string& whitelist) { m_cmdWhitelist = whitelist; }
@@ -451,6 +512,44 @@ private:
std::condition_variable m_FileXferCv;
std::map<uint64_t, FileTransferSession> m_FileXferSessions; // device_id → 会话
// ===== P9:远程交谈(受 m_ChatMutex 保护;单设备单会话)=====
// 用 shared_ptr 持有会话:chat_wait / chat_send 在工作线程里复制一份后,即使 map 条目
// 被 chat_close 或断线删除也安全,不需要额外的「迭代器有效」规则。
struct ChatSession {
std::string sessionId;
context* mainCtx = nullptr; // 主连接(仅身份校验)
uint64_t mainClientId = 0;
context* subCtx = nullptr; // 已绑定的子连接;关闭后置空
std::string peer; // GetPeerName()(老客户端 clientID=0 兜底)
bool started = false; // 已收到 TOKEN_CHAT_START 并回 [0]
bool closed = false;
bool sendBusy = false; // 同一会话串行发送
bool waitBusy = false; // 同一会话只允许一个 chat_wait
std::chrono::steady_clock::time_point readyAt; // 建窗等待期满(绑定 + 1000ms)
time_t lastActiveAt = 0;
std::deque<ChatMessage> inbox; // 未投递消息(UTF-8)
size_t inboxBytes = 0;
uint64_t nextMsgId = 1;
int dropped = 0; // inbox 溢出丢弃的条数(chat_wait 报告)
};
using ChatSessionPtr = std::shared_ptr<ChatSession>;
std::mutex m_ChatMutex;
std::condition_variable m_ChatCv;
std::map<uint64_t, ChatSessionPtr> m_ChatSessions; // device_id → 会话
std::map<context*, uint64_t> m_ChatContextToDevice; // subCtx → device_id(顶部路由)
std::set<context*> m_ChatAbsorbedSubCtx; // CancelIO 后尾巴包静默丢弃
struct ChatOrphanMark { std::chrono::steady_clock::time_point expiry; };
std::map<uint64_t, ChatOrphanMark> m_ChatOrphanByDevice; // 迟到 62 墓碑(5s)
std::map<std::string, ChatOrphanMark> m_ChatOrphanByPeer;
std::atomic<int> m_ChatRoutes{0}; // 路由集合大小(快速路径)
bool m_chatEnabled = false; // P9 开关(默认关)
// 持 m_ChatMutex 调用:只更新 m_ChatRoutes(store,relaxed 读取在锁外)。
void RefreshChatRoutesLocked();
// 持 m_ChatMutex 调用:清理过期墓碑。
void PruneChatOrphansLocked(std::chrono::steady_clock::time_point now);
bool m_readonly = true;
std::string m_cmdWhitelist;
bool m_terminalEnabled = false; // 持久终端开关(默认关;要求 m_readonly=false)