Feature: Harden the MCP transport and add non-destructive host tools

Cap MCP request bodies at 2 MB, set a 15 s idle read timeout and a 60 s
write timeout, and give httplib an explicit 32-thread pool: long tools
such as chat_wait hold a worker for up to 55 s, and the default pool of
8 to 15 left other callers queued.

Every tool returned by tools/list now carries readOnlyHint,
destructiveHint, idempotentHint and openWorldHint. The table is
per-tool; anything not registered defaults to destructive so a new
write tool cannot silently look harmless. Read-only tools are forced
to destructiveHint=false.

get_host_detail appends the technical fields the host store already
holds (cpuCores, memoryGB, systemBits, programBits, user, isAdmin,
installTime, expiredDate, monitors, exeVersion, clientPath, pid,
publicIp). The JSON writer is pinned to 15 significant digits so
memoryGB renders as 27.8 instead of 27.800000000000001. list hosts
output is unchanged.

Add host_set_remark and host_set_watch_level. Both validate the host
against the store, are refused in readonly mode, repaint the affected
row, and are audited without recording the value written.

Add search_file, which drives the client file-manager search channel
and returns paged results. The root path is normalized before sending:
the client enumerates with wsprintf("%s\*.*"), so a trailing
backslash produced C:\*.* and FindFirstFile failed, returning zero
hits instantly. The client only searches recursively, so non-recursive
requests are filtered server-side by comparing the parent directory.
Collection stops at 5000 records or 4 MB and the client is told to
stop; on timeout the partial results are returned. Search result
packets are never closed early: the sub-connection stays open until
TOKEN_SEARCH_FILE_FINISH, because the client's search thread holds a
pointer into the file manager object.

Batch reads report a skipped counter and are bounded to 50 ids and a
50 s deadline.

Add tools/mcp_smoke.ps1, a read-only end-to-end smoke test that asserts
auth rejection, the payload limit, annotation coverage, paging fields
and the main read tools. It takes the token from the environment and
never prints it.

Document all of the above in docs/Mcp_Design.md section 10, including
the client-side MAX_PATH stack overflow that a deep search_file call
can trigger, together with the workaround of searching shallow
directories.

Co-Authored-By: deepseek-flash
This commit is contained in:
yuanyuanxianganddeepseek-flash committed 2026-10-25 13:59:17 +01:00
1 parent ac5b174b5f
commit abe7e99a77
7 files changed
+1244 -11

No files matched your search

+82
View File
@@ -492,3 +492,85 @@ void CMcpSettingsDlg::OnBnClickedBtnSave()
- `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` 链路),不重复造工具。