Compare commits
3
Commits
cc0e4bbd7a
...
8f718d9b39
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8f718d9b39 | ||
|
|
abe7e99a77 | ||
|
|
ac5b174b5f |
No files matched your search
+27
-2
@@ -433,9 +433,15 @@ UINT CFileManager::SendFilesList(LPCTSTR lpszDirectory)
|
||||
m_nTransferMode = TRANSFER_MODE_NORMAL;
|
||||
|
||||
// 展开环境变量 (如 %USERPROFILE%, %DESKTOP% 等)
|
||||
char szExpandedDir[MAX_PATH];
|
||||
char szExpandedDir[MAX_PATH] = { 0 }; // 展开失败时保持空串,避免下面的长度判断读未初始化栈
|
||||
ExpandEnvironmentStringsA(lpszDirectory, szExpandedDir, MAX_PATH);
|
||||
|
||||
// 展开失败 / 目录 + "\*.*" + NUL 装不下:按空目录回(放在分配缓冲之前,免得多一条泄漏路径)
|
||||
if (szExpandedDir[0] == '\0' || lstrlenA(szExpandedDir) + 5 > MAX_PATH) {
|
||||
BYTE bToken = TOKEN_FILE_LIST;
|
||||
return Send(&bToken, 1);
|
||||
}
|
||||
|
||||
UINT nRet = 0;
|
||||
char strPath[MAX_PATH];
|
||||
char *pszFileName = NULL;
|
||||
@@ -556,6 +562,10 @@ void CFileManager::SearchFilesRecursive(LPCTSTR lpszDirectory, LPCTSTR lpszPatte
|
||||
return;
|
||||
}
|
||||
|
||||
// wsprintf 不做边界检查,超长会写穿栈(Debug 版弹 Run-Time Check Failure #2,
|
||||
// Release 版静默破坏栈)。递归最多 32 层,深度累加很容易超过 MAX_PATH,必须逐层预判。
|
||||
if (lstrlenA(lpszDirectory) + 5 > MAX_PATH) return; // 目录 + "\*.*" + NUL
|
||||
|
||||
char strPath[MAX_PATH];
|
||||
WIN32_FIND_DATA FindFileData;
|
||||
|
||||
@@ -572,6 +582,11 @@ void CFileManager::SearchFilesRecursive(LPCTSTR lpszDirectory, LPCTSTR lpszPatte
|
||||
|
||||
BOOL bIsDir = FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
|
||||
|
||||
// 单个条目也要预判:全路径装不下就跳过(既不记录也不递归进去),
|
||||
// 否则下面的 wsprintf 会写穿 szFullPath。
|
||||
if (lstrlenA(lpszDirectory) + 1 + lstrlenA(FindFileData.cFileName) + 1 > MAX_PATH)
|
||||
continue;
|
||||
|
||||
char szFullPath[MAX_PATH];
|
||||
wsprintf(szFullPath, "%s\\%s", lpszDirectory, FindFileData.cFileName);
|
||||
|
||||
@@ -646,11 +661,21 @@ DWORD WINAPI CFileManager::SearchThreadProc(LPVOID lpParam)
|
||||
void CFileManager::SearchFiles(LPCTSTR lpszSearchPath, LPCTSTR lpszSearchName)
|
||||
{
|
||||
// 展开环境变量
|
||||
char szExpandedPath[MAX_PATH];
|
||||
char szExpandedPath[MAX_PATH] = { 0 }; // 展开失败时为空串,递归里直接返回
|
||||
ExpandEnvironmentStringsA(lpszSearchPath, szExpandedPath, MAX_PATH);
|
||||
|
||||
if (szExpandedPath[0] == '\0') { // 展开失败:直接按「0 条结果」结束
|
||||
SendToken(TOKEN_SEARCH_FILE_FINISH);
|
||||
return;
|
||||
}
|
||||
|
||||
// 构建搜索模式 (如 *.txt 或 *keyword*)
|
||||
char szPattern[MAX_PATH];
|
||||
// 关键字来自网络包,最多 MAX_PATH 字节,加通配符后可能超出 szPattern。
|
||||
if (lstrlenA(lpszSearchName) + 3 > MAX_PATH) {
|
||||
SendToken(TOKEN_SEARCH_FILE_FINISH);
|
||||
return;
|
||||
}
|
||||
if (strchr(lpszSearchName, '*') == NULL && strchr(lpszSearchName, '?') == NULL) {
|
||||
wsprintf(szPattern, "*%s*", lpszSearchName);
|
||||
} else {
|
||||
|
||||
@@ -573,6 +573,11 @@ UINT CFileManager::SendFilesList(TCHAR* lpszDirectory)
|
||||
else
|
||||
lpszSlash = _T("");
|
||||
TCHAR str_last[] = { _T('%'),_T('s'),_T('%'),_T('s'),_T('*'),_T('.'),_T('*'),_T('\0') };
|
||||
// wsprintf 不做边界检查:目录 + "\*.*" + NUL 装不下就按空目录回,别写穿 strPath。
|
||||
if ((int)(_tcslen(lpszDirectory) + _tcslen(lpszSlash)) + 4 > MAX_PATH) {
|
||||
BYTE bToken = TOKEN_FILE_LIST;
|
||||
return Send(&bToken, 1);
|
||||
}
|
||||
wsprintf(strPath, str_last, lpszDirectory, lpszSlash);
|
||||
hFile = FindFirstFile(strPath, &FindFileData);
|
||||
|
||||
|
||||
@@ -258,6 +258,7 @@ Json::Value BuildHostJson(context* ctx, _ClientList* clientMap);
|
||||
| `McpPort` | `6544` | MCP 监听端口;仅当 `McpEnabled=1` 时生效;未配置用默认 `6544` |
|
||||
| `McpBind` | `127.0.0.1` | 监听地址;默认仅本机;可设 `0.0.0.0`(所有网卡)或内网 IP(如 `192.168.0.92`)以支持远程 |
|
||||
| `McpToken` | 空(UI 默认随机值) | 静态 token;对话框内「token 必填、默认随机值」——首次打开若为空则预填随机并随保存持久化。运行时优先级:env `YAMA_MCP_TOKEN` → `McpToken` → 皆空则随机生成(见 §3.5) |
|
||||
| `McpKeylog` | `0` | 键盘记录工具 `get_keylog` 的独立开关(见 §9.3);与 `McpReadonly` 无关,改动需重启生效 |
|
||||
|
||||
> 与旧版「`McpPort=0` 即禁用」不同:启用与否改由独立的 `McpEnabled` 开关控制,`McpPort` 回归纯端口语义,二者解耦。
|
||||
|
||||
@@ -444,3 +445,132 @@ void CMcpSettingsDlg::OnBnClickedBtnSave()
|
||||
- ✅ **取数方案**:C(抽公共函数 `BuildHostJson`,MCP 与 WebService 平级复用)。
|
||||
- ✅ **返回字段**:全量,含实时信息(`rtt` / `activeWindow`),支持 AI 监督场景。
|
||||
- ✅ **序列化**:`structuredContent` + `outputSchema`,`content` 附带可读摘要。
|
||||
|
||||
---
|
||||
|
||||
## 9. 增补(2026-10-25:N1–N5)
|
||||
|
||||
本轮在既有工具族(P2–P9)之上补齐「能找到主机、能一次查多台、输出不撑爆上下文、认证可追溯」四件事,全部为服务端改动,客户端零改动。
|
||||
|
||||
### 9.1 N1 离线主机可见
|
||||
|
||||
- 新增工具 `list_all_hosts`(`online` / `offline` 两个布尔过滤,默认都为 `true`),数据源是 `m_ClientMap`(主机列表历史记录,`GetAll()` 快照 + `m_cs` 保护),在线条目复用 `BuildHostJson`,离线条目由 `BuildOfflineHostJson` 生成,字段:`id` / `name` / `remark` / `ip` / `os` / `location` / `online` / `group` / `last_seen` / `install_time` / `authStatus`。
|
||||
- `search_hosts` 的 `online` 参数:`true` = 仅在线,`false` = 仅离线(修复此前 `online=false` 永远返回空列表的问题),缺省 = 仅在线(与改动前一致,不改变既有调用方看到的结果)。两类都要请用 `list_all_hosts`。
|
||||
- `authStatus` 是 `ClientValue::Authorized` 的三态枚举(`unauthorized` / `authorized_by_super` / `authorized_by_admin` / `forbidden`),不是布尔值。
|
||||
- `get_host_detail` 对「在 `m_ClientMap` 里但当前离线」的 id 不再返回 `-32002`,改为返回该主机的最后记录(`online=false`),使 `list_all_hosts` 的结果可直接消费。
|
||||
|
||||
### 9.2 N2 批量只读调用
|
||||
|
||||
- 只读工具支持 `ids: []`(最多 50 个),与 `id` 二选一(inputSchema 用 `anyOf` 表达)。命中批量的工具:`get_host_detail` / `list_processes` / `list_windows` / `list_services` / `list_files` / `list_registry` / `get_client_log` / `get_activity_history` / `list_network_connections` / 全部 `host_list_*` / `host_get_hosts_file`。
|
||||
- 写操作工具传 `ids` 直接 `-32602` 拒绝(不逐个执行,避免误操作扩散)。
|
||||
- 返回:`{tool, total, succeeded, failed, results:[{id, ok, data|error, text}]}`;`content` 里是「共 N 台,成功 X 台,失败 Y 台」+ 最多 ~1200 字节的失败明细。
|
||||
- `limit` / `offset` 对每台主机各自生效;批量是串行执行,单台超时会占用整批等待时间。
|
||||
|
||||
### 9.3 N3 `get_keylog`
|
||||
|
||||
- 复用客户端既有键盘记录链路:主连接下发 `COMMAND_KEYBOARD(169)` → 客户端建子连接 → 子连接回 `TOKEN_KEYBOARD_START(293)` 作为就绪包绑定 → 之后每约 1 秒推一包 `TOKEN_KEYBOARD_DATA(294)`。
|
||||
- 服务端把击键流**累积**(不是一问一答),窗口 `duration_ms`(默认 4000,1000–15000)或字节上限 `max_bytes`(默认 64 KiB,1024–256 KiB)先到者结束;结束时 `EndManagedSession(..., cancelIo=true)` 关闭子连接 —— 与 MFC 关对话框同一路径,客户端据此停止记录。
|
||||
- 复用 P8 的挂起会话表(新增 `PendingKind::Keylog`,仍受「单设备单飞行」约束),就绪包绑定、迟到包墓碑、子连接断开唤醒全部沿用 P8 逻辑;绑定后服务端回 `COMMAND_NEXT`,让客户端 `WaitForDialogOpen` 立即返回(本工具不开 UI)。
|
||||
- 返回 `{id, duration_ms, bytes, lines, lineCount, truncated}`,文本按客户端代码页转 UTF-8(`GetClientEncoding`)。**注意**:客户端连上后会先把缓冲区里已有的历史记录推过来,所以结果既含历史也含窗口期内的新击键。
|
||||
- 独立开关 `McpKeylog`(默认 `0`,不要求只读关)。工具只在开关打开时出现在 `tools/list`,关闭时直接调用返回 `-32006`。
|
||||
- 隐私:击键内容只进本次响应;审计只记 `CALL_OK tool=get_keylog ms=… bytes=…`,不落任何正文。
|
||||
|
||||
### 9.4 N4 认证加固
|
||||
|
||||
- 静态 token 校验失败:返回 401,并按来源 IP 计数;60 秒窗口内失败 10 次即封禁该 IP 900 秒,封禁期内返回 429 + `Retry-After`。失败表上限 1024,满时先清理过期项。
|
||||
- 环回来源(`127.0.0.1` / `::1`)**只记账不封禁**:内置 frpc 把 MCP 端口映射出去时是「本机连本机」,且这条转发没开 Proxy Protocol(httplib 不解析),服务端看到的源地址恒为环回。若按 IP 封禁,一次外部扫描就能把隧道后面所有客户端(包括自己)锁死 15 分钟。审计里这类封禁触发记为 `AUTH_BLOCK ... scope=proxy-source-exempt`。
|
||||
- 审计文件 `<exe>\logs\mcp_audit.log`(追加写,5 MB 轮转为 `.1`),每行:时间戳(毫秒)、事件、来源 IP、详情。
|
||||
- `AUTH_FAIL`:UA(截断/清洗)、body 大小、是否因此被封禁。
|
||||
- `AUTH_BLOCK`:封禁生效。
|
||||
- `CALL_OK` / `CALL_FAIL`:`tool=`、耗时 `ms=`、响应字节数 `bytes=`。
|
||||
- 审计**不记录** token、密码、哈希、剪贴板内容或工具返回正文。
|
||||
|
||||
### 9.5 N5 列表输出治理
|
||||
|
||||
- 列表类工具统一 `limit` / `offset`:默认 `limit=100`,硬上限 `1000`,`offset` 默认 0;非正数按默认值处理。
|
||||
- `structuredContent` 统一附 `total` / `totalAll` / `offset` / `limit` / `hasMore`,与 `McpMachine.cpp` 既有约定一致(`host_list_*` / `list_network_connections` 本来就是这样)。
|
||||
- `content` 摘要统一为「共 N <单位>,本次返回第 a-b 条(还有更多,可用 offset 继续取)。」;`hasMore=false` 时不再出现「继续取」的误导提示;`offset` 越界时明确写「offset 超出范围,本次返回 0 条」。
|
||||
- 实现集中在 `McpInternal.h/.cpp`:`PageWindow` / `ResolvePageWindow` / `ApplyPageWindow` / `WritePageFields` / `AppendPagingProps` / `PageSummary`。
|
||||
- `list_files` 仍受客户端单次 500 条的硬限制(`total=500` 表示客户端截断,不是服务端分页)。
|
||||
|
||||
---
|
||||
|
||||
## 10. 增补(2026-10-25:A 批加固 / B 批非破坏性能力)
|
||||
|
||||
A 批只改服务端传输、元数据与校验,不动任何既有工具语义;B 批新增三个工具(两个写主机库、一个远程搜索)。**客户端零改动。**
|
||||
|
||||
### 10.1 A1/A2 传输层加固(`CMcpServer::Start`)
|
||||
|
||||
httplib 默认值对 MCP 场景不合适,改为显式配置:
|
||||
|
||||
| 项 | 默认 | 现在 | 原因 |
|
||||
|---|---|---|---|
|
||||
| 请求体上限 | 不限(`SIZE_MAX`) | 2 MB(超出 413 `RequestEntityTooLarge`) | 只收 JSON 参数,文件内容走子连接分块,绝不进 HTTP body |
|
||||
| 读超时 | 5s | 15s | 经 frp 隧道上传参数时,单次 recv 不该 5s 就断 |
|
||||
| 写超时 | 5s | 60s | `get_screenshot` 大图 base64、慢链路下 5s 会写断响应 |
|
||||
| 线程池 | `max(8, 核数-1)` | 固定 32 | `chat_wait`(最长 55s)与批量只读会长期占线程 |
|
||||
|
||||
读超时是 **socket 空闲读超时**,不是「处理时长上限」:`search_file` 阻塞 20s、`chat_wait` 阻塞 55s 都正常返回(已实测)。
|
||||
|
||||
### 10.2 A3 工具注解(`McpInternal::ApplyToolAnnotations`)
|
||||
|
||||
- `tools/list` 每个工具都带 `annotations`:`readOnlyHint` / `destructiveHint` / `idempotentHint` / `openWorldHint`,由 `McpInternal.cpp` 的 `kToolHints` 表按名登记,末尾统一补一次。
|
||||
- 未登记的工具按规范默认值处理(`destructiveHint=true`),即**新增工具必须显式登记**,漏登记只会更保守,不会误标成只读。
|
||||
- 只读工具的 `destructiveHint` 一律 `false`(按规范对只读工具无意义,避免客户端误报「破坏性」)。
|
||||
- `openWorldHint=false` 只给「只读服务端本机状态」的工具(`list_online_hosts` / `search_hosts` / `list_all_hosts` / `get_host_detail` / `get_activity_history` / `get_audit_log`),其余都会触达外部主机。
|
||||
|
||||
### 10.3 A4 `get_host_detail` 字段补全
|
||||
|
||||
在线主机现在返回:`id` / `name` / `online` / `ip` / `publicIp` / `location` / `group` / `os` / `version` / `exeVersion` / `clientType` / `clientPath` / `systemBits` / `programBits` / `cpuCores` / `memoryGB` / `monitors` / `screen` / `user` / `isAdmin` / `pid` / `installTime` / `activeWindow` / `rtt` / `tls`;离线主机返回 `authStatus` / `last_seen` / `install_time` 等最后记录。
|
||||
|
||||
注意 `memoryGB` 是 **double**:客户端 `GetMemorySizeGB()` 上报的就是浮点字符串(如 `"27.800000000000001"` 的原始形态),不能按整数解析。服务端按 1 位小数规范化,并给 jsoncpp 写入器设 15 位有效数字,避免输出 17 位噪声。
|
||||
|
||||
### 10.4 B1 主机库写入:`host_set_remark` / `host_set_watch_level`
|
||||
|
||||
- 写的是服务端本机的 `_ClientList`(`MAP_NOTE` / `MAP_LEVEL`),**只影响主控端自己的展示**:不下发命令、不改远端状态。
|
||||
- 门控:`McpReadonly=0` 即可(不要求 `McpManage`);在线/离线(历史记录)主机都能写,id 在主机库中存在即可。
|
||||
- `host_set_remark`:`remark` 必填(空串 = 清除),**严格 GBK 转换**(emoji、`ö` 等不可表示字符报 `-32602`),长度上限 63 GBK 字节(主机库列 `char Note[64]`)。
|
||||
- `host_set_watch_level`:`level` 0–3。重复写同一值幂等。
|
||||
- 写后 `SaveToFile(GetDbPath())` 落库,并用 `LVM_REDRAWITEMS` 让在线列表那一行立刻刷新(MCP 线程不直接碰 `CListCtrl`)。
|
||||
- 审计只记「set/cleared + 字节数」与 `level=`,**不记录备注正文**。
|
||||
|
||||
### 10.5 B2 远程文件搜索:`search_file`
|
||||
|
||||
**链路**(旧文件管理器,不是 SimplePlugins 版):
|
||||
|
||||
```
|
||||
主连接 COMMAND_LIST_DRIVE → 客户端建子连接 → 子连接回 TOKEN_DRIVE_LIST
|
||||
→ 服务端 OnDriveList 下发 COMMAND_SEARCH_FILE [根目录 \0][模式 \0](ANSI/GBK 两个 C 串)
|
||||
→ N × TOKEN_SEARCH_FILE_LIST(分片)→ TOKEN_SEARCH_FILE_FINISH
|
||||
```
|
||||
|
||||
协议来自 `client/FileManager.cpp`(`COMMAND_LIST_DRIVE` → `LoopFileManager` → `CFileManager`)。客户端工程是 MultiByte,所有字段都是 GBK,服务端用 `Utf8ToCpExact` 严格转换,不可表示即 `-32602`。
|
||||
|
||||
要点:
|
||||
|
||||
- **模式**:不含 `*` / `?` 时客户端当成 `*pattern*`(不区分大小写的子串),含通配符时走 `WildcardMatch`。
|
||||
- **递归**:客户端只有递归搜索(深度 32,最多 10000 条,跳过隐藏/系统目录与重解析点)。`recursive=false` 由**服务端按「父目录 == 根目录」过滤**实现。
|
||||
- **路径归一化**:客户端用 `wsprintf("%s\\*.*")` 枚举,根目录带尾部反斜杠会拼成 `C:\\*.*` 导致 `FindFirstFile` 失败、搜索秒回 0 条。服务端统一切成正斜杠→反斜杠并去尾斜杠(`C:\` → `C:`,客户端再拼回 `C:\*.*`)。
|
||||
- **超时**:`timeout_ms` 默认 20000(1000–120000)。到点先下发 `COMMAND_FILES_SEARCH_STOP`,再等 5s 收尾;收不到 `FINISH` 也返回已收到的部分结果,`finished=false`。
|
||||
- **收集上限**:5000 条 / 4 MB 原始包,超出即让客户端停搜并置 `truncated=true`(保护服务端内存,整盘搜索能命中几十万条)。
|
||||
- **子连接身份校验**:`TOKEN_SEARCH_FILE_LIST` / `TOKEN_SEARCH_FILE_FINISH` 都按 `context*` 比对当前 pending 的子链接,旧搜索(已放弃)的尾包一律不受理,避免迟到的 FINISH 终止新搜索。
|
||||
- **已知风险(客户端既有缺陷,未修)**:`client/FileManager.cpp` 的 `SearchFilesRecursive` 用无界 `wsprintf` 往 `char[MAX_PATH]` 里拼路径(`strPath` 第 562 行、`szFullPath` 第 578 行),全程没有长度检查。目录一深(累计路径超过 260)就栈溢出:Debug 客户端弹 `Run-Time Check Failure #2 - Stack around the variable 'strPath' was corrupted` 并挂住搜索线程,Release 客户端静默破坏栈。MFC 文件管理器的「搜索」走同一函数,**与 MCP 无关**(本工具只是让它更容易被触发)。规避:只搜具体的中浅层目录,别从盘符根开始深搜。
|
||||
- **无头路由**:MFC 对话框存在时搜索结果走 `OnReceiveComplete`;只有无头子连接(MCP 调用)才会进 `MessageHandle`,所以这两条 case 只影响 MCP。`TOKEN_SEARCH_FILE_LIST` 分支**绝不 CancelIO**(后面还有 FINISH 与剩余分片)。
|
||||
- 输出:`{files:[{path,name,dir,size,modified}], finished, truncated, total, totalAll, offset, limit, hasMore}`。
|
||||
|
||||
### 10.6 A5 冒烟测试脚本
|
||||
|
||||
`tools/mcp_smoke.ps1`:只调只读工具(列表/详情/搜索 + 传输层负例),断言分页字段、注解、401/413、批量汇总。
|
||||
|
||||
```powershell
|
||||
$env:YAMA_MCP_TOKEN = '<token>'
|
||||
powershell -ExecutionPolicy Bypass -File tools\mcp_smoke.ps1 # 默认 6544(Release)
|
||||
powershell -ExecutionPolicy Bypass -File tools\mcp_smoke.ps1 -Base http://127.0.0.1:6545/mcp
|
||||
```
|
||||
|
||||
token 只从 `-Token` / env 读取,不落仓库、不打印;无在线主机时加 `-SkipHost`。退出码 0/1,可接 CI。
|
||||
|
||||
### 10.7 明确不做的两项
|
||||
|
||||
- `get_clipboard`:剪贴板常含口令/令牌/私钥,属"读即泄密",且客户端没有"只读不覆盖"的现成链路;已有 `remote_clipboard` 覆盖写。需要时用 `get_screenshot` + 人工确认。
|
||||
- `close_window`:`operate_window` 的 `close` 动作已覆盖(同一 `COMMAND_WINDOW_CONTROL` 链路),不重复造工具。
|
||||
@@ -2430,6 +2430,8 @@ BOOL CMy2015RemoteDlg::OnInitDialog()
|
||||
THIS_CFG.GetInt("settings", "McpMachineDangerous", 0) != 0);
|
||||
// P9 远程交谈(chat_*):独立开关默认关,与只读开关无关。
|
||||
McpServer().SetChatEnabled(THIS_CFG.GetInt("settings", "McpChat", 0) != 0);
|
||||
// N3 键盘记录(get_keylog):独立开关默认关,与只读开关无关。
|
||||
McpServer().SetKeylogEnabled(THIS_CFG.GetInt("settings", "McpKeylog", 0) != 0);
|
||||
if (!McpServer().Start(mcpBind, mcpPort)) {
|
||||
Mprintf("McpServer start failed on %s:%d\n", mcpBind.c_str(), mcpPort);
|
||||
} else {
|
||||
@@ -6865,6 +6867,25 @@ VOID CMy2015RemoteDlg::MessageHandle(CONTEXT_OBJECT* ContextObject)
|
||||
ContextObject->CancelIO(); // 无论是否命中,用完即关(无 MFC 对话框接管此子链接)
|
||||
break;
|
||||
}
|
||||
case TOKEN_SEARCH_FILE_LIST: { // 搜索结果【B2:仅 MCP 无头搜索会到达】
|
||||
// 有挂起的 search_file 且是本连接发的 → 收下这一包;否则是已被放弃的旧搜索
|
||||
// (工具线程已超时返回部分结果)的尾包,原地丢弃即可。
|
||||
// 注意:这里绝不能 CancelIO。客户端搜索线程持有 CFileManager 的 this 指针,
|
||||
// 且关连接后 ~CFileManager(client/FileManager.cpp)只会 m_bSearching=false 并
|
||||
// 最多等 5s;线程若正在 FindFirstFile 里就会继续跑。子连接统一等
|
||||
// TOKEN_SEARCH_FILE_FINISH 再关——那时客户端搜索线程已经退出。
|
||||
uint64_t devId = ContextObject->GetClientID();
|
||||
McpServer().OnSearchFileRecords(devId, ContextObject, szBuffer, len);
|
||||
break;
|
||||
}
|
||||
case TOKEN_SEARCH_FILE_FINISH: { // 搜索结束【B2】
|
||||
// 客户端是「先停搜索线程、再发 FINISH」(自然结束或收到 COMMAND_FILES_SEARCH_STOP
|
||||
// 后下一轮循环退出),所以 FINISH 到达时关子连接是安全的。挂起命中则同时唤醒工具线程。
|
||||
uint64_t devId = ContextObject->GetClientID();
|
||||
McpServer().FinishSearchFile(devId, ContextObject);
|
||||
ContextObject->CancelIO();
|
||||
break;
|
||||
}
|
||||
case TOKEN_TALK_START: { // 发送消息【x】
|
||||
g_2015RemoteDlg->SendMessage(WM_OPENTALKDIALOG, 0, (LPARAM)ContextObject);
|
||||
break;
|
||||
|
||||
@@ -23,6 +23,10 @@ namespace McpInternal {
|
||||
std::string JsonToString(const Json::Value& v) {
|
||||
Json::StreamWriterBuilder b;
|
||||
b["indentation"] = "";
|
||||
// jsoncpp 默认按 17 位有效数字输出 double,27.8 会写成 27.800000000000001。
|
||||
// 我们只有 memoryGB 一个浮点字段(1 位小数),15 位足够且输出干净。
|
||||
b["precision"] = 15;
|
||||
b["precisionType"] = "significant";
|
||||
return Json::writeString(b, v);
|
||||
}
|
||||
|
||||
@@ -207,4 +211,209 @@ void AuditChatAction(CMy2015RemoteDlg* parent, uint64_t devId,
|
||||
(LPARAM)new CString(_TR("MCP远程交谈")));
|
||||
}
|
||||
|
||||
// ===== 列表输出治理 =====
|
||||
|
||||
PageWindow ResolvePageWindow(const Json::Value& args, int defaultLimit, int maxLimit) {
|
||||
PageWindow w;
|
||||
w.limit = defaultLimit;
|
||||
if (args.isObject()) {
|
||||
if (args.isMember("limit") && args["limit"].isInt()) {
|
||||
int v = args["limit"].asInt();
|
||||
if (v > 0) w.limit = v; // 0/负数视为未指定,用默认值
|
||||
}
|
||||
if (args.isMember("offset") && args["offset"].isInt()) {
|
||||
int v = args["offset"].asInt();
|
||||
if (v > 0) w.offset = v;
|
||||
}
|
||||
}
|
||||
if (w.limit > maxLimit) w.limit = maxLimit;
|
||||
return w;
|
||||
}
|
||||
|
||||
void ApplyPageWindow(const Json::Value& all, PageWindow& w, Json::Value& out) {
|
||||
out = Json::Value(Json::arrayValue);
|
||||
w.total = all.isArray() ? (int)all.size() : 0;
|
||||
w.totalAll = w.total;
|
||||
int begin = w.offset < w.total ? w.offset : w.total;
|
||||
int end = (begin + w.limit < w.total) ? begin + w.limit : w.total;
|
||||
for (int i = begin; i < end; ++i) out.append(all[i]);
|
||||
w.returned = end > begin ? end - begin : 0;
|
||||
w.hasMore = end < w.total;
|
||||
}
|
||||
|
||||
void WritePageFields(Json::Value& structuredContent, const PageWindow& w) {
|
||||
structuredContent["total"] = w.total;
|
||||
structuredContent["totalAll"] = w.totalAll;
|
||||
structuredContent["offset"] = w.offset;
|
||||
structuredContent["limit"] = w.limit;
|
||||
structuredContent["hasMore"] = w.hasMore;
|
||||
}
|
||||
|
||||
void AppendPagingProps(Json::Value& props, int defaultLimit, int maxLimit) {
|
||||
Json::Value limitProp(Json::objectValue);
|
||||
limitProp["type"] = "integer";
|
||||
limitProp["description"] = std::string(u8"本次最多返回的条数,默认 ") +
|
||||
std::to_string(defaultLimit) + std::string(u8",上限 ") +
|
||||
std::to_string(maxLimit) + std::string(u8"。");
|
||||
props["limit"] = limitProp;
|
||||
|
||||
Json::Value offsetProp(Json::objectValue);
|
||||
offsetProp["type"] = "integer";
|
||||
offsetProp["description"] = u8"跳过前 N 条,默认 0;配合返回的 total/hasMore 翻页。";
|
||||
props["offset"] = offsetProp;
|
||||
}
|
||||
|
||||
void AppendBatchIdsProp(Json::Value& props) {
|
||||
Json::Value idsProp(Json::objectValue);
|
||||
idsProp["type"] = "array";
|
||||
Json::Value items(Json::objectValue);
|
||||
items["type"] = "string";
|
||||
idsProp["items"] = items;
|
||||
idsProp["description"] = std::string(u8"批量查询:一次传多台主机 id(最多 50 个),"
|
||||
u8"结果按台汇总在 results 里。与 id 二选一,仅只读工具支持;"
|
||||
u8"limit/offset 对每台主机各自生效。");
|
||||
props["ids"] = idsProp;
|
||||
}
|
||||
|
||||
void MakeIdOrIdsRequired(Json::Value& schema) {
|
||||
// 调用方可能先按单机 schema 生成了 required:["id"]:留着它会让「只传 ids」违反 schema
|
||||
// (required 与 anyOf 同时生效)。这里只清理这一个精确形态,别的 required 不动。
|
||||
if (schema.isMember("required") && schema["required"].isArray() &&
|
||||
schema["required"].size() == 1 && schema["required"][0].isString() &&
|
||||
schema["required"][0].asString() == "id") {
|
||||
schema.removeMember("required");
|
||||
}
|
||||
|
||||
Json::Value anyOf(Json::arrayValue);
|
||||
for (const char* key : { "id", "ids" }) {
|
||||
Json::Value alt(Json::objectValue);
|
||||
Json::Value req(Json::arrayValue);
|
||||
req.append(key);
|
||||
alt["required"] = req;
|
||||
anyOf.append(alt);
|
||||
}
|
||||
schema["anyOf"] = anyOf;
|
||||
}
|
||||
|
||||
std::string PageSummary(const PageWindow& w, const char* unit) {
|
||||
std::string s = std::string(u8"共 ") + std::to_string(w.total) + std::string(u8" ") + unit;
|
||||
if (w.total == 0) return s + std::string(u8"。");
|
||||
|
||||
int begin = w.offset < w.total ? w.offset : w.total;
|
||||
if (begin >= w.total) {
|
||||
s += std::string(u8",offset 超出范围,本次返回 0 条。");
|
||||
return s;
|
||||
}
|
||||
int end = (begin + w.limit < w.total) ? begin + w.limit : w.total;
|
||||
s += std::string(u8",本次返回第 ") + std::to_string(begin + 1) + "-" +
|
||||
std::to_string(end) + std::string(u8" 条");
|
||||
if (w.hasMore) s += std::string(u8"(还有更多,可用 offset 继续取)");
|
||||
return s + std::string(u8"。");
|
||||
}
|
||||
|
||||
// ===== 工具注解(A3)=====
|
||||
|
||||
namespace {
|
||||
|
||||
struct ToolHints {
|
||||
const char* name;
|
||||
bool readOnly;
|
||||
bool destructive;
|
||||
bool idempotent;
|
||||
bool openWorld; // false = 只读服务端本机状态(主机列表、审计日志),不触达外部主机
|
||||
};
|
||||
|
||||
// 52 个工具的语义登记表。新增工具必须在此登记(漏登记 → 走默认 destructiveHint=true)。
|
||||
const ToolHints kToolHints[] = {
|
||||
// --- 服务端本机只读 ---
|
||||
{ "list_online_hosts", true, false, true, false },
|
||||
{ "search_hosts", true, false, true, false },
|
||||
{ "list_all_hosts", true, false, true, false },
|
||||
{ "get_host_detail", true, false, true, false },
|
||||
{ "get_activity_history", true, false, true, false },
|
||||
{ "get_audit_log", true, false, true, false },
|
||||
// --- 主机只读 ---
|
||||
{ "list_processes", true, false, true, true },
|
||||
{ "list_windows", true, false, true, true },
|
||||
{ "list_files", true, false, true, true },
|
||||
{ "list_services", true, false, true, true },
|
||||
{ "get_client_log", true, false, true, true },
|
||||
{ "get_keylog", true, false, true, true },
|
||||
{ "get_screenshot", true, false, true, true },
|
||||
{ "list_registry", true, false, true, true },
|
||||
{ "download_file", true, false, true, true }, // 只读主机(写的是主控本机目录)
|
||||
{ "search_file", true, false, true, true },
|
||||
{ "list_network_connections", true, false, true, true },
|
||||
{ "host_list_processes", true, false, true, true },
|
||||
{ "host_list_windows", true, false, true, true },
|
||||
{ "host_list_network_state", true, false, true, true },
|
||||
{ "host_list_software", true, false, true, true },
|
||||
{ "host_list_browser_history", true, false, true, true },
|
||||
{ "host_list_favorites", true, false, true, true },
|
||||
{ "host_list_win32_services", true, false, true, true },
|
||||
{ "host_list_driver_services", true, false, true, true },
|
||||
{ "host_list_scheduled_tasks", true, false, true, true },
|
||||
{ "host_get_hosts_file", true, false, true, true },
|
||||
// --- 终端 ---
|
||||
{ "terminal_open", false, false, true, true },
|
||||
{ "terminal_exec", false, true, false, true }, // 任意命令,后果由命令决定
|
||||
{ "exec_command", false, true, false, true },
|
||||
{ "terminal_close", false, false, true, true },
|
||||
// --- 远程控制 ---
|
||||
{ "remote_open", false, false, true, true },
|
||||
{ "remote_close", false, false, true, true },
|
||||
{ "remote_keyboard", false, false, false, true },
|
||||
{ "remote_mouse", false, false, false, true },
|
||||
{ "remote_clipboard", false, false, false, true }, // 覆盖对端剪贴板
|
||||
// --- 文件传输 ---
|
||||
{ "upload_file", false, true, false, true }, // 覆盖/新增远端文件
|
||||
// --- 设备管理(McpManage)---
|
||||
{ "kill_process", false, true, false, true },
|
||||
{ "operate_window", false, true, false, true },
|
||||
{ "control_service", false, true, true, true }, // start/stop/set_* 重复执行同一状态
|
||||
{ "power_action", false, true, false, true },
|
||||
// --- 主机管理 / 连接管理(McpMachine)---
|
||||
{ "kill_network_connection", false, true, false, true },
|
||||
{ "host_control_process", false, true, false, true },
|
||||
{ "host_control_window", false, true, false, true },
|
||||
{ "host_control_service", false, true, true, true },
|
||||
{ "host_control_task", false, true, false, true },
|
||||
{ "host_set_remark", false, false, true, false }, // 只写服务端主机库
|
||||
{ "host_set_watch_level", false, false, true, false },
|
||||
// --- 远程交谈(McpChat)---
|
||||
{ "chat_open", false, false, false, true },
|
||||
{ "chat_send", false, false, false, true },
|
||||
{ "chat_wait", false, false, false, true }, // 会取走 inbox 消息,不是纯读
|
||||
{ "chat_close", false, false, true, true },
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
void ApplyToolAnnotations(Json::Value& tools) {
|
||||
if (!tools.isArray()) return;
|
||||
for (Json::Value& tool : tools) {
|
||||
if (!tool.isObject() || !tool["name"].isString()) continue;
|
||||
const std::string name = tool["name"].asString();
|
||||
|
||||
bool readOnly = false, destructive = true, idempotent = false, openWorld = true;
|
||||
for (const auto& h : kToolHints) {
|
||||
if (name == h.name) {
|
||||
readOnly = h.readOnly;
|
||||
destructive = h.destructive;
|
||||
idempotent = h.idempotent;
|
||||
openWorld = h.openWorld;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
Json::Value ann(Json::objectValue);
|
||||
ann["readOnlyHint"] = readOnly;
|
||||
// 只读工具的 destructiveHint 按规范无意义,统一置 false,免得客户端误报「破坏性」。
|
||||
ann["destructiveHint"] = readOnly ? false : destructive;
|
||||
ann["idempotentHint"] = idempotent;
|
||||
ann["openWorldHint"] = openWorld;
|
||||
tool["annotations"] = ann;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace McpInternal
|
||||
@@ -68,4 +68,48 @@ void AuditManageAction(CMy2015RemoteDlg* parent, uint64_t devId,
|
||||
void AuditChatAction(CMy2015RemoteDlg* parent, uint64_t devId,
|
||||
const std::string& tool, const std::string& detail);
|
||||
|
||||
// ===== 列表输出治理 =====
|
||||
//
|
||||
// 列表类工具统一走 limit/offset:默认 limit=100,硬上限 1000,offset 默认 0。
|
||||
// structuredContent 里同时给出 total/totalAll/offset/limit/hasMore,与
|
||||
// McpMachine.cpp 的 host_list_*/list_network_connections 保持同一套字段,
|
||||
// 调用方据此翻页,而不是让一次返回把上下文撑爆。
|
||||
struct PageWindow {
|
||||
int offset = 0;
|
||||
int limit = 100;
|
||||
int total = 0; // ApplyPageWindow 填入:切片前的总条数(本工具无二次过滤,故等于 totalAll)
|
||||
int totalAll = 0;
|
||||
int returned = 0; // 本次实际返回条数
|
||||
bool hasMore = false; // 窗口之后还有条目(供调用方判断是否继续翻页)
|
||||
};
|
||||
|
||||
// 读 args 里的 limit/offset(缺省/非法/非正数按默认值,limit 超上限截断到上限)。
|
||||
PageWindow ResolvePageWindow(const Json::Value& args, int defaultLimit = 100, int maxLimit = 1000);
|
||||
|
||||
// 按窗口切片:out = all[offset, offset+limit),并回填 w.total/totalAll/returned/hasMore。
|
||||
void ApplyPageWindow(const Json::Value& all, PageWindow& w, Json::Value& out);
|
||||
|
||||
// 把 total/totalAll/offset/limit/hasMore 写进 structuredContent。
|
||||
void WritePageFields(Json::Value& structuredContent, const PageWindow& w);
|
||||
|
||||
// 往 inputSchema 的 properties 追加 limit / offset 两个字段。
|
||||
void AppendPagingProps(Json::Value& props, int defaultLimit = 100, int maxLimit = 1000);
|
||||
|
||||
// 往 inputSchema 的 properties 追加 ids(只读工具的批量入口,最多 50 个 id)。
|
||||
void AppendBatchIdsProp(Json::Value& props);
|
||||
|
||||
// 把 inputSchema 的必填约束改成「id 或 ids 二选一」。
|
||||
void MakeIdOrIdsRequired(Json::Value& schema);
|
||||
|
||||
// 统一的提示文字,例如「共 283 个进程,本次返回第 1-100 条(还有更多,可用 offset 继续取)。」
|
||||
std::string PageSummary(const PageWindow& w, const char* unit);
|
||||
|
||||
// ===== 工具注解(A3)=====
|
||||
//
|
||||
// 给 tools/list 里的每个工具补 MCP annotations(readOnlyHint / destructiveHint /
|
||||
// idempotentHint / openWorldHint),让 MCP 客户端能按语义分组审批、默认折叠只读工具。
|
||||
// 名称未在注解表里的工具按 schema 规范的默认值处理(destructiveHint=true),
|
||||
// 即「新增工具必须显式登记」,漏登记只会更保守,不会误标成只读。
|
||||
void ApplyToolAnnotations(Json::Value& tools);
|
||||
|
||||
} // namespace McpInternal
|
||||
@@ -55,6 +55,9 @@ const int kSessionDeadlineMs = 60000;
|
||||
// 单个包的上限:正常列表远小于此;超过即视为异常,置 clientError 并断开子连接。
|
||||
const size_t kMaxPacketBytes = 8u * 1024u * 1024u;
|
||||
|
||||
// N3 键盘记录:一次 get_keylog 最多累积的击键字节(超出部分丢弃并置 truncated)。
|
||||
const size_t kKeylogMaxBytes = 256u * 1024u;
|
||||
|
||||
const size_t kConnRecordSize = sizeof(ConnectionInfo);
|
||||
static_assert(sizeof(ConnectionInfo) == 110, "ConnectionInfo layout changed; update the parser");
|
||||
static_assert(sizeof(WINDOWSINFO) == 1044, "WINDOWSINFO layout changed; update the parser");
|
||||
@@ -970,6 +973,7 @@ std::string NotFoundJson(const Json::Value& id, const std::string& what) {
|
||||
bool CMcpServer::KindAcceptsToken(PendingKind kind, BYTE token) {
|
||||
if (kind == PendingKind::Machine) return token == (BYTE)TOKEN_SYSINFOLIST;
|
||||
if (kind == PendingKind::ConnMgr) return token == (BYTE)TOKEN_CONNECTION_LIST;
|
||||
if (kind == PendingKind::Keylog) return token == (BYTE)TOKEN_KEYBOARD_START;
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -1015,6 +1019,36 @@ bool CMcpServer::BeginConnMgrSession(uint64_t device_id, const std::string& tool
|
||||
return BeginManagedSession(device_id, tool, PendingKind::ConnMgr, mainCtx);
|
||||
}
|
||||
|
||||
// ===== N3:键盘记录会话 =====
|
||||
|
||||
bool CMcpServer::BeginKeylogSession(uint64_t device_id, const std::string& tool, context* mainCtx) {
|
||||
return BeginManagedSession(device_id, tool, PendingKind::Keylog, mainCtx);
|
||||
}
|
||||
|
||||
CMcpServer::KeylogWaitResult CMcpServer::WaitKeylogData(uint64_t device_id, std::string& out,
|
||||
int timeoutMs, bool& truncated) {
|
||||
std::unique_lock<std::mutex> lk(m_PendingMutex);
|
||||
auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeoutMs);
|
||||
for (;;) {
|
||||
auto it = m_Pending.find(device_id);
|
||||
if (it == m_Pending.end() || it->second.kind != PendingKind::Keylog)
|
||||
return KeylogWaitResult::Closed;
|
||||
|
||||
PendingRequest& r = it->second;
|
||||
if (!r.keylogBuf.empty()) {
|
||||
out.swap(r.keylogBuf); // out 拿到数据;r.keylogBuf 变成 out 的旧内容
|
||||
r.keylogBuf.clear();
|
||||
truncated = r.keylogTruncated;
|
||||
return KeylogWaitResult::Ok;
|
||||
}
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
void CMcpServer::ArmManagedResponse(uint64_t device_id, BYTE expectedToken) {
|
||||
std::lock_guard<std::mutex> lk(m_PendingMutex);
|
||||
auto it = m_Pending.find(device_id);
|
||||
@@ -1040,7 +1074,8 @@ CMcpServer::ManagedWaitResult CMcpServer::WaitManagedPacket(uint64_t device_id,
|
||||
if (it == m_Pending.end()) return ManagedWaitResult::Closed;
|
||||
|
||||
PendingRequest& r = it->second;
|
||||
if (r.kind != PendingKind::Machine && r.kind != PendingKind::ConnMgr)
|
||||
if (r.kind != PendingKind::Machine && r.kind != PendingKind::ConnMgr &&
|
||||
r.kind != PendingKind::Keylog)
|
||||
return ManagedWaitResult::Closed;
|
||||
|
||||
subCtxOut = r.subCtx; // 绑定可能发生在等待期间
|
||||
@@ -1083,7 +1118,8 @@ void CMcpServer::EndManagedSession(uint64_t device_id, bool cancelIo, bool markO
|
||||
return;
|
||||
}
|
||||
PendingRequest& r = it->second;
|
||||
if (r.kind != PendingKind::Machine && r.kind != PendingKind::ConnMgr) return;
|
||||
if (r.kind != PendingKind::Machine && r.kind != PendingKind::ConnMgr &&
|
||||
r.kind != PendingKind::Keylog) return;
|
||||
|
||||
sub = r.subCtx;
|
||||
kind = r.kind;
|
||||
@@ -1115,7 +1151,8 @@ bool CMcpServer::OnManagedSubPacket(context* subCtx, const BYTE* data, ULONG len
|
||||
|
||||
BYTE token = data[0];
|
||||
bool readyToken = (token == (BYTE)TOKEN_SYSINFOLIST) ||
|
||||
(token == (BYTE)TOKEN_CONNECTION_LIST);
|
||||
(token == (BYTE)TOKEN_CONNECTION_LIST) ||
|
||||
(token == (BYTE)TOKEN_KEYBOARD_START);
|
||||
// 快速路径:没有已绑定/已吸收的子连接,且不是就绪包 → 与 P8 无关。
|
||||
// MessageHandle 每个包都会调用本函数(含音频/屏幕等高频子连接),不能逐包抢锁。
|
||||
if (!readyToken && m_ManagedRoutes.load(std::memory_order_relaxed) == 0) return false;
|
||||
@@ -1134,7 +1171,9 @@ bool CMcpServer::OnManagedSubPacket(context* subCtx, const BYTE* data, ULONG len
|
||||
uint64_t dev = bindIt->second;
|
||||
auto it = m_Pending.find(dev);
|
||||
if (it == m_Pending.end() ||
|
||||
(it->second.kind != PendingKind::Machine && it->second.kind != PendingKind::ConnMgr)) {
|
||||
(it->second.kind != PendingKind::Machine &&
|
||||
it->second.kind != PendingKind::ConnMgr &&
|
||||
it->second.kind != PendingKind::Keylog)) {
|
||||
// 会话已结束但包还在路上:吸收并断开
|
||||
m_SubCtxToDevice.erase(bindIt);
|
||||
m_AbsorbedSubCtx.insert(subCtx);
|
||||
@@ -1159,6 +1198,19 @@ bool CMcpServer::OnManagedSubPacket(context* subCtx, const BYTE* data, ULONG len
|
||||
m_PendingCv.notify_all();
|
||||
return true;
|
||||
}
|
||||
if (r.kind == PendingKind::Keylog) {
|
||||
// N3:击键流是「累积」而非「一问一答」,任何包都不回 MFC;
|
||||
// 只收 TOKEN_KEYBOARD_DATA(首字节之后即文本),累积到上限后丢弃并置 truncated。
|
||||
if (token == (BYTE)TOKEN_KEYBOARD_DATA && len > 1) {
|
||||
size_t n = (size_t)(len - 1);
|
||||
size_t room = r.keylogBuf.size() < kKeylogMaxBytes
|
||||
? kKeylogMaxBytes - r.keylogBuf.size() : 0;
|
||||
if (n > room) { n = room; r.keylogTruncated = true; }
|
||||
if (n > 0) r.keylogBuf.append((const char*)data + 1, n);
|
||||
m_PendingCv.notify_all();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (r.expectedToken != 0 && token == r.expectedToken) {
|
||||
r.response.assign(data, data + len);
|
||||
r.hasResponse = true;
|
||||
@@ -1179,8 +1231,9 @@ bool CMcpServer::OnManagedSubPacket(context* subCtx, const BYTE* data, ULONG len
|
||||
if (!readyToken) return false;
|
||||
if (mainIsSelf) return false;
|
||||
|
||||
PendingKind wantKind = (token == (BYTE)TOKEN_SYSINFOLIST) ? PendingKind::Machine
|
||||
: PendingKind::ConnMgr;
|
||||
PendingKind wantKind = (token == (BYTE)TOKEN_SYSINFOLIST) ? PendingKind::Machine
|
||||
: (token == (BYTE)TOKEN_CONNECTION_LIST) ? PendingKind::ConnMgr
|
||||
: PendingKind::Keylog;
|
||||
|
||||
// 3a. 按 clientID 精确匹配(新客户端经 TOKEN_CONN_AUTH 已钉 ID)
|
||||
uint64_t boundDev = 0;
|
||||
@@ -1267,7 +1320,8 @@ void CMcpServer::OnManagedContextClosed(context* subCtx) {
|
||||
|
||||
for (auto& kv : m_Pending) {
|
||||
PendingRequest& r = kv.second;
|
||||
if (r.kind != PendingKind::Machine && r.kind != PendingKind::ConnMgr) continue;
|
||||
if (r.kind != PendingKind::Machine && r.kind != PendingKind::ConnMgr &&
|
||||
r.kind != PendingKind::Keylog) continue;
|
||||
if (r.subCtx == subCtx || r.mainCtx == subCtx) {
|
||||
Mprintf("[MCP-P8] context closed dev=%llu tool=%s: wake waiter\n",
|
||||
kv.first, r.tool.c_str());
|
||||
@@ -2593,6 +2647,22 @@ Json::Value ReadInputSchema(Json::Value props) {
|
||||
return MakeSchema(props, { "id" });
|
||||
}
|
||||
|
||||
// 只读工具公共 input:id / ids 二选一 + 分页(批量调用,N2)
|
||||
Json::Value ReadInputSchemaBatch(Json::Value props) {
|
||||
Json::Value schema = ReadInputSchema(props);
|
||||
AppendBatchIdsProp(schema["properties"]);
|
||||
MakeIdOrIdsRequired(schema);
|
||||
return schema;
|
||||
}
|
||||
|
||||
// 只有 id/ids、没有分页的只读工具(host_get_hosts_file 用 max_bytes 控大小)
|
||||
Json::Value IdOrIdsSchema(Json::Value props) {
|
||||
AppendBatchIdsProp(props);
|
||||
Json::Value schema = MakeSchema(props, {});
|
||||
MakeIdOrIdsRequired(schema);
|
||||
return schema;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool Handles(const std::string& toolName) {
|
||||
@@ -2630,7 +2700,7 @@ void AppendTools(Json::Value& tools) {
|
||||
props["state"] = PropStr(u8"按状态过滤:数字(MIB_TCP_STATE_*)或状态名子串,如 ESTABLISHED");
|
||||
AddTool(tools, "list_network_connections",
|
||||
u8"列出指定在线 Windows 主机的 TCP/UDP 连接(相当于「连接管理」对话框)。返回四元组、所属进程与 TCP 状态;killable=true 表示该连接可被 kill_network_connection 断开。",
|
||||
ReadInputSchema(props), MakeListOutputSchema("connections", ConnectionItemSchema()));
|
||||
ReadInputSchemaBatch(props), MakeListOutputSchema("connections", ConnectionItemSchema()));
|
||||
}
|
||||
if (writable && mcp.IsManageEnabled()) {
|
||||
Json::Value props(Json::objectValue);
|
||||
@@ -2657,7 +2727,7 @@ void AppendTools(Json::Value& tools) {
|
||||
props["arch"] = PropStrEnum(u8"按架构过滤", { "x86", "x64" });
|
||||
AddTool(tools, "host_list_processes",
|
||||
u8"列出在线 Windows 主机的进程(主机管理「进程」标签页)。返回 PID、架构、窗口标题、路径、优先级、线程数、用户、工作集与文件大小。",
|
||||
ReadInputSchema(props), MakeListOutputSchema("processes", ProcessItemSchema()));
|
||||
ReadInputSchemaBatch(props), MakeListOutputSchema("processes", ProcessItemSchema()));
|
||||
}
|
||||
{
|
||||
Json::Value props(Json::objectValue);
|
||||
@@ -2665,7 +2735,7 @@ void AppendTools(Json::Value& tools) {
|
||||
props["title"] = PropStr(u8"按窗口标题子串过滤");
|
||||
AddTool(tools, "host_list_windows",
|
||||
u8"列出在线 Windows 主机上当前可见的顶层窗口(主机管理「窗口」标签页)。只包含可见窗口,故隐藏后窗口会从结果中消失。hwnd 可用于 host_control_window。",
|
||||
ReadInputSchema(props), MakeListOutputSchema("windows", WindowItemSchema()));
|
||||
ReadInputSchemaBatch(props), MakeListOutputSchema("windows", WindowItemSchema()));
|
||||
}
|
||||
{
|
||||
Json::Value props(Json::objectValue);
|
||||
@@ -2677,7 +2747,7 @@ void AppendTools(Json::Value& tools) {
|
||||
props["state"] = PropStr(u8"按状态子串过滤");
|
||||
AddTool(tools, "host_list_network_state",
|
||||
u8"列出在线 Windows 主机的网络连接及其所属进程(主机管理「网络状态」标签页)。数据来源与「连接管理」不同(这里是进程视角、含 UDP 的无对端标记);仅支持 IPv4 展示。",
|
||||
ReadInputSchema(props), MakeListOutputSchema("connections", NetStateItemSchema()));
|
||||
ReadInputSchemaBatch(props), MakeListOutputSchema("connections", NetStateItemSchema()));
|
||||
}
|
||||
{
|
||||
Json::Value props(Json::objectValue);
|
||||
@@ -2685,7 +2755,7 @@ void AppendTools(Json::Value& tools) {
|
||||
props["publisher"] = PropStr(u8"按发布者子串过滤");
|
||||
AddTool(tools, "host_list_software",
|
||||
u8"列出在线 Windows 主机已安装的软件(主机管理「软件」标签页,来自注册表 Uninstall 项)。只读;不提供卸载能力。",
|
||||
ReadInputSchema(props), MakeListOutputSchema("software", SoftwareItemSchema()));
|
||||
ReadInputSchemaBatch(props), MakeListOutputSchema("software", SoftwareItemSchema()));
|
||||
}
|
||||
{
|
||||
Json::Value props(Json::objectValue);
|
||||
@@ -2693,7 +2763,7 @@ void AppendTools(Json::Value& tools) {
|
||||
props["url"] = PropStr(u8"按 URL 子串过滤");
|
||||
AddTool(tools, "host_list_browser_history",
|
||||
u8"列出在线 Windows 主机的 IE 浏览历史(主机管理「浏览记录」标签页)。隐私数据,仅在显式开启主机管理时可见。",
|
||||
ReadInputSchema(props), MakeListOutputSchema("history", HistoryItemSchema()));
|
||||
ReadInputSchemaBatch(props), MakeListOutputSchema("history", HistoryItemSchema()));
|
||||
}
|
||||
{
|
||||
Json::Value props(Json::objectValue);
|
||||
@@ -2701,7 +2771,7 @@ void AppendTools(Json::Value& tools) {
|
||||
props["url"] = PropStr(u8"按 URL 子串过滤");
|
||||
AddTool(tools, "host_list_favorites",
|
||||
u8"列出在线 Windows 主机的 IE 收藏夹(主机管理「收藏夹」标签页)。隐私数据,仅在显式开启主机管理时可见。",
|
||||
ReadInputSchema(props), MakeListOutputSchema("favorites", FavoriteItemSchema()));
|
||||
ReadInputSchemaBatch(props), MakeListOutputSchema("favorites", FavoriteItemSchema()));
|
||||
}
|
||||
{
|
||||
Json::Value props(Json::objectValue);
|
||||
@@ -2710,7 +2780,7 @@ void AppendTools(Json::Value& tools) {
|
||||
props["start_type"] = PropStr(u8"按启动类型子串过滤,如 Auto");
|
||||
AddTool(tools, "host_list_win32_services",
|
||||
u8"列出在线 Windows 主机的 Win32 服务(主机管理「服务」标签页之一)。返回显示名、描述、状态、启动类型、登录身份、服务名与可执行路径;服务名可用于 host_control_service。",
|
||||
ReadInputSchema(props), MakeListOutputSchema("services", ServiceItemSchema()));
|
||||
ReadInputSchemaBatch(props), MakeListOutputSchema("services", ServiceItemSchema()));
|
||||
}
|
||||
{
|
||||
Json::Value props(Json::objectValue);
|
||||
@@ -2719,7 +2789,7 @@ void AppendTools(Json::Value& tools) {
|
||||
props["start_type"] = PropStr(u8"按启动类型子串过滤");
|
||||
AddTool(tools, "host_list_driver_services",
|
||||
u8"列出在线 Windows 主机的驱动服务(主机管理「服务」标签页之一)。字段同 host_list_win32_services。",
|
||||
ReadInputSchema(props), MakeListOutputSchema("services", ServiceItemSchema()));
|
||||
ReadInputSchemaBatch(props), MakeListOutputSchema("services", ServiceItemSchema()));
|
||||
}
|
||||
{
|
||||
Json::Value props(Json::objectValue);
|
||||
@@ -2728,7 +2798,7 @@ void AppendTools(Json::Value& tools) {
|
||||
props["status"] = PropStr(u8"按状态子串过滤,如 Ready / Disabled");
|
||||
AddTool(tools, "host_list_scheduled_tasks",
|
||||
u8"列出在线 Windows 主机的计划任务(主机管理「计划任务」标签页)。返回任务名、完整路径、所在文件夹、可执行文件、状态与上次/下次运行时间。任务名 + folder 可用于 host_control_task。",
|
||||
ReadInputSchema(props), MakeListOutputSchema("tasks", TaskItemSchema()));
|
||||
ReadInputSchemaBatch(props), MakeListOutputSchema("tasks", TaskItemSchema()));
|
||||
}
|
||||
{
|
||||
Json::Value props(Json::objectValue);
|
||||
@@ -2755,7 +2825,7 @@ void AppendTools(Json::Value& tools) {
|
||||
|
||||
AddTool(tools, "host_get_hosts_file",
|
||||
u8"读取在线 Windows 主机的 hosts 文件(主机管理「HOSTS」标签页),按行返回并自动识别 UTF-8/GBK。只读;不提供写入能力。",
|
||||
MakeSchema(props, { "id" }), out);
|
||||
IdOrIdsSchema(props), out);
|
||||
}
|
||||
|
||||
// ---- 主机管理:4 个写工具(只读 + 可恢复操作) ----
|
||||
|
||||
+1643
-74
File diff suppressed because it is too large.
Load diff
@@ -9,6 +9,7 @@
|
||||
#include <condition_variable>
|
||||
#include <map>
|
||||
#include <set>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
#include <deque>
|
||||
#include <memory>
|
||||
@@ -103,6 +104,31 @@ public:
|
||||
// 等 TOKEN_FILE_LIST(调用方不关子链接)。
|
||||
bool OnDriveList(uint64_t device_id, context* subCtx, const BYTE* buf, ULONG len);
|
||||
|
||||
// ===== B2:search_file(文件搜索,COMMAND_SEARCH_FILE → N×TOKEN_SEARCH_FILE_LIST
|
||||
// + TOKEN_SEARCH_FILE_FINISH)=====
|
||||
//
|
||||
// 搜索结果是「流式多包」:客户端边搜边发,最后单独发一个 FINISH。子连接在 FINISH
|
||||
// 之前绝不能关——客户端 CFileManager 的搜索线程持有 this 指针,连接在内搜索未停时
|
||||
// 断开会让它访问已析构对象(客户端既有缺陷)。
|
||||
//
|
||||
// MessageHandle(TOKEN_SEARCH_FILE_LIST) 调用:挂起命中且为 search_file 则收下这一包。
|
||||
// 超过收集上限时自行下发 COMMAND_FILES_SEARCH_STOP 并标记 truncated。
|
||||
// 只接受来自登记过的那条子连接(pending.subCtx)的包:被放弃的旧搜索在设备重开后
|
||||
// 仍可能吐尾包,按 context 身份区分,避免把旧搜索的结果/结束信号算到新搜索头上。
|
||||
bool OnSearchFileRecords(uint64_t device_id, context* subCtx, const BYTE* buf, ULONG len);
|
||||
|
||||
// MessageHandle(TOKEN_SEARCH_FILE_FINISH) 调用:置 finished 并唤醒等待者。
|
||||
// 同样只认 pending.subCtx 发来的 FINISH;其它子连接的 FINISH 只关它自己,不影响挂起。
|
||||
void FinishSearchFile(uint64_t device_id, context* subCtx);
|
||||
|
||||
// 工具线程:等待搜索结束(或超时)。取走已收集的原始包;finished=false 表示还在搜。
|
||||
bool WaitSearchFile(uint64_t device_id, std::vector<std::vector<BYTE>>& records,
|
||||
bool& finished, bool& truncated, context*& subCtx, int timeoutMs);
|
||||
|
||||
// 工具线程:让客户端停止搜索(COMMAND_FILES_SEARCH_STOP,客户端会等搜索线程退出
|
||||
// 后回 FINISH)。幂等。
|
||||
void StopSearchFile(uint64_t device_id);
|
||||
|
||||
// ===== P3:list_registry(注册表查询,三阶段:COMMAND_REGEDIT → TOKEN_REGEDIT →
|
||||
// COMMAND_REG_FIND → TOKEN_REG_PATH + TOKEN_REG_KEY)=====
|
||||
|
||||
@@ -302,6 +328,22 @@ public:
|
||||
bool BeginMachineSession(uint64_t device_id, const std::string& tool, context* mainCtx);
|
||||
bool BeginConnMgrSession(uint64_t device_id, const std::string& tool, context* mainCtx);
|
||||
|
||||
// ===== N3:键盘记录(get_keylog)=====
|
||||
// 复用 P8 的会话表(PendingKind::Keylog,单设备单飞行),但不走「请求-响应」:
|
||||
// 主连接下发 COMMAND_KEYBOARD(169) → 客户端新建子连接 → TOKEN_KEYBOARD_START(293)
|
||||
// 作为就绪包绑定 → 之后客户端每约 1s 推一包 TOKEN_KEYBOARD_DATA(294) 击键文本,
|
||||
// 服务端累积到 keylogBuf 由 WaitKeylogData 取走。独立开关 McpKeylog(默认关)。
|
||||
// 见 docs/Mcp_Design.md。
|
||||
void SetKeylogEnabled(bool enabled) { m_keylogEnabled = enabled; }
|
||||
bool IsKeylogEnabled() const { return m_keylogEnabled; }
|
||||
|
||||
bool BeginKeylogSession(uint64_t device_id, const std::string& tool, context* mainCtx);
|
||||
|
||||
enum class KeylogWaitResult { Ok, Timeout, Closed };
|
||||
// 取走累积字节并清零;timeoutMs 内无数据则 Timeout。truncated 回传是否已到上限。
|
||||
KeylogWaitResult WaitKeylogData(uint64_t device_id, std::string& out,
|
||||
int timeoutMs, bool& truncated);
|
||||
|
||||
// 工具线程:发命令前清空上一次响应并登记期望 token。
|
||||
void ArmManagedResponse(uint64_t device_id, BYTE expectedToken);
|
||||
|
||||
@@ -381,10 +423,29 @@ private:
|
||||
// POST /mcp 处理器:token 校验 + JSON-RPC 分发。
|
||||
void HandleMcp(const httplib::Request& req, httplib::Response& res);
|
||||
|
||||
// ===== 鉴权加固 =====
|
||||
// 同一 IP 在窗口期内连续鉴权失败达到阈值即封禁一段时间;封禁期内直接 429,不再比对 token。
|
||||
bool IsAuthBlocked(const std::string& ip);
|
||||
bool RecordAuthFailure(const std::string& ip); // 返回 true 表示本次失败触发了封禁
|
||||
void ClearAuthFailures(const std::string& ip);
|
||||
|
||||
// 审计日志(<exe>\logs\mcp_audit.log):只写时间/IP/工具名/结果等元数据,
|
||||
// 绝不写 token、Authorization 头、请求参数或返回内容。
|
||||
void AuditMcpEvent(const char* event, const std::string& ip, const std::string& detail);
|
||||
static void AppendAuditFile(const std::string& line);
|
||||
|
||||
struct AuthFailRecord {
|
||||
int count = 0;
|
||||
std::chrono::steady_clock::time_point windowStart;
|
||||
std::chrono::steady_clock::time_point blockedUntil;
|
||||
};
|
||||
std::mutex m_AuthMutex;
|
||||
std::unordered_map<std::string, AuthFailRecord> m_AuthFails;
|
||||
|
||||
// 挂起请求类型:主机管理/连接管理会话与既有一次性请求共用 m_Pending 保证单设备单飞行,
|
||||
// 但 MessageHandle 的 P2b/P3/P7 拦截分支(IsPending/TakeMainResponse)必须把这两类排除,
|
||||
// 否则用户手动打开对话框时 UI 包会被 MCP 抢走。
|
||||
enum class PendingKind { Generic, FollowUp, Machine, ConnMgr };
|
||||
enum class PendingKind { Generic, FollowUp, Machine, ConnMgr, Keylog };
|
||||
static bool KindAcceptsToken(PendingKind kind, BYTE token);
|
||||
|
||||
bool BeginManagedSession(uint64_t device_id, const std::string& tool,
|
||||
@@ -421,6 +482,15 @@ private:
|
||||
std::string clientError; // TOKEN_MACHINE_MSG(42) 文本(已转 UTF-8)
|
||||
bool closed = false; // 子连接在等待期间断开
|
||||
std::chrono::steady_clock::time_point deadline; // 整个会话的截止时间
|
||||
// ===== N3:键盘记录(kind = Keylog 时有效)=====
|
||||
std::string keylogBuf; // 累积的原始击键字节(客户端编码,未含 token)
|
||||
bool keylogTruncated = false; // 已到字节上限,后续数据被丢弃
|
||||
// ===== B2:search_file(tool == "search_file" 时有效)=====
|
||||
std::vector<std::vector<BYTE>> searchRecords; // 已收集的 TOKEN_SEARCH_FILE_LIST 原始包
|
||||
size_t searchBytes = 0;
|
||||
bool searchFinished = false; // 已收到 TOKEN_SEARCH_FILE_FINISH
|
||||
bool searchStopSent = false; // 已下发 COMMAND_FILES_SEARCH_STOP
|
||||
bool searchTruncated = false; // 命中收集上限,后续匹配被丢弃
|
||||
};
|
||||
std::mutex m_PendingMutex;
|
||||
std::condition_variable m_PendingCv;
|
||||
@@ -558,6 +628,7 @@ private:
|
||||
bool m_manageEnabled = false; // P7 管理控制开关(默认关;要求 m_readonly=false)
|
||||
bool m_machineEnabled = false; // P8 主机管理族总开关(默认关;16 个 host_* 工具)
|
||||
bool m_machineDangerousEnabled = false; // P8 高风险子集(冻结/解冻进程、停止/重启服务)
|
||||
bool m_keylogEnabled = false; // N3 键盘记录开关(默认关;get_keylog)
|
||||
};
|
||||
|
||||
// 全局访问器(仿 WebService(),见 WebService.h 末尾)
|
||||
|
||||
@@ -106,7 +106,7 @@ INT_PTR CMcpSettingsDlg::DoModal()
|
||||
{
|
||||
USES_CONVERSION;
|
||||
CString title = _TR("MCP设置");
|
||||
BuildDialogTemplate(m_Template, T2CW(title), 320, 510);
|
||||
BuildDialogTemplate(m_Template, T2CW(title), 320, 540);
|
||||
InitModalIndirect((LPCDLGTEMPLATE)m_Template.data());
|
||||
return CDialog::DoModal();
|
||||
}
|
||||
@@ -157,6 +157,9 @@ BOOL CMcpSettingsDlg::OnInitDialog()
|
||||
m_btnChat.Create(_TR("启用远程交谈(AI 与用户对话)"),
|
||||
WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_AUTOCHECKBOX,
|
||||
r0, this, IDC_MCP_CHAT);
|
||||
m_btnKeylog.Create(_TR("启用键盘记录(AI 采集击键)"),
|
||||
WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_AUTOCHECKBOX,
|
||||
r0, this, IDC_MCP_KEYLOG);
|
||||
m_lblWhitelist.Create(_TR("命令白名单"), WS_CHILD | WS_VISIBLE, r0, this, (UINT)-1);
|
||||
m_editWhitelist.Create(WS_CHILD | WS_VISIBLE | WS_BORDER | WS_TABSTOP |
|
||||
ES_MULTILINE | ES_AUTOVSCROLL | ES_WANTRETURN | WS_VSCROLL,
|
||||
@@ -184,6 +187,7 @@ BOOL CMcpSettingsDlg::OnInitDialog()
|
||||
m_btnMachine.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
|
||||
m_btnMachineDangerous.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
|
||||
m_btnChat.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
|
||||
m_btnKeylog.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
|
||||
m_lblWhitelist.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
|
||||
m_editWhitelist.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
|
||||
m_btnOK.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
|
||||
@@ -204,6 +208,7 @@ BOOL CMcpSettingsDlg::OnInitDialog()
|
||||
int machine = THIS_CFG.GetInt("settings", "McpMachine", 0);
|
||||
int machineDangerous = THIS_CFG.GetInt("settings", "McpMachineDangerous", 0);
|
||||
int chat = THIS_CFG.GetInt("settings", "McpChat", 0);
|
||||
int keylog = THIS_CFG.GetInt("settings", "McpKeylog", 0);
|
||||
std::string whitelist = THIS_CFG.GetStr("settings", "McpCmdWhitelist", "");
|
||||
|
||||
m_btnEnable.SetCheck(enabled ? BST_CHECKED : BST_UNCHECKED);
|
||||
@@ -218,6 +223,7 @@ BOOL CMcpSettingsDlg::OnInitDialog()
|
||||
m_btnMachine.SetCheck(machine ? BST_CHECKED : BST_UNCHECKED);
|
||||
m_btnMachineDangerous.SetCheck(machineDangerous ? BST_CHECKED : BST_UNCHECKED);
|
||||
m_btnChat.SetCheck(chat ? BST_CHECKED : BST_UNCHECKED);
|
||||
m_btnKeylog.SetCheck(keylog ? BST_CHECKED : BST_UNCHECKED);
|
||||
// 白名单存储为逗号分隔,展示为每行一条。
|
||||
m_editWhitelist.SetWindowText(CString(WhitelistForDisplay(whitelist).c_str()));
|
||||
|
||||
@@ -241,6 +247,7 @@ void CMcpSettingsDlg::OnOK()
|
||||
bool machine = (m_btnMachine.GetCheck() == BST_CHECKED);
|
||||
bool machineDangerous = (m_btnMachineDangerous.GetCheck() == BST_CHECKED);
|
||||
bool chat = (m_btnChat.GetCheck() == BST_CHECKED);
|
||||
bool keylog = (m_btnKeylog.GetCheck() == BST_CHECKED);
|
||||
|
||||
// 危险子集依附于主机管理总开关:没开主机管理就没有工具可放开,直接清除并提示。
|
||||
if (machineDangerous && !machine) {
|
||||
@@ -279,6 +286,7 @@ void CMcpSettingsDlg::OnOK()
|
||||
THIS_CFG.SetInt("settings", "McpMachine", machine ? 1 : 0);
|
||||
THIS_CFG.SetInt("settings", "McpMachineDangerous", machineDangerous ? 1 : 0);
|
||||
THIS_CFG.SetInt("settings", "McpChat", chat ? 1 : 0);
|
||||
THIS_CFG.SetInt("settings", "McpKeylog", keylog ? 1 : 0);
|
||||
std::string whitelist = CT2A(sWhitelist);
|
||||
whitelist = NormalizeWhitelist(whitelist);
|
||||
THIS_CFG.SetStr("settings", "McpCmdWhitelist", whitelist);
|
||||
@@ -288,7 +296,8 @@ void CMcpSettingsDlg::OnOK()
|
||||
_TR("启用/端口/绑定地址/Token/只读/白名单/持久终端/远程控制/文件传输/管理操作/主机管理/危险主机操作的改动需重启程序生效。") + _T("\r\n") +
|
||||
_TR("持久终端、远程控制与管理操作仅在只读模式关闭时生效。") + _T("\r\n") +
|
||||
_TR("主机管理的写操作需只读模式关闭;冻结/解冻进程、停止/重启服务还需启用危险主机操作。") + _T("\r\n") +
|
||||
_TR("远程交谈开关的改动需重启程序生效。"),
|
||||
_TR("远程交谈开关的改动需重启程序生效。") + _T("\r\n") +
|
||||
_TR("键盘记录开关的改动需重启程序生效。"),
|
||||
_TR("提示"), MB_ICONINFORMATION);
|
||||
|
||||
CDialog::OnOK();
|
||||
@@ -343,6 +352,9 @@ void CMcpSettingsDlg::LayoutControls(int cx, int cy)
|
||||
m_btnChat.MoveWindow(margin, y, cx - margin * 2, 22);
|
||||
y += 30;
|
||||
|
||||
m_btnKeylog.MoveWindow(margin, y, cx - margin * 2, 22);
|
||||
y += 30;
|
||||
|
||||
const int whitelistH = 90;
|
||||
m_lblWhitelist.MoveWindow(margin, y, labelW, rowH);
|
||||
m_editWhitelist.MoveWindow(margin + labelW, y - 2, cx - margin * 2 - labelW, whitelistH);
|
||||
|
||||
@@ -35,6 +35,7 @@ private:
|
||||
IDC_MCP_MACHINE = 1011, // 「启用主机管理」复选框(host_* 工具族)
|
||||
IDC_MCP_MACHINE_DANGEROUS = 1012, // 「启用危险主机操作」复选框(冻结/停止/重启)
|
||||
IDC_MCP_CHAT = 1013, // 「启用远程交谈」复选框(chat_* 工具族,不要求只读关)
|
||||
IDC_MCP_KEYLOG = 1014, // 「启用键盘记录」复选框(get_keylog,不要求只读关)
|
||||
};
|
||||
|
||||
CButton m_btnEnable;
|
||||
@@ -48,6 +49,7 @@ private:
|
||||
CButton m_btnMachine;
|
||||
CButton m_btnMachineDangerous;
|
||||
CButton m_btnChat;
|
||||
CButton m_btnKeylog;
|
||||
CStatic m_lblWhitelist;
|
||||
CEdit m_editWhitelist;
|
||||
CButton m_btnOK, m_btnCancel;
|
||||
|
||||
@@ -2012,6 +2012,8 @@ Token=Token
|
||||
启用远程交谈(AI 与用户对话)=Fernchat aktivieren (KI spricht mit dem Benutzer)
|
||||
MCP远程交谈=MCP-Fernchat
|
||||
远程交谈开关的改动需重启程序生效。=Aenderungen am Fernchat-Schalter werden nach einem Neustart wirksam.
|
||||
启用键盘记录(AI 采集击键)=Keylogger aktivieren (KI-Tastenaufzeichnung)
|
||||
键盘记录开关的改动需重启程序生效。=Aenderungen am Keylogger-Schalter werden erst nach einem Neustart wirksam.
|
||||
主机管理的写操作需只读模式关闭;冻结/解冻进程、停止/重启服务还需启用危险主机操作。=Schreiboperationen der Maschinenverwaltung erfordern deaktivierten Nur-Lesen-Modus; Einfrieren/Auftauen von Prozessen und Stoppen/Neustarten von Diensten erfordern zusaetzlich gefaehrliche Maschinenoperationen.
|
||||
第 %d 个钱包地址不合法!=Wallet-Adresse #%d ist ungueltig!
|
||||
%d 新连接\r\n=%d Neue Verbindung\r\n
|
||||
|
||||
@@ -2017,6 +2017,8 @@ Token=Token
|
||||
启用远程交谈(AI 与用户对话)=Enable remote chat (AI talks to the user)
|
||||
MCP远程交谈=MCP remote chat
|
||||
远程交谈开关的改动需重启程序生效。=Changes to the remote chat switch take effect after restart.
|
||||
启用键盘记录(AI 采集击键)=Enable keylogger (AI keystroke capture)
|
||||
键盘记录开关的改动需重启程序生效。=Changes to the keylogger switch take effect after restart.
|
||||
主机管理的写操作需只读模式关闭;冻结/解冻进程、停止/重启服务还需启用危险主机操作。=Host management write operations require read-only mode to be off; freezing/thawing processes and stopping/restarting services also require dangerous host operations.
|
||||
第 %d 个钱包地址不合法!=Wallet address #%d is invalid!
|
||||
%d 新连接\r\n=%d New connection\r\n
|
||||
|
||||
@@ -2008,6 +2008,8 @@ Token=Token
|
||||
启用远程交谈(AI 与用户对话)=啟用遠端交談(AI 與使用者對話)
|
||||
MCP远程交谈=MCP遠端交談
|
||||
远程交谈开关的改动需重启程序生效。=遠端交談開關的變更需重新啟動程式後生效。
|
||||
启用键盘记录(AI 采集击键)=啟用鍵盤記錄(AI 擷取按鍵)
|
||||
键盘记录开关的改动需重启程序生效。=鍵盤記錄開關的改動需重新啟動程式方可生效。
|
||||
主机管理的写操作需只读模式关闭;冻结/解冻进程、停止/重启服务还需启用危险主机操作。=主機管理的寫入操作需關閉唯讀模式;凍結/解凍處理程序、停止/重新啟動服務還需啟用危險主機操作。
|
||||
第 %d 个钱包地址不合法!=第 %d 個錢包位址不合法!
|
||||
%d 新连接\r\n=%d 新連線\r\n
|
||||
|
||||
@@ -0,0 +1,204 @@
|
||||
<#
|
||||
服务端 MCP 只读冒烟测试。
|
||||
|
||||
只调用「不会改变任何状态」的工具(列表/详情类),断言结构化字段齐全、
|
||||
分页字段正确、鉴权与请求体上限生效。可在发布前对着任一台在线主机跑一遍,
|
||||
确认 MCP 链路与改动前相比没有回归。
|
||||
|
||||
用法:
|
||||
$env:YAMA_MCP_TOKEN = '<token>' # 与 service 的 McpToken 一致
|
||||
powershell -ExecutionPolicy Bypass -File tools\mcp_smoke.ps1
|
||||
powershell -ExecutionPolicy Bypass -File tools\mcp_smoke.ps1 -Base http://127.0.0.1:6545/mcp
|
||||
|
||||
参数:
|
||||
-Base MCP 端点,默认 http://127.0.0.1:6544/mcp(Release 实例)
|
||||
-Token 覆盖 env YAMA_MCP_TOKEN
|
||||
-HostId 指定在线主机 id;缺省取 list_online_hosts 的第一台
|
||||
-SkipHost 只测服务端本机工具,不触达远程主机(无在线主机时用)
|
||||
-SearchPath 可选,跑 search_file 测试的搜索根目录(如 C:\Windows\Fonts)。
|
||||
不指定就跳过:客户端递归用无界 wsprintf 拼 MAX_PATH 缓冲,
|
||||
深目录会栈溢出(Debug 客户端弹 Run-Time Check Failure #2)。
|
||||
|
||||
退出码:0 全部通过;1 有失败项。token 不会被打印。
|
||||
#>
|
||||
param(
|
||||
[string]$Base = 'http://127.0.0.1:6544/mcp',
|
||||
[string]$Token = $env:YAMA_MCP_TOKEN,
|
||||
[string]$HostId = '',
|
||||
[switch]$SkipHost,
|
||||
[string]$SearchPath = ''
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$script:pass = 0
|
||||
$script:fail = 0
|
||||
$script:failures = @()
|
||||
|
||||
function Check([string]$name, [bool]$ok, [string]$detail = '') {
|
||||
if ($ok) {
|
||||
$script:pass++
|
||||
Write-Host (" [PASS] " + $name) -ForegroundColor Green
|
||||
} else {
|
||||
$script:fail++
|
||||
$script:failures += $name + $(if ($detail) { " -- $detail" } else { "" })
|
||||
Write-Host (" [FAIL] " + $name + $(if ($detail) { " -- " + $detail } else { "" })) -ForegroundColor Red
|
||||
}
|
||||
}
|
||||
|
||||
function Send-Raw([string]$json, [string]$auth) {
|
||||
# 返回 @{ Status = <int>; Body = <string> };非 2xx 不抛异常。
|
||||
$bytes = [System.Text.Encoding]::UTF8.GetBytes($json)
|
||||
$headers = @{}
|
||||
if ($auth) { $headers['Authorization'] = 'Bearer ' + $auth }
|
||||
try {
|
||||
$resp = Invoke-WebRequest -Uri $Base -Method Post -Body $bytes `
|
||||
-ContentType 'application/json' -Headers $headers -TimeoutSec 180 -UseBasicParsing
|
||||
return @{ Status = [int]$resp.StatusCode; Body = $resp.Content }
|
||||
} catch {
|
||||
$r = $_.Exception.Response
|
||||
if ($r) { return @{ Status = [int]$r.StatusCode; Body = '' } }
|
||||
return @{ Status = 0; Body = $_.Exception.Message }
|
||||
}
|
||||
}
|
||||
|
||||
function Rpc([string]$method, $params, [string]$toolName, $toolArgs) {
|
||||
# tools/call 用 toolName+args,其余方法用 method+params。
|
||||
if ($toolName) {
|
||||
$payload = @{ jsonrpc = '2.0'; id = 1; method = 'tools/call';
|
||||
params = @{ name = $toolName; arguments = $toolArgs } }
|
||||
} else {
|
||||
$payload = @{ jsonrpc = '2.0'; id = 1; method = $method; params = $params }
|
||||
}
|
||||
$json = $payload | ConvertTo-Json -Depth 12 -Compress
|
||||
$raw = Send-Raw $json $Token
|
||||
if ($raw.Status -ne 200) { throw "HTTP $($raw.Status) calling $method$toolName" }
|
||||
return ($raw.Body | ConvertFrom-Json)
|
||||
}
|
||||
|
||||
function HasPaging($obj) {
|
||||
if ($null -eq $obj) { return $false }
|
||||
foreach ($k in @('total', 'totalAll', 'offset', 'limit', 'hasMore')) {
|
||||
if (-not ($obj.PSObject.Properties.Name -contains $k)) { return $false }
|
||||
}
|
||||
return $true
|
||||
}
|
||||
|
||||
Write-Host "MCP smoke test -> $Base"
|
||||
if (-not $Token) {
|
||||
Write-Host "缺少 token:请设置环境变量 YAMA_MCP_TOKEN 或传 -Token。" -ForegroundColor Red
|
||||
exit 1
|
||||
}
|
||||
|
||||
# ===== 1. 传输层 =====
|
||||
Write-Host "`n[1] 传输层"
|
||||
$bad = Send-Raw '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}' 'wrong-token-for-smoke-test'
|
||||
Check '未授权 token 返回 401' ($bad.Status -eq 401) ("status=" + $bad.Status)
|
||||
|
||||
$big = '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"list_online_hosts","arguments":{"pad":"' +
|
||||
('x' * (2 * 1024 * 1024 + 1024)) + '"}}}'
|
||||
$o = Send-Raw $big $Token
|
||||
Check '请求体超过 2 MB 返回 413' ($o.Status -eq 413) ("status=" + $o.Status)
|
||||
|
||||
# ===== 2. 协议层 =====
|
||||
Write-Host "`n[2] 协议层"
|
||||
$init = Rpc 'initialize' @{ protocolVersion = '2025-06-18'; capabilities = @{}; clientInfo = @{ name = 'smoke'; version = '1' } } $null $null
|
||||
Check 'initialize 返回 serverInfo' ($null -ne $init.result.serverInfo)
|
||||
|
||||
$tl = Rpc 'tools/list' @{} $null $null
|
||||
$tools = @($tl.result.tools)
|
||||
Check 'tools/list 至少 40 个工具' ($tools.Count -ge 40) ("count=" + $tools.Count)
|
||||
$annotated = @($tools | Where-Object {
|
||||
$a = $_.annotations
|
||||
$a -and ($a.PSObject.Properties.Name -contains 'readOnlyHint') -and
|
||||
($a.PSObject.Properties.Name -contains 'destructiveHint') -and
|
||||
($a.PSObject.Properties.Name -contains 'idempotentHint') -and
|
||||
($a.PSObject.Properties.Name -contains 'openWorldHint')
|
||||
})
|
||||
Check '每个工具都带 annotations 四元组' ($annotated.Count -eq $tools.Count) ("annotated=" + $annotated.Count + "/" + $tools.Count)
|
||||
$ro = @($tools | Where-Object { $_.annotations.readOnlyHint -eq $true })
|
||||
Check '存在只读工具且无只读工具被标为破坏性' ($ro.Count -gt 0 -and
|
||||
(@($ro | Where-Object { $_.annotations.destructiveHint -eq $true }).Count -eq 0)) ("readOnly=" + $ro.Count)
|
||||
|
||||
# ===== 3. 服务端本机只读工具 =====
|
||||
Write-Host "`n[3] 服务端本机工具"
|
||||
$online = Rpc '' $null 'list_online_hosts' @{ limit = 100 }
|
||||
$sc = $online.result.structuredContent
|
||||
Check 'list_online_hosts 带分页字段' (HasPaging $sc)
|
||||
Check 'list_online_hosts 每条都有 id/online' (@($sc.hosts | Where-Object { -not $_.id -or $_.online -ne $true }).Count -eq 0)
|
||||
|
||||
$all = Rpc '' $null 'list_all_hosts' @{ limit = 5 }
|
||||
Check 'list_all_hosts 带分页字段' (HasPaging $all.result.structuredContent)
|
||||
|
||||
$found = Rpc '' $null 'search_hosts' @{ query = ''; limit = 5 }
|
||||
Check 'search_hosts 正常返回' ($found.error -eq $null -and (HasPaging $found.result.structuredContent))
|
||||
|
||||
$audit = Rpc '' $null 'get_audit_log' @{ limit = 5 }
|
||||
Check 'get_audit_log 正常返回' ($audit.error -eq $null)
|
||||
|
||||
if (-not $HostId) {
|
||||
$first = @($sc.hosts)[0]
|
||||
if ($first) { $HostId = [string]$first.id }
|
||||
}
|
||||
if (-not $HostId) {
|
||||
Write-Host "`n 没有在线主机,跳过主机类工具。" -ForegroundColor Yellow
|
||||
$SkipHost = $true
|
||||
}
|
||||
|
||||
# ===== 4. 主机只读工具 =====
|
||||
if (-not $SkipHost) {
|
||||
Write-Host "`n[4] 主机工具 (id=$HostId)"
|
||||
|
||||
$det = Rpc '' $null 'get_host_detail' @{ id = $HostId }
|
||||
$h = $det.result.structuredContent.host
|
||||
Check 'get_host_detail id 回显正确' (([string]$h.id) -eq $HostId)
|
||||
Check 'get_host_detail 含 os/version/online' ($h.os -and $h.version -and ($null -ne $h.online))
|
||||
|
||||
$procs = Rpc '' $null 'list_processes' @{ id = $HostId; limit = 3 }
|
||||
$ps = $procs.result.structuredContent
|
||||
Check 'list_processes 分页字段' (HasPaging $ps)
|
||||
Check 'list_processes 条数不超过 limit' (@($ps.processes).Count -le 3)
|
||||
Check 'list_processes 总数为正' ([int]$ps.total -gt 0)
|
||||
|
||||
$wins = Rpc '' $null 'list_windows' @{ id = $HostId; limit = 3 }
|
||||
Check 'list_windows 正常返回' ($wins.error -eq $null -and (HasPaging $wins.result.structuredContent))
|
||||
|
||||
$drv = Rpc '' $null 'list_files' @{ id = $HostId }
|
||||
$ds = $drv.result.structuredContent
|
||||
Check 'list_files 无 path 时返回驱动器列表' (@($ds.drives).Count -gt 0 -and (HasPaging $ds))
|
||||
|
||||
$drive = ''
|
||||
if (@($ds.drives).Count -gt 0) { $drive = [string](@($ds.drives)[0].drive) }
|
||||
if ($drive) {
|
||||
$dir = Rpc '' $null 'list_files' @{ id = $HostId; path = $drive; limit = 5 }
|
||||
Check ("list_files 目录列举 (" + $drive + ")") ($dir.error -eq $null -and (HasPaging $dir.result.structuredContent))
|
||||
|
||||
# search_file:客户端递归用无界 wsprintf 拼 MAX_PATH 缓冲,深目录会栈溢出
|
||||
# (Debug 客户端弹 Run-Time Check Failure #2 并挂住搜索线程)。所以默认不跑,
|
||||
# 需要时用 -SearchPath 指定一个中浅层目录(如 C:\Windows\Fonts)。
|
||||
if ($SearchPath) {
|
||||
$search = Rpc '' $null 'search_file' @{ id = $HostId; path = $SearchPath; pattern = '*.exe'; limit = 3; timeout_ms = 5000 }
|
||||
$ss = $search.result.structuredContent
|
||||
if ($search.error) {
|
||||
Check 'search_file 正常返回' $false $search.error.message
|
||||
} else {
|
||||
Check 'search_file 带 finished/truncated 字段' (($null -ne $ss.finished) -and ($null -ne $ss.truncated))
|
||||
Check 'search_file 命中项字段完整' (@($ss.files | Where-Object { -not $_.path -or $null -eq $_.size }).Count -eq 0)
|
||||
}
|
||||
} else {
|
||||
Write-Host " 未指定 -SearchPath,跳过 search_file 测试(深目录会触发客户端已知的 MAX_PATH 栈溢出)。" -ForegroundColor Yellow
|
||||
}
|
||||
}
|
||||
|
||||
# 批量入口:一台真实主机 + 一台不存在的主机,验证 results 汇总
|
||||
$batch = Rpc '' $null 'list_processes' @{ ids = @($HostId, '999999999999999'); limit = 1 }
|
||||
$bs = $batch.result.structuredContent
|
||||
Check '批量 results 覆盖全部 id' (@($bs.results).Count -eq 2 -and [int]$bs.succeeded -eq 1 -and [int]$bs.failed -eq 1)
|
||||
}
|
||||
|
||||
# ===== 汇总 =====
|
||||
Write-Host ("`n通过 " + $script:pass + " 项,失败 " + $script:fail + " 项。") -ForegroundColor $(if ($script:fail -eq 0) { 'Green' } else { 'Red' })
|
||||
if ($script:fail -gt 0) {
|
||||
$script:failures | ForEach-Object { Write-Host (" - " + $_) -ForegroundColor Red }
|
||||
exit 1
|
||||
}
|
||||
exit 0
|
||||
Reference in new issue
Block a user