5 Commits
Author SHA1 Message Date
yuanyuanxianganddeepseek-flash 1c832ff7f2 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
2026-10-28 21:25:49 +01:00
yuanyuanxianganddeepseek-flash 3d388f8e45 Feature: Add remote_block_input to MCP remote control
A GUI automation run is interrupted the moment a person at the host touches
the mouse, and locking the host's keyboard and mouse is the standard answer.
The client already implements COMMAND_SCREEN_BLOCK_INPUT and the MFC screen
window already sends it, so the tool needs no client change: it puts the same
two-byte packet [COMMAND_SCREEN_BLOCK_INPUT][0|1] on the hidden screen
sub-connection that remote_open established. The gate is remote_open's own -
McpRemoteControl=1 and McpReadonly=0 - because the ability to lock someone out
deserves exactly the same door as the ability to drive their desktop, and
Linux and Android clients are refused with -32005: they have no branch for
this packet at all and would silently ignore it.

Locking a host out is only acceptable if every way back in is closed, so the
session now carries its own lock state and three paths release it. block=false
releases it directly. block=true always carries a deadline (max_block_ms,
default 300000, clamped to 1000..3600000) and a watchdog thread started with
the MCP server sweeps every 500ms for expired locks, sends the release and
records it; the next remote_block_input reports it as auto_unblocked so the
model learns that its lock lapsed instead of assuming it is still held.
remote_close and the idle reclaim both send block=false before they tear the
sub-connection down, because once that connection is gone the server has no
channel left and a live client process stays blocked - all three release
paths write an audit line, since none of them is something a person can see.

The send happens outside the MCP lock, and the watchdog takes the session's
busy flag while it releases, so it cannot interleave with an injection or race
a close; a failed send keeps the lock marked and retries five seconds later
rather than hammering a dead connection every tick, and a session that dies
under the watchdog is erased the same way an injection would erase it.

Verified against a real Windows client over MCP on a Debug x64 build: block
then unblock, block with a 1.5-2s deadline left to expire and reported back as
auto_unblocked with the watchdog audit entry at the expected second, block
with a ten-minute deadline then remote_close with "(input lock forced off)"
in the audit, and the five refusals (missing block, non-boolean block,
max_block_ms out of range, unknown session, offline host). The smoke test
gained [4d] for those refusals; 54 checks pass. Two limits are worth stating
plainly. BlockInput only works when the calling process is elevated (or
UIAccess), the client ignores the API's return value, so on an ordinary
client the lock silently does nothing and the tool can only promise that the
command was delivered - both the tool description and the server instructions
say so. And the idle-reclaim release, like the two verified paths, is only
exercised at a 300s idle timeout; it shares the same send helper and was
reviewed rather than timed out live. Bin/settings.ini was restored
byte-exact and the Release instance was left alone.

Co-Authored-By: deepseek-flash
2026-10-28 21:25:47 +01:00
yuanyuanxianganddeepseek-flash 27b5431130 Feature: Add the file-write tools behind their own switch
P10-B adds delete_path, move_path and create_folder, and the switch they
need. Reusing McpFileTransfer would have been wrong: uploading overwrites a
file, deleting destroys a tree, and an operator who wants one may well not
want the other. McpFileWrite is therefore a separate key, off by default,
wired the way every other switch is - read from settings.ini at startup,
reported as get_server_status.switches.file_write, and exposed with its own
checkbox in the MCP settings dialog. The tools additionally require readonly
to be off: a read-only server has no business modifying a host.

No client change was needed: COMMAND_DELETE_FILE, COMMAND_DELETE_DIRECTORY,
COMMAND_CREATE_FOLDER and COMMAND_RENAME_FILE already existed in the Windows
file manager. The chain reuses the file-manager sub-connection and adds a
phase - the main connection asks for the drive list, the sub-connection's
first packet hands it to OnDriveList which sends the write command, and the
client's TOKEN_*_FINISH ack moves the pending request from phase 0 to 1,
where the tool sends COMMAND_LIST_FILES for the parent so the ack and the
confirmation share one timeout. Only the IO thread touches the
sub-connection; the tool thread just waits on the shared condvar, which keeps
the sub-connection's lifetime out of its reach.

The confirmation exists because the client answers unconditionally: it
ignores the return values of DeleteFile, MoveFile and
MakeSureDirectoryPathExists and there is no error token. ok therefore only
means "the command arrived", and verified is the real answer - true when the
parent listing shows the expected post-state, false when it shows the
opposite, null when the listing itself did not come back (timeout or
disconnect), since reporting that as false would be a lie. Linux, macOS and
Android hosts are refused outright: those clients decode these paths as GBK
while the server speaks UTF-8 to them for list_files, so a non-ASCII path
would corrupt rather than fail. Paths are validated as UTF-8, converted to
GBK exactly once, and reject %VAR%, relative paths, drive and share roots,
and - for delete_path and for move_path's source - the Windows, Program
Files, ProgramData, $Recycle.Bin and System Volume Information trees.
create_folder gets no system-directory ban, because writing there is the same
permission upload_file already has.

Two defects surfaced while exercising this against a real client:
create_folder's wire path has to end with a backslash, because
MakeSureDirectoryPathExists treats a non-terminated last component as a file
name and only creates the intermediate levels; and
ResolveFileOpVerified(LookupInListing(...), isDir, ...) read isDir before the
lookup ever set it - argument evaluation order is unspecified and MSVC
evaluates right to left - so every create_folder reported verified=false even
when the directory existed.

Verified on a Debug x64 build against a Windows client over MCP: nested
create_folder, upload, rename, delete, delete a tree, the failure shapes
(delete with recursive=false on a directory, create_folder onto an existing
file name, delete of a non-existent target) and every refusal (drive root,
C:\Windows\Temp, C:\Users, %TEMP%, relative, empty, over-long, from==to,
offline host, non-numeric id), with a Chinese-named directory created,
renamed and deleted end to end; no file-manager window appeared in the server
process during any of it. The smoke test gained section [4c], opt-in through
-FileWriteDir, which asserts verified and never ok and walks a sandbox
through the same path; two runs passed 69 checks with the sandbox removed
afterwards. Bin/settings.ini was restored byte-exact and the Release
instance was left alone.

Co-Authored-By: deepseek-flash
2026-10-28 21:25:46 +01:00
yuanyuanxianganddeepseek-flash bb55f52b29 Feature: Add instructions, capability reporting and filters to MCP
P10-A is the first batch of the next MCP phase: the server now tells a model
how it expects to be driven instead of leaving the rules to be inferred from
per-tool descriptions.

initialize carries the instructions field that MCP 2025-06-18 defines, in
five sections: where host ids come from, which switch hides which tool, what
each error code implies for the next action, typical orchestrations, and
safety. Every statement was checked against the implementation rather than
derived from the tool descriptions, and four did not survive: the host_*
family only supports name/pid filters in part (named per tool now), read-only
mode does not hide host_set_remark and host_set_watch_level (they touch only
the local host store and are refused with -32006 when called), -32003 is one
lock keyed by device id rather than one per capability, and there is no
"screen stream" tool to pick instead of get_screenshot. The string is built
from u8 literals because the project compiles with /execution-charset:.936.

get_host_detail returns a capabilities object (platform, screenPreview,
remoteControl, fileTransferV2, c2cPaths, registry), each flag tied to a gate
that already exists in the dispatcher, so a model no longer discovers a
host's limits by calling and reading -32005. remoteControl mirrors the two
conditions remote_* actually applies (Windows or Linux, and not
multi-monitor), not the preview bit. Making the flags honest exposed
list_registry rejecting only LNX and MAC, so an APK host passed and then
waited out the timeout; it now uses the same is-Windows predicate the bit is
computed from. That predicate existed as identical local copies in
McpMachine.cpp and McpChat.cpp and now lives in McpInternal.

list_processes and list_windows take an optional name and pid, filtered on
the server before the page window is applied, with total counting matches
and totalAll still reporting the unfiltered count. The two tools get their
own schema builder so list_services does not advertise a filter it would
silently ignore, and the pid descriptions differ because a pid means the
process itself for one tool and its owner for the other.

get_keylog gains set_offline and clear, the two commands the client already
implements on the keyboard sub-connection but nothing on the MCP side ever
sent, plus offlineRecord from the ready packet's byte 1. Both writes are
gated on McpReadonly=0 and validated before COMMAND_KEYBOARD goes out, so a
refused call cannot leave a running keyboard session behind; the tool's
annotations change from read-only to writable and destructive, and the
server instructions gain the matching sentence.

Four capabilities are exposed twice through two different sub-connection
chains, so each pair's descriptions now say which one to reach for first and
when the other is the only option: the host_* trio carries more fields and
filters on the server, the list_* trio is the McpMachine=0 fallback, and
operate_window is the only one that can close a window. No tool was merged:
the split is what lets McpMachine be switched off on its own. search_file's
description drops the stale MAX_PATH-overflow warning (fixed in 8f718d9) for
the behaviour that remains - the client silently skips any entry whose full
path does not fit, so a drive-root scan misses deep results and reaches the
10000-entry cap sooner.

Verified per commit by building the Debug x64 server, starting it on a spare
port so the running Release instance could not answer instead, and reading
the fields back out of real responses as UTF-8; tools/list shows 54 tools
with the edited descriptions present. Bin/settings.ini was restored
byte-exact and the Release instance was left alone. The smoke test gained
assertions for all four additions: instructions has to parse out of
initialize, capabilities is compared against the reported platform (registry
true exactly for the Windows client types, remoteControl false on macOS and
Android), the filters query a real entry back by name and by pid while
totalAll stays put, and offlineRecord accepts both a boolean and its absence
for old clients. That script ran 28 checks clean against this build, with
the host-scoped assertions exercised against synthetic responses on a
separate harness (12 of 12, including the negative cases).

Co-Authored-By: deepseek-flash
2026-10-28 21:25:44 +01:00
yuanyuanxianganddeepseek-flash 4a3cded174 Docs: Plan the next MCP phase, with its claims checked against the code
Mcp_Next_Plan.md lays out what the MCP surface can still gain and how the
existing tools can be improved: a full client-command coverage matrix, a
file-system write batch, a remote-control gap, and a list of protocol-level
blanks. Every conclusion is tied to a file and line so the next step can be
implemented without re-deriving the analysis.

The first draft was written from a read of the code but not verified against
it. Auditing it turned up four claims that would have sent the work in the
wrong direction, and they are corrected here rather than left to be discovered
during implementation:

- The draft wanted a mode=offline for get_keylog because "the tool only sees a
  1-15s live window". That premise is false. CKeyboardManager1 builds its
  CircularBuffer from the on-disk record file, and SendData replays the whole
  buffer from position zero on every (re)connect, so the existing tool already
  returns the persisted history whenever kbrecord=Yes. What is actually missing
  is only the on/off switch, the clear command, and reporting the state the
  client already sends in TOKEN_KEYBOARD_START byte 1.

- Unlike P7, the file-write tools do not plug into OnSystemReady: their ready
  packet is TOKEN_DRIVE_LIST, which lands in OnDriveList, where an empty path
  is currently read as "list drives" and consumed. Worse, the three finish
  tokens have no case at all in the top-level dispatch, so on the MCP path
  (hDlg == NULL) they fall into default: and the sub-connection is never
  closed. Appendix C now spells out the three wiring layers that every
  sub-connection write tool has to touch.

- -32008 carries two meanings, not four: both remaining sites are argument
  validation, and the multi-monitor rejection was already moved to -32005.
  Dropping the proposed -32013 removes a whole error-code split.

- The draft put server gate state into get_host_detail, duplicating the
  switches object that get_server_status already returns; monitors and most
  per-host facts are already there too, so capabilities shrinks to the
  client's own ability bits.

It also records what the audit added: delete_path inherits the client's
unbounded wsprintf when recursing (the search path got a length guard in
8f718d9, DeleteDirectory and FixedUploadList did not), a single read-only file
fails silently while a directory delete clears the attribute first, and
create_folder means "ensure this path exists" rather than "create the last
component".

Co-Authored-By: deepseek-flash
2026-10-28 18:50:53 +01:00
13 changed files with 4107 additions and 167 deletions

No files matched your search

+3 -2
View File
@@ -677,15 +677,16 @@ token 只从 `-Token` / env 读取,不落仓库、不打印;无在线主机
| `-32602` | Invalid params | 未知工具名、缺必填参数、参数类型/取值非法、批量 `ids` 超过 50 个、`search_file` 过滤参数非法、文本无法转 GBK | 改参数重试,重试同样的请求不会成功 |
| `-32001` | Timeout | 等客户端就绪/等子连接/等搜索结果超时(`timeout_ms` 内没等到) | 可加大 `timeout_ms` 重试;持续出现看主机是否卡住 |
| `-32002` | Host offline / not found | 主机 id 不存在、主连接已断、会话 id 不存在或已关闭 | 先 `list_online_hosts` 刷新再选主机 |
| `-32003` | Busy | 该主机已有同类请求在飞(终端/截屏/文件/聊天会话),或同设备重复 `chat_open` | 等前一个结束或先 `*_close` |
| `-32003` | Busy | 该主机已有同类请求在飞(终端/截屏/文件/聊天会话),或同设备重复 `chat_open`。`message` 末尾带 `(tool=..., elapsed=Ns)` 点名占用者 | 用 `mcp_list_sessions` 看全部会话;等前一个结束、先 `*_close`,或 `mcp_cancel_session` 释放 |
| `-32004` | Send failed | 命令写入主连接失败(连接刚断) | 重试一次;仍失败按 `-32002` 处理 |
| `-32005` | Not supported on this host | 能力限制,改参数也修不好:需要 Windows 的工具用在 LNX/MAC/APK 主机上;`remote_open` 遇到多显示器(阶段一);主机无屏幕预览/控制能力位 | 换主机或换工具;不要改参数重试 |
| `-32006` | Policy refused | 只读模式 / 对应 `Mcp*` 开关关闭 / 主机不支持该能力(如 V2 文件传输) | **不要重试**:这是配置决定,需管理员改服务端配置 |
| `-32007` | Not in command whitelist | `exec_command` 的命令不在 `McpCmdWhitelist` 里,或词边界不匹配(`dir` 过、`dirx` 拒) | **不要重试**:换成白名单内的命令,或请管理员加白名单项 |
| `-32008` | Rejected by validation | 只覆盖「参数被校验拒绝、改参数可修」:`exec_command` 含 shell 元字符(Windows `&\|<>^`;Linux `&\|<>;` 与反引号、`$(` `${` `!`)或控制字符(含 `\r\n`);`terminal_exec` 含 `&`/`\|`/换行;路径/参数含非法字符 | 按 `message` 修正参数后重试 |
| `-32012` | Rejected by validation | 只覆盖「参数被校验拒绝、改参数可修」:`exec_command` 含 shell 元字符(Windows `&\|<>^`;Linux `&\|<>;` 与反引号、`$(` `${` `!`)或控制字符(含 `\r\n`);`terminal_exec` 含 `&`/`\|`/换行;路径/参数含非法字符。**`-32008` 是同一语义的历史别名**(早期实现用它,已发布的客户端/文档可能仍在匹配),新代码一律用 `-32012` | 按 `message` 修正参数后重试 |
| `-32009` | Target not found | 远端路径/注册表键不存在(win32 `2`/`3`,由新客户端主动回报);`kill_network_connection` 的四元组在当前连接表里查不到(`dry_run` 传假四元组最常见) | 先用 `list_files`/`list_registry`(或 `host_list_network_state`)确认目标存在 |
| `-32010` | Access denied | 目标存在但权限不足(win32 `5`):非提权客户端的服务枚举(`OpenSCManager`)、受保护目录(如 `System Volume Information`)、受保护注册表键(如 `HKLM\SAM`) | **不要重试**:需客户端提权(管理员运行)或换目标 |
| `-32011` | Destination write failed | 文件传输的**目标端**已收到数据但写盘失败:`copy_files_c2c` / `upload_file` 的目标主机回了回执且 `status != 0`(`message` 带 status、首个 errno、实收文件数) | **不要原样重试**:按文案判断(errno 13/1→权限、2→路径不存在、28→磁盘满),先修目标端目录/权限 |
| `-32800` | Request cancelled | 客户端取消了这次调用:`notifications/cancelled`、`mcp_cancel_session` 或 SSE 流断开(检测到断开会置同一个取消位)。工具在 ≤1s 内退出等待并走既有的超时清理路径,主机占用已释放 | 不是主机故障,可直接重试;终止类命令可能已经执行,重试前先读一次现状 |
- **命令超时会销毁持久会话**(`terminal_exec`):等服务端收集到哨兵超时返回 `-32001`,会话随即被销毁并留 600 秒「墓碑」;对同一 `session_id` 再发命令返回 `-32002`,文案明确写 `Terminal session was destroyed after this command timed out (waited N ms); call terminal_open again`,与「id 写错」(`Terminal session not found: <id>`)区分开。
- **新客户端把失败改成结构化回报**(`TOKEN_SERVICE_ERROR=170` / `TOKEN_FILE_LIST_ERROR=171` / `TOKEN_REG_ERROR=172` / `TOKEN_DOWNLOAD_ERROR=173`,布局 `[token:1][win32 码:4 LE]`):`list_services`(未提权)、`list_files`/`list_registry`(路径/键不存在或拒绝访问)、`download_file`(远端路径全部不存在)都在客户端侧就失败并立即回报,服务端转译成 `-32009`/`-32010`,**亚秒级返回**,不再靠超时猜。老客户端不发这些包,成功路径报文一律不变,因此老客户端/老服务端的行为与改造前完全一致(老服务端把未知 token 走 `default` 丢弃)。
+682
View File
@@ -0,0 +1,682 @@
# MCP 能力扩展与优化方案(P10 起)
> 版本:v2(已按代码核对修订) 状态:评审通过,按 §6 顺序施工
> 前置文档:`Mcp_Design.md`(协议/架构/配置/错误码)、`Mcp_Phase2_Design.md`(双模式无头驱动)、
> `Mcp_Manage_Design.md`(P7 写工具范式)、`Mcp_Machine_Design.md`(P8 会话抽象)、
> `Mcp_Terminal_Design.md`、`Mcp_RemoteControl_Design.md`、`Mcp_FileTransfer_Design.md`、`Mcp_Chat_Design.md`、
> `Mcp_Test_Report_2026-10-25.md`(实测结论与已修问题)
>
> 本文回答两个问题:**还能做哪些工具**、**现有工具还能怎么优化**。所有结论都落到具体文件与行号,
> 并区分「客户端零改动」「需客户端改动」「客户端尚未实现」三种可行性。
>
> **v2 修订要点**(逐条核对代码后更正,详见各节开头的「初稿的错误」):
> §5.2 的 `mode=offline` 前提不成立(历史数据本来就会回传);§2.3 低估了服务端接线工作量;
> §5.6 的「一码四义」不成立;§5.1 的 `serverGates` 与 `get_server_status` 重复;§3.2 应给出明确优先级。
---
## 0. 结论摘要
1. **工具面已经覆盖「看 + 管 + 连」三层**(54 个工具,8 个功能族),但仍有三处结构性缺口:
**文件系统只有读没有写**(能列、能搜、能传,不能删/改名/建目录)、
**远程控制缺「防人工干扰」与「能力自述」**(无法锁定对端键鼠、模型不知道主机支持什么)、
**同一能力存在两套重叠工具**(`list_processes` vs `host_list_processes` 等 4 组,模型不知该选哪个)。
2. **最高性价比的一批新工具是文件系统写操作**(`delete_path` / `move_path` / `create_folder`):
客户端四个命令 + 三个完成 token **全部已实现**(`client/file/FileManager.cpp:97-121`;
`TOKEN_DELETE_FINISH` 被删文件与删目录复用)。MCP 侧复用 P7 的 `followUp` 范式即可,
**客户端零改动**,一次性补齐「AI 能整理远程磁盘」这个最常用场景。
注意这不等于「照抄 P7」:文件管理器子连接的就绪包是 `TOKEN_DRIVE_LIST` 不是
`TOKEN_SYSTEM_READY`,且三个完成 token 在服务端顶层分发里**还没有 case**——真正的接线
工作量在这里,详见 §2.3。
3. **最大的非工具类短板是「能力自述」**:`get_host_detail` 不告诉模型这台主机支持什么,
模型只能靠 `-32005` 试错(`list_registry`、`get_screenshot`、`remote_*`、`upload_file` 各有平台/能力位门槛)。
补一个 `capabilities` 对象是**纯服务端改动、几十行代码**,但直接减少一整类无效调用。
服务端开关态不必另开字段——`get_server_status` 的 `switches` 已经完整暴露(`McpServer.cpp:3142`),
`capabilities` 只描述「这台主机本身能做什么」,两者分工明确。
4. **协议层有四个空白**:`initialize.instructions`、`notifications/progress`、`notifications/cancelled`、
`logging`。其中前两个直接影响「长任务(下载/上传/搜索/chat_wait)时模型以为卡死」的体验。
5. **不建议现在做**的:注册表写、Windows 事件日志、进程模块/启动项、剪贴板读——都需要客户端改,
且安全边界要单独评审;代理隧道(`COMMAND_PROXY`)价值最高但工程量大,建议单独立项。
> **一处需要纠正的常见误解**:进程「挂起 / 恢复」**已经实现**,不需要新工具——
> 它是 `host_control_process` 的 `action=freeze|thaw`(`McpMachine.cpp:2107`),
> 且已带「动作后重拉进程列表复核」的验证逻辑。本轮不再重复造这个工具。
---
## 1. 现状盘点
### 1.1 工具族(54 个)
登记表在 `server/2015Remote/McpInternal.cpp:368` 的 `kToolHints[]`。
注意:**表头注释写「53 个工具」,实际数组是 54 项**(注释已过期,属一处文档瑕疵,见 §5.13)。
| 族 | 数 | 工具 | 门控条件 |
|---|---|---|---|
| 服务端本机只读 | 7 | `list_online_hosts` `search_hosts` `list_all_hosts` `get_host_detail` `get_activity_history` `get_audit_log` `get_server_status` | `McpReadonly`(默认 1 = 只读) |
| 主机只读 | 21 | `list_processes` `list_windows` `list_files` `list_services` `get_client_log` `get_keylog` `get_screenshot` `list_registry` `download_file` `search_file` `list_network_connections` + `host_list_*`(10 个标签页) | `McpReadonly`;`get_keylog` 另需 `McpKeylog=1`;`host_list_*` 另需 `McpMachine=1` |
| 终端 | 4 | `terminal_open` `terminal_exec` `terminal_close` `exec_command` | `McpTerminal=1` **且** `McpReadonly=0` |
| 远程控制 | 5 | `remote_open` `remote_close` `remote_mouse` `remote_keyboard` `remote_clipboard` | `McpRemoteControl=1` **且** `McpReadonly=0` |
| 文件传输 | 2 | `upload_file` `copy_files_c2c` | `McpFileTransfer=1`(`download_file` 只要求此开关,不要求 `McpReadonly=0`) |
| 设备管理 | 4 | `kill_process` `operate_window` `control_service` `power_action` | `McpManage=1` **且** `McpReadonly=0` |
| 主机/连接管理 | 7 | `kill_network_connection` `host_control_process` `host_control_window` `host_control_service` `host_control_task` `host_set_remark` `host_set_watch_level` | 前 5 个:`McpMachine=1` + `McpMachineDangerous=1` + `McpReadonly=0`;后 2 个只要求 `McpReadonly=0` |
| 远程交谈 | 4 | `chat_open` `chat_send` `chat_wait` `chat_close` | `McpChat=1`(与 `McpReadonly` 无关) |
**已有的工程范式**(新工具直接复用,不必重新设计):
- **一次性子连接 + 首包即数据**:`list_processes` / `list_windows` / `list_services` / `list_registry` / `get_client_log`。
- **接管子连接 → 发写命令 → 收确认**(`PendingRequest::followUp` / `followUpSent`):`kill_process` / `operate_window` / `control_service`(`Mcp_Manage_Design.md §3`)。
- **多步会话抽象**(`PendingKind::Machine` / `ConnMgr`):`host_list_*` / `host_control_*`(`Mcp_Machine_Design.md §3`)。
- **流式会话**(`TermSession` / `ScreenCtrlSession` / `FileTransferSession` / `ChatSession`):终端、远程控制、文件传输、聊天。
- **迟到首包吸收**(`MarkLateFirstPacketForTool` / `TakeToolFirstPacket`):防超时后误弹 MFC 窗口。
### 1.2 协议层能力
| 能力 | 现状 | 证据 |
|---|---|---|
| `initialize` / `ping` / `tools/list` / `tools/call` | ✅ | `McpServer.cpp:7633` 起 |
| `initialize.instructions` | ❌ 未实现 | 全文 0 处 `instructions` |
| `tools/list` 的 `annotations` | ✅ 四类 hint 齐备 | `McpInternal.cpp:437` `ApplyToolAnnotations` |
| `outputSchema` | ✅ 48 处 | — |
| `resources` / `prompts` | ❌ 未实现 | 0 处 |
| `notifications/progress` | ❌ 未实现 | 0 处 `progressToken` |
| `notifications/cancelled` | ❌ 未实现 | 0 处 `cancelled` |
| `Mcp-Session-Id` | ❌ 无状态 | 0 处 |
| 分页 | 用 `limit`/`offset`,非 MCP `cursor` | 全部列表工具一致 |
| 传输 | Streamable HTTP `POST /mcp`;可选内置 TLS 终结(`McpTlsProxy`) | `Mcp_Design.md §13` |
| 认证 | 静态 Bearer token + 失败计数封禁 | `Mcp_Design.md §3.5` |
| 错误码 | `-32700` … `-32011` 共 14 个 | `Mcp_Design.md §12` |
### 1.3 客户端能力 → MCP 覆盖矩阵
对 `common/commands.h` 中 Windows 客户端**已实现**的命令逐个核对(`client/KernelManager.cpp`、`client/MachineManager.cpp`、`client/file/FileManager.cpp`、`client/ScreenManager.cpp`、`client/KeyboardManager.cpp`):
| 客户端能力 | 命令 | MCP 现状 | 可行性 |
|---|---|---|---|
| 列目录 / 列盘 | `COMMAND_LIST_FILES` / `COMMAND_LIST_DRIVE` | ✅ `list_files` | — |
| 搜索文件 | `COMMAND_SEARCH_FILE` | ✅ `search_file` | — |
| 下载 / 上传 | `CMD_DOWN_FILES_V2` / `COMMAND_SEND_FILE_V2` | ✅ `download_file` / `upload_file` | — |
| 客户端间直传 | `COMMAND_C2C_SEND_FILES` | ✅ `copy_files_c2c` | — |
| **删除文件** | `COMMAND_DELETE_FILE` → `TOKEN_DELETE_FINISH` | ❌ **缺** | **零客户端改动** |
| **删除目录(递归)** | `COMMAND_DELETE_DIRECTORY` → `TOKEN_DELETE_FINISH` | ❌ **缺** | **零客户端改动** |
| **新建目录** | `COMMAND_CREATE_FOLDER` → `TOKEN_CREATEFOLDER_FINISH` | ❌ **缺** | **零客户端改动** |
| **重命名 / 同卷移动** | `COMMAND_RENAME_FILE` → `TOKEN_RENAME_FINISH` | ❌ **缺** | **零客户端改动** |
| 进程列表 / 结束 | `COMMAND_PSLIST` / `COMMAND_KILLPROCESS` | ✅ `list_processes` / `kill_process` | — |
| 进程挂起 / 恢复 | `COMMAND_PROCESS_FREEZING` / `COMMAND_PROCESS_THAW` | ✅ `host_control_process(action=freeze\|thaw)` | — |
| 窗口列表 / 控制 | `COMMAND_WSLIST` / `CMD_WINDOW_CLOSE` / `CMD_WINDOW_TEST` | ✅ `list_windows` / `operate_window` | — |
| 服务列表 / 控制 | `TOKEN_SERVERLIST` / `COMMAND_SERVICECONFIG` | ✅ `list_services` / `control_service` | — |
| 计划任务 / 软件 / 驱动 / 浏览器记录 / 收藏 / hosts 读 | `COMMAND_MACHINE_*` | ✅ `host_list_*`(10 个) | — |
| **写 hosts 文件** | `COMMAND_HOSTS_SET` | ❌ **缺** | 零客户端改动,但**整文件覆盖**,高风险 |
| **卸载软件** | `COMMAND_APPUNINSTALL`(`WinExec`,无回包) | ❌ **缺** | 零客户端改动,风险高 |
| 连接列表 / 断开连接 | `COMMAND_CONNECTION` / `COMMAND_KILL_CONNECTION` | ✅ `list_network_connections` / `kill_network_connection` | — |
| 屏幕截图 | `COMMAND_SCREEN_PREVIEW_REQ` | ✅ `get_screenshot` | — |
| 鼠标 / 键盘 / 剪贴板写 | `COMMAND_SCREEN_CONTROL` + `MSG64` | ✅ `remote_*` | — |
| **锁定对端键鼠** | `COMMAND_SCREEN_BLOCK_INPUT`(2 字节) | ❌ **缺** | **零客户端改动**(无回包) |
| 黑屏 / Ctrl+Alt+Del | `COMMAND_SCREEN_BLANK` / `COMMAND_SCREEN_CTRL_ALT_DEL` | ❌ | **客户端未实现**,需客户端改动 |
| 窗口级 / 区域捕获 | `COMMAND_SCREEN_WINDOW` / `COMMAND_SCREEN_ROI` | ❌ | 流式接口,需评估(见 §4.2) |
| 注册表读 | `COMMAND_REGEDIT` + `COMMAND_REG_FIND` | ✅ `list_registry`(子键 + 值) | — |
| **注册表写** | 无命令 | ❌ | **需客户端改动** |
| 键盘记录(实时) | `COMMAND_KEYBOARD` | ✅ `get_keylog` | — |
| **键盘记录(离线常驻)** | `COMMAND_KEYBOARD_OFFLINE` / `COMMAND_KEYBOARD_CLEAR` | ❌ **缺** | **零客户端改动**(见 §5.2) |
| 客户端日志 | `COMMAND_QUERY_LOG` | ✅ `get_client_log` | — |
| 电源操作 | `TOKEN_MACHINE_MANAGE` | ✅ `power_action` | — |
| 远程交谈 | `COMMAND_CHAT` | ✅ `chat_*` | — |
| **客户端升级** | `COMMAND_UPDATE` | ❌ | 零客户端改动,需独立评审(见 §4.4) |
| **上传执行 / 下载执行** | `COMMAND_UPLOAD_EXEC` / `COMMAND_DOWN_EXEC` | ❌ | 零客户端改动,需独立评审(见 §4.4) |
| **代理映射** | `COMMAND_PROXY` | ❌ | 需独立设计(见 §4.3) |
| 摄像头 / 语音 | `COMMAND_WEBCAM` / `COMMAND_AUDIO` | ❌ | 需流式解码,建议后置 |
| 清除事件日志 / 隐藏开网页 / 卸载后门 | `COMMAND_CLEAN_EVENT` / `COMMAND_OPEN_URL_*` / `COMMAND_REMOVE` | ❌ | **当前 Windows 客户端未实现**,为死命令 |
**结论**:客户端已实现、但 MCP 还没接的能力共 **14 项**,其中 **9 项属「零客户端改动、可常规批次接入」**:
- 文件写 4 项(删除文件 / 删除目录 / 建目录 / 改名移动)
- 键鼠锁定 1 项(`remote_block_input`)
- 离线键盘记录 2 项(开关 / 清空)
- 主机侧 2 项(写 hosts、卸载软件)—— 零改动但风险高,建议后置或不做
另有 5 项(代理、升级、上传执行、摄像头、窗口级捕获)虽也零客户端改动,但工程量或风险远超常规批次,需单独立项(§4)。
---
## 2. 新工具(P10-A):文件系统写操作
### 2.1 为什么是最高优先级
MCP 现在能读、能传、能搜,**唯独不能删、不能改名、不能建目录**。任何「整理远程磁盘」「清理临时文件」「归档日志」「部署目录准备」类任务都会卡在最后一步,只能退回 `exec_command`(`del` / `move` / `mkdir`)——而 `exec_command` 受命令白名单约束(`McpCmdWhitelist`),`del` 默认不在白名单里,且无法处理中文路径与超长路径的编码问题。
用原生文件通道做,还能绕开 shell 白名单、拿到确定的 ack、复用已有的 `TOKEN_*_FINISH` 协议。
### 2.2 工具定义
| 工具 | 入参 | 客户端命令 | 完成 ack |
|---|---|---|---|
| `delete_path` | `id`、`path`、`recursive`(默认 `false`) | `recursive=true` → `COMMAND_DELETE_DIRECTORY`;否则 `COMMAND_DELETE_FILE` | `TOKEN_DELETE_FINISH` |
| `move_path` | `id`、`from`、`to` | `COMMAND_RENAME_FILE` + `[from\0][to\0]` | `TOKEN_RENAME_FINISH` |
| `create_folder` | `id`、`path` | `COMMAND_CREATE_FOLDER` + `[path\0]` | `TOKEN_CREATEFOLDER_FINISH` |
输出统一为 `{id, path, ok:true, verified?:bool}`,并附一句可读摘要。
### 2.3 复用链路(与 P7 同构,但**不是**照抄 P7)
```
主连接 COMMAND_LIST_DRIVE → 客户端建文件管理器子连接 → 子连接回 TOKEN_DRIVE_LIST
→(followUp)下发 COMMAND_DELETE_FILE / _DIRECTORY / _CREATE_FOLDER / _RENAME_FILE
→ 等 TOKEN_*_FINISH → 关闭子连接
```
- 服务端已有现成的三段式入口:`list_files`(`McpServer.cpp:2419`)、`search_file`(`McpServer.cpp:8050`)、`download_file`(`McpServer.cpp:6430`)都走 `COMMAND_LIST_DRIVE` 开子连接。
- `PendingRequest` 的 `followUp` / `followUpSent` / `subCtx` 字段(`McpServer.h:584-587`)足够承载「先等就绪首包、再发写命令、再等确认」的两阶段语义,**数据结构不用改**。
- 路径编码:客户端工程是 MultiByte,路径必须 `Utf8ToCpExact` 严格转 GBK(同 `search_file` 的做法),不可表示即 `-32602`。
**但接入点必须新写三处,这是本节的主要工作量:**
1. **就绪包分流走 `OnDriveList`,不是 `OnSystemReady`。**
`OnSystemReady`(`McpServer.cpp:8070`)里有工具名硬门(只认 `kill_process` / `operate_window`),且文件管理器子连接的就绪包是 `TOKEN_DRIVE_LIST`,根本不会进那个分支。
`OnDriveList`(`McpServer.cpp:7832`)当前对空 `path` 一律判定为「只列盘」并把 `TOKEN_DRIVE_LIST` 当数据取走(`:7846-7851`),所以必须在它最前面按 `tool` 分流:文件写工具 → 下发 `followUp`、保持子连接、返回 `false`。
2. **三个完成 token 需要在服务端顶层分发新增 case。**
`TOKEN_DELETE_FINISH` / `TOKEN_RENAME_FINISH` / `TOKEN_CREATEFOLDER_FINISH` 目前只在 `server/2015Remote/FileManagerDlg.cpp:983-995` 的 hDlg 路径里处理。MCP 的子连接 `hDlg == NULL`(`NotifyProc` 只有 hDlg 存在才交给对话框),三个包会落到 `2015RemoteDlg.cpp:7249` 的 `default:`——只打一行 "unknown command"、**并不关闭子连接**。必须新增 case:`TakeMainResponse` + `CancelIO`。
3. **`MarkLateFirstPacketForTool` 要登记新工具。**
否则工具超时后迟到的 `TOKEN_DRIVE_LIST` 会当成人工操作,**弹出 MFC 文件管理器窗口**。把新工具名加入 `TOKEN_DRIVE_LIST` 那条分支(`McpServer.cpp:7760`)即可。
### 2.4 已知限制(必须写进工具描述)
| 限制 | 原因 | 缓解 |
|---|---|---|
| **ack 只代表「已执行」,不代表「成功」** | 客户端忽略 `DeleteFile` / `MoveFile` / `MakeSureDirectoryPathExists` 的返回值,无条件 `SendToken(..._FINISH)` | 文档明确要求「调用后用 `list_files` 复核」;可选增强见 §5.7 |
| **`move_path` 仅同卷** | 客户端用 `::MoveFile`(`client/file/FileManager.cpp:990`),非 `MoveFileEx` | 描述里写「跨盘请改用 `download_file` + `upload_file`」 |
| **删除无回收站、目录递归** | `COMMAND_DELETE_DIRECTORY` → `DeleteDirectory` 递归删除 | 工具描述加显著警告;`recursive` 必须显式传 `true` |
| **删除单个只读文件会静默失败** | `COMMAND_DELETE_FILE` 直接 `DeleteFile`(`:101`),不像 `DeleteDirectory` 那样先 `SetFileAttributes(...NORMAL)`(`:659`) | 描述里提示「只读文件请先改属性」 |
| **`create_folder` 会自动建中间层** | `MakeSureDirectoryPathExists`,语义是「确保路径存在」而非「只建最后一级」 | 写进描述:传入已含文件名的路径会建出同名目录 |
| **深目录递归删除可能压垮客户端** | `DeleteDirectory` 用无界 `wsprintf` 拼 `MAX_PATH` 栈缓冲(`:643/653/657`);`SearchFiles` 已在 8f718d9 加长度预判,删除/`FixedUploadList` 尚未 | 服务端拒绝超过 MAX_PATH 的 `recursive` 目标;彻底修复归 P12 |
| 路径不存在时**不会**快速失败 | 客户端不回报 win32 码 | 需要客户端补 `TOKEN_FILE_OP_ERROR`(见 §5.7 与 §6 的 P12 批次) |
### 2.5 安全门
新增单一开关 **`McpFileWrite`**(默认 `0`),要求 `McpReadonly=0` 同时成立:
- 不复用 `McpFileTransfer`:上传是「覆盖」,删除是「毁灭」,风险等级不同,必须能分别关。
- 三个工具全部登记 `readOnlyHint=false, destructiveHint=true`(`delete_path`)/ `false`(`move_path`、`create_folder`)。
- 审计:沿用 `AuditManageAction`,记录 `path=` 与 `recursive=`,**不记录文件内容**。
- 建议追加服务端侧保护:拒绝 `path` 落在系统关键目录(`C:\Windows`、`C:\Windows\System32`、`C:\Program Files`)下的 `delete_path`,除非另开 `McpFileWriteDangerous`。这一条可在实现时按需取舍,但**至少要把 `C:\Windows` 与盘根目录挡住**(`delete_path` 传 `C:\` + `recursive=true` 是灾难级误操作)。
---
## 3. 新工具(P10-C):远程控制补全 + 工具族去重
### 3.1 `remote_block_input`(P10-C,零客户端改动)
| 项 | 内容 |
|---|---|
| 入参 | `id`、`session_id`、`block`(`true` / `false`) |
| 命令 | 屏幕子连接上 `[COMMAND_SCREEN_BLOCK_INPUT][0\|1]`(2 字节,`client/ScreenManager.cpp:1198`) |
| 门控 | 随 `remote_open`(`McpRemoteControl=1` + `McpReadonly=0`),不单独设开关 |
**价值**:AI 做 GUI 自动化时,真人碰一下鼠标就会把流程打断;锁定对端键鼠是标准做法。
**必须做的两件事**(否则会把人锁在电脑外):
1. `remote_close` 与 idle 回收时**强制补发 `block=false`**;
2. 会话内 `block=true` 超过 `max_block_ms`(建议默认 300s)自动解锁并在结果里标注 `auto_unblocked=true`。
`BlockInput` 在进程退出时会自动解除,所以真正的死锁风险只出现在「客户端进程活着但会话丢了」——上面两条正好覆盖。
### 3.2 工具族重叠:`list_*` vs `host_list_*`(P10-A,纯文档/描述改动)
**这是当前最容易被忽略、但对模型影响最大的问题**。同一件事有两套工具,走两条完全不同的链路,门控也不同:
| 能力 | 设备管理族(P2/P7) | 主机管理族(P8) | 差异 |
|---|---|---|---|
| 进程列表 | `list_processes`(`COMMAND_SYSTEM`→`CSystemManager`) | `host_list_processes`(`COMMAND_MACHINE_PROCESS`→`MachineManager`) | 后者字段更全(优先级、线程数、用户、工作集、文件大小),**且已有 `name`/`pid` 服务端过滤**(`McpMachine.cpp:2733-2741`) |
| 窗口列表 | `list_windows`(`COMMAND_WSLIST`) | `host_list_windows`(`COMMAND_MACHINE_WINDOWS`) | 同上,后者也带过滤 |
| 服务列表 | `list_services`(`COMMAND_SERVICES`→`ServicesManager`) | `host_list_win32_services`(`COMMAND_MACHINE_WIN32SERVICE`) | 后者含描述、登录身份 |
| 窗口控制 | `operate_window`(含 `close`) | `host_control_window`(**无** `close`) | 门控不同 |
门控差异是关键:`host_list_*` 需要 `McpMachine=1`,而 `list_*` 只需 `McpReadonly`。所以:
- `McpMachine=0` 时 `host_list_*` **不出现在 `tools/list`**,模型只能用 `list_*`;
- `McpMachine=1` 时两套都在,模型**没有任何依据**判断该用哪个。
**结论比初稿更强:`host_list_*` 是首选而非平级备选**——字段更全、且过滤能力本来就已存在(`list_*`
要等 §5.3 补完过滤才追平)。`list_*` 的定位是「`McpMachine=0` 时的降级路径」。
**做法**(不需要合并工具,只改描述,风险极低):
1. 在两套工具的 `description` 里互相指路,且措辞要给出明确优先级:
- `list_processes` → 「`McpMachine=0` 时的降级路径,字段较少;若 `host_list_processes` 在 `tools/list` 里,一律优先用它」;
- `host_list_processes` → 「首选;与 `list_processes` 同源但字段更全并支持服务端过滤,仅在不可用时退回」。
2. 在 `initialize.instructions`(§5.8)里写一条选型规则,一次性讲清四组关系。
**不建议合并**:两族走不同子连接、不同能力位、不同门控,合并会破坏既有安全模型(`McpMachine` 开关的意义就是「单独关掉一套」)。
---
## 4. 大能力(需独立立项,不建议并入本轮)
### 4.1 分级原则
下面这些能力「能做」但**不适合和文件写工具混在一个批次**:要么工程量大(代理、摄像头),要么安全边界必须单独评审(升级、执行、卸载)。按建议顺序列出。
| 能力 | 客户端改动 | 工程量 | 风险 | 建议 |
|---|---|---|---|---|
| 注册表写(set/delete value) | **需要**(无现成命令) | 中 | 高(可持久化篡改) | P12,独立开关 + 白名单键路径 |
| Windows 事件日志读取 | **需要** | 中 | 低(只读) | P12,优先于注册表写 |
| 进程模块 / 启动项 / 网络共享 | **需要** | 中 | 低(只读) | P12,补「主机取证」维度 |
| 剪贴板只读 | **需要**(客户端只有写) | 小 | 中(读即泄密) | 维持 `Mcp_Design.md §10.7` 的「不做」结论 |
| 窗口级一次性截图 | 需评估 | 中 | 低 | 见 §4.2 |
| 代理隧道 `proxy_*` | 否(`COMMAND_PROXY` 已有) | **大** | 高 | 见 §4.3 |
| 客户端升级 `upgrade_client` | 否(`COMMAND_UPDATE` 已有) | 中 | 高 | 见 §4.4 |
| 上传执行 `upload_exec` | 否(已有) | 小 | **极高** | 默认不做,或仅 `McpMachineDangerous` 下 |
| 摄像头快照 / 语音采集 | 否(已有流) | 大 | 中 | 后置 |
| 写 hosts 文件 | 否(已有) | 小 | 高 | 见 §4.5 |
### 4.2 窗口级截图
`COMMAND_SCREEN_WINDOW`(`client/ScreenManager.cpp:894`)接的是**屏幕流**(按窗口标题捕获,空串恢复全屏),不是一次性 JPEG。要做 `get_screenshot(window_title=...)` 需要服务端在屏幕子连接上收若干帧再截一张,本质上是「起一个临时屏幕会话」——比现有 `get_screenshot`(主连接一次 RPC)重得多。
**建议**:先做「AI 侧的替代方案」——`remote_open` 已能拿全屏,`list_windows` 能给窗口句柄与标题,模型可以据此用 `remote_mouse` 点击。等 `remote_*` 在真实任务里被证明「全屏截图不够用」再投入。
### 4.3 代理隧道(价值最高的「新维度」)
`COMMAND_PROXY`(`client/KernelManager.cpp:1039` + `client/proxy/ProxyManager.cpp`)能把客户端当 SOCKS/端口转发跳板。MCP 化的形态是:
```
proxy_open(id, target_host, target_port, local_port) → 服务端本地监听
→ AI 用普通 HTTP/DB 客户端访问 127.0.0.1:local_port
→ 流量经客户端转发到内网 target
proxy_close(session_id)
```
**这会让 AI 从「操作主机」升级为「进入主机所在内网」**——价值远高于再加几个只读工具。
但代价是:服务端要起本地监听(防火墙/端口冲突/生命周期管理)、要做并发与超时、审计粒度要细到「连接目标」,而且这是一个**新的攻击面**(本机任意进程都能用这个监听)。建议单独立项,先出安全设计再动手。
### 4.4 客户端升级 / 上传执行
- `upgrade_client`:`COMMAND_UPDATE` 链路完整,但升级失败会让主机**永久失联**,且没有回滚。至少要「先校验包完整性 + 保留旧版本 + 升级后 N 分钟无心跳则告警」。
- `upload_exec` / `download_exec`:等价于任意代码执行,**绕过 `exec_command` 的全部白名单约束**。这与现有安全模型(`McpCmdWhitelist` 逐条加白)根本冲突。**建议维持不做**;确有需要时只允许 `McpMachineDangerous` 下、且必须显式传 `confirm=true`。
### 4.5 写 hosts 文件
`COMMAND_HOSTS_SET`(`client/MachineManager.cpp:318`)用 `CREATE_ALWAYS` **整文件覆盖**,且无回包、失败静默。MCP 化必须是「读-改-写」语义:
- 入参只接受 `entries[]` 追加/删除,服务端先 `host_get_hosts_file` 读全文,服务端合并,再整文件下发;
- 必须备份原文件(服务端存一份到 `%TEMP%`);
- 门控 `McpMachineDangerous` + `McpReadonly=0`。
**建议**:本轮不做。误覆盖 hosts 会导致目标机 DNS 全断,恢复成本高。
---
## 5. 现有工具优化
按「影响面 ÷ 成本」排序。P0 = 建议本轮做,P1 = 下一轮,P2 = 择机。
> 另有一项「两套工具族重叠」的优化放在 §3.2(因为要顺带说明它为什么不合并),同样是 P0。
### 5.1 【P0】`get_host_detail` 增加 `capabilities`
**问题**:模型拿到 `clientType=WIN` 就以为所有工具都能用,于是反复撞 `-32005`:
| 工具 | 隐藏门槛 | 报错位置 |
|---|---|---|
| `get_screenshot` | `CLIENT_CAP_SCREEN_PREVIEW` 能力位 | `McpServer.cpp:2328` |
| `remote_*` | 同上 + 单显示器(多屏现在报 `-32005`,不是 `-32008`) | `McpServer.cpp:3715` 附近 |
| `list_registry` | 非 LNX/MAC | `McpServer.cpp:2569` |
| `upload_file` | 客户端 `SupportsFileV2()` | `McpServer.cpp:4972` |
| `get_keylog` | `McpKeylog=1` | 门控 |
| `host_list_*` | `McpMachine=1` | 门控 |
**做法**:在 `AppendHostTechnicalDetail`(`McpServer.cpp:2018`)末尾追加。只写**主机自身**的能力,
服务端开关不重复——`get_server_status` 的 `switches` 已经完整暴露(`McpServer.cpp:3142`),
`monitors` 也已经有了(`:2048-2053`):
```cpp
Json::Value caps(Json::objectValue);
caps["platform"] = clientType; // WIN / LNX / MAC / APK
caps["screenPreview"] = ctx->SupportsScreenPreview();
caps["remoteControl"] = ctx->SupportsScreenPreview() && monitors == 1;
caps["fileTransferV2"] = ctx->SupportsFileV2();
caps["c2cPaths"] = ctx->SupportsC2CPaths();
caps["registry"] = (clientType != "LNX" && clientType != "MAC" && clientType != "APK");
host["capabilities"] = caps;
```
**收益**:模型在规划阶段就能排除不可用工具,把「试错 → 报错 → 换工具」的三轮往返压缩成一次。
**成本**:约 30 行,零客户端改动,`outputSchema` 加一个对象。
### 5.2 【P0】`get_keylog`:补离线开关与真实状态(**已重写,初稿前提有误**)
> **初稿的错误**:原文断言「现在只能采 1–15 秒窗口,对『昨天谁敲了什么』完全无用,需要新增 `mode=offline`」。
> 这是错的。`CKeyboardManager1` 构造时就 `new CircularBuffer(m_strRecordFile)`,而 `CircularBuffer`
> 的构造函数直接 `LoadDataFromFile()`(`client/KeyboardManager.h:31-38`);`SendData` 每次(重)连上后
> 从 `pos=0` 把整个缓冲区推给服务端(`client/KeyboardManager.cpp:504-516`),缓冲区 10 MB
> (`KeyboardManager.h:15`)。**只要目标机 `kbrecord=Yes`,现有的 `get_keylog` 已经把落盘历史
> (含无人在线的时段)一并返回了**——工具描述自己就写着「先把缓冲区里已有的记录(含历史)推给服务端」
> (`McpServer.cpp:1559`)。所以 `mode=offline` 不用做,做了也是重复实现。
**真正缺的两件事**:
1. **开关**:`COMMAND_KEYBOARD_OFFLINE`(2 字节)与 `COMMAND_KEYBOARD_CLEAR`(1 字节)
已实现于 `client/KeyboardManager.cpp:125` / `:131`,就在 `get_keylog` 已经建立的那条
键盘子连接上,MCP 侧从未下发过。
2. **状态自述**:客户端在就绪包 `TOKEN_KEYBOARD_START` 的 `byte[1]` 里已经带了「离线记录是否开启」
(`client/KeyboardManager.cpp:164`),服务端 `get_keylog` 拿到了这个包却没解析。
模型因此不知道「我看到的这些历史是不是全量」。
**做法**:
| 参数 | 语义 |
|---|---|
| `offlineRecord`(**输出**) | 客户端当前是否开着离线常驻记录,取自 `TOKEN_KEYBOARD_START` 的 `byte[1]`;`false` 时历史只覆盖本进程启动后的在线时段 |
| `set_offline`(输入,`true`/`false`) | 下发 `COMMAND_KEYBOARD_OFFLINE` 改变常驻状态。写操作:需 `McpReadonly=0` |
| `clear`(输入,`true`) | 下发 `COMMAND_KEYBOARD_CLEAR` 清空客户端缓冲区与落盘文件。破坏性:需 `McpReadonly=0`,且应排在采集之前 |
两个写动作都必须**先于采集窗口下发**,且失败要如实返回(`Send2Client` 的返回值要检查)。
### 5.3 【P0】`list_processes` / `list_windows` 增加服务端过滤
**问题**:`BuildPagedHostListInputSchema` 只有 `{id, limit, offset}`(`McpServer.cpp:776`,调用点在 `:1477` 等)。一台正常 Windows 有 200–400 个进程、几十个窗口,模型要翻 3–4 页才能找到目标;每页都是完整字段,上下文开销很大。
**做法**:加可选 `name`(进程名/窗口标题子串,ASCII 不区分大小写)与 `pid`,在服务端分页**之前**过滤,`total` 为命中数、`totalAll` 为总数。口径照抄 `BuildSearchHosts`(`McpServer.cpp:1878-1887`):
```cpp
ApplyPageWindow(matched, page, pageItems);
if (filtered) page.totalAll = (int)all.size(); // 过滤前总数
```
**收益**:`list_processes(name="chrome")` 从 3 页变 1 条;两套工具族的能力也对齐了(`host_list_*` 本来就有这两个参数)。
### 5.4 【P1】`power_action` 增加结果验证
**问题**:`power_action` 是「发完即走、无响应」(`McpServer.cpp:5812` 附近注释),返回 `ok:true` 只代表**命令写进了 socket**。模型会误以为「已重启」,紧接着调 `list_processes` 却拿到旧进程列表。
**做法**:加 `wait`(默认 `false`)与 `wait_ms`(默认 60000):
- `wait=true`:轮询主连接是否断开 → 再轮询是否重新上线,返回 `{sent:true, went_offline:true, came_back:true, elapsed_ms}`;
- 超时不算失败,返回 `came_back:false` 让模型自己决定。
### 5.5 【P1】破坏性工具统一 `dry_run`
`kill_network_connection` 有 `dry_run`(实测报告「观察项」明确肯定了这个设计),但 `kill_process`、`operate_window(close)`、`host_control_*` 都没有。建议统一:`dry_run=true` 时只做「目标存在性校验 + 返回将被影响的对象」,不执行。
对 AI 尤其重要:模型可以在执行前把「我要杀这 3 个进程」摆给用户看。
### 5.6 【P2,收益被初稿高估】错误码:`-32008` 其实只有两种语义
> **初稿的错误**:原文说 `-32008` 一码四义(含「老客户端格式」「多显示器不支持」)。核对后全文件只有两处
> `-32008`:`exec_command` 的 shell 元字符(`McpServer.cpp:2901`)与 `terminal_exec` 的 `&`/`|`/换行
> (`McpServer.cpp:3465`)——**两者都是「改参数可修」**。多显示器早就改成 `-32005` 了,代码注释明说
> 「这是能力限制、改参数也修不好」(`McpServer.cpp:3715`)。能力类错误已经统一走 `-32005`。
因此拆分只剩一个干净的诉求:把「参数非法」从 `-32008` 换成 MCP 语义更准确的 `-32012`。
| 新码 | 语义 | 模型动作 |
|---|---|---|
| `-32012` | Validation rejected(参数非法,改参数可修) | 修参数重试 |
`-32008` 保留为历史别名(不破坏既有客户端与已发布的文档)。这是一次纯常量替换,收益是让模型
不必读英文 message 就能区分「改参数」与「换主机」,但**优先级低于 P0 各项**。
### 5.7 【P1】写工具的 ack 语义显式化
现状:`delete_path` / `move_path` / `create_folder` / `kill_process` / `operate_window` / `control_service` 的 ack 都是**客户端无条件回包**,不代表操作成功。
两条路,建议都做:
1. **文档层**:`outputSchema` 里加 `verified: bool`(可为 `null`)与 `verify_hint: string`("call list_files on the parent directory to confirm");
2. **实现层**(低成本高收益):`delete_path` / `move_path` 在收到 ack 后,**在同一个子连接上**再补一次 `COMMAND_LIST_FILES` 校验父目录,把 `verified` 填成真实结果。注意不是"多开一次子连接":子连接还开着,客户端收到 finish 后就在等下一条命令,所以代价只是同一连接上的一次往返(约 50–150ms)。实现要点是重新登记一个 `list_files` 挂起(`BeginPending(devId, "list_files", path)`,`McpServer.cpp:7795` 已有该重载),再直接 `Send2Client`;`TOKEN_FILE_LIST` 的现有 case 会在投递结果后 `CancelIO` 收尾,正好完成清场。校验本身失败(超时/连接断)时 `verified` 返回 `null`,**不要谎报 false**。
彻底的做法是客户端补 `TOKEN_FILE_OP_ERROR`(带 win32 码),归入 §4.1 的 P12 批次。
### 5.8 【P1】`initialize` 返回 `instructions`
**问题**:模型对这套服务端的「隐性知识」全靠工具描述拼凑:主机 id 是 64 位雪花值(不能猜)、要先 `list_online_hosts` 再操作、`-32003` 是单设备单飞行、`-32006` 不要重试、远程控制要先 `remote_open` 拿 `session_id`。`Mcp_Design.md` 把这些写在文档里,但**模型看不到文档**。
**做法**:`initialize` 响应里加 `instructions`(纯文本,建议 600–900 字),内容:
1. 主机 id 的获取方式与形态(禁止猜测);
2. 工具族与开关关系(哪些工具可能不在 `tools/list` 里,为什么);
3. 错误码 → 动作的对照(只列 6 个高频码);
4. 典型任务编排(文件整理、进程排查、GUI 自动化各一段);
5. 「同一主机同时只能有一个远程请求」的约束。
**收益**:这是**单点投入、全局收益**的改动——所有客户端的每一次会话都受益,且零风险。优先级应当排在所有新工具之前。
### 5.9 【P2】`notifications/progress` 与 `notifications/cancelled`
**问题**:
- `download_file` 默认超时 600s、`upload_file` / `copy_files_c2c` 同类、`search_file` 最长 120s、`chat_wait` 最长 55s。这段时间里客户端**收不到任何信号**,模型和用户都以为卡死。
- 客户端取消请求(用户按 Esc / 关闭会话)时,服务端**不会中止**正在进行的传输,主机会被锁到超时为止(实测报告 P2 的 600 秒锁定就是这类后果)。
**做法**:
- 长任务在 `tools/call` 的 `_meta.progressToken` 存在时,按 1–2 秒节流推送 `notifications/progress`(`progress` = 已传字节 / 总字节);
- 维护「进行中的请求 → 会话」映射,收到 `notifications/cancelled` 时走既有的清理路径(清 pending、关子连接、删半成品文件)。
这两项都在 `McpServer.cpp` 的 HTTP 处理器层,**不动任何工具实现**。
### 5.10 【P2】会话可观测与自救
`-32003 Device busy` 现在是死路:模型不知道是谁占着这台主机、也不知道等多久。建议加两个纯服务端工具:
| 工具 | 作用 |
|---|---|
| `mcp_list_sessions` | 列出所有在飞会话:`{host_id, tool, session_id, started_at, idle_ms, kind}` |
| `mcp_cancel_session` | 按 `session_id` 强制中止(等价于 `notifications/cancelled` 的内部路径) |
`-32003` 的 message 里带上「当前占用者与已持续时间」,模型就能自己决定「等」还是「取消」。
### 5.11 【P2】`tools/list` 体积
54 个工具、每个都带完整中文描述 + 双 schema。实测**工具描述与属性说明文本合计约 23 KB**(54 条 `description` + 158 条 schema 属性说明),叠加 JSON 结构与 schema 骨架后,`tools/list` 响应实际在 **45–60 KB** 量级。
对 200K 上下文的模型不算致命,但对小上下文客户端(8K–32K)会挤占绝大部分预算,且**每轮对话都要重传**(多数客户端不缓存)。
三个可选做法(不建议同时上):
1. **精简描述**(推荐):把「实现细节、限制、已知问题」从 `description` 移到 `instructions` 或工具文档,`description` 只保留「做什么 + 关键约束」一两句。可省 30–40%。
2. **工具族合并**:`host_list_processes` … `host_get_hosts_file` 这 10 个合并为 `host_list(tab, id, limit, offset)`。省 9 个工具、约 20% 体积,代价是 `annotations` 与 `outputSchema` 变粗(10 个 tab 的条目结构不同),**discoverability 也会下降**——模型看到 `tab` 枚举才知道有哪些能力。**不建议**。
3. **可配置 profile**:`McpToolProfile=full|compact`,compact 只出 `name + 一句话 + 必填参数`。适合小模型客户端,但要维护两套描述。
### 5.12 【P2】`control_service` 的逐项 `Sleep(500)`
`client/ServicesManager.cpp:213` 的 `ServicesConfig` 对每一项 `Sleep(500)` 后再回列表。批量控制 10 个服务 = 至少 5 秒。服务端可以在 `action` 里支持 `items[]` 批量下发(一次子连接、一个 payload),把 N 次往返压成 1 次。**前提是确认客户端能解析多条目 payload**——按现有实现它只处理单条,需要客户端改动,因此列为 P2。
### 5.13 【P0,顺手修】`kToolHints` 表头注释过期
`McpInternal.cpp:367` 注释写「53 个工具的语义登记表」,实际数组 **54 项**。一行修复。
### 5.14 其他小项
| 项 | 位置 | 说明 |
|---|---|---|
| `list_windows` 无 `pid` 过滤 | `McpServer.cpp:2201` | 见 §5.3 |
| `search_file` 无深度/大小上限参数 | `McpServer.cpp:8050` | 客户端固定深度 32 / 10000 条,服务端可加 `max_depth` 但需客户端支持;暂不做 |
| `search_file` 的描述仍写着「会栈溢出」 | `McpServer.cpp:1850` | 客户端侧已于 8f718d9 修复,描述与 `tools/mcp_smoke.ps1` 的注释都过期,应一并更正 |
| `get_screenshot` 无区域裁剪 | `McpServer.cpp:2085` | 有 `max_width`;ROI 需客户端改动,收益有限,不做 |
| 审计不含调用参数 | `Mcp_Design.md §10.8` | 有意设计(防泄漏),维持 |
| `chat_wait` 会取走 inbox | `McpInternal.cpp:431` | 已正确标注非幂等,无需改 |
---
## 6. 批次与验收建议
| 批次 | 内容 | 客户端改动 | 预估规模 | 验收方式 |
|---|---|---|---|---|
| **P10-A(优化,先做)** | `instructions`、`capabilities`、`list_*` 过滤、`get_keylog` 离线开关与状态、工具族互指、`kToolHints` 注释、`search_file` 过期描述 | 无 | 服务端 ~450 行 | 冒烟断言 `instructions` 非空;`capabilities` 与平台一致;`list_processes(name=...)` 命中数 < 全量且 `totalAll` 正确;`get_keylog.offlineRecord` 与实际 `kbrecord` 一致 |
| **P10-B** | `delete_path` / `move_path` / `create_folder` + `McpFileWrite` 开关 + 系统目录保护 + §2.3 的三处接线 + `verified` 复核 | 无 | ~700 行 | 冒烟新增:建目录→传文件→改名→删除→删目录→越界拒绝;中文路径 + 超长路径各一条;超时后确认**不弹**文件管理器窗口 |
| **P10-C** | `remote_block_input`(含强制解锁与超时自动解锁) | 无 | ~200 行 | 会话内 block→截图对比→unblock;`remote_close` 后确认已解锁 |
| **P11(已完成 2026-10-28,见附录 D)** | `power_action` 验证、`dry_run` 统一、`-32012`、progress/cancelled、`mcp_list_sessions` | 无 | ~700 行 | 长任务 progress 回调计数 > 0;取消后主机 1s 内释放(`get_server_status` 可查) |
| **P12** | 注册表写、事件日志、进程模块/启动项、`TOKEN_FILE_OP_ERROR`、`DeleteDirectory` 的路径长度防御 | **需要** | 客户端 + 服务端 | 单独设计文档 |
| **独立立项** | 代理隧道、客户端升级、摄像头/语音 | 视方案 | 大 | 单独安全评审 |
**建议顺序**:P10-A → P10-B → P10-C → P11,**每批独立提交**。
理由:P10-A 全是**几十行代码换全局体验**的改动(能力自述 + 使用说明 + 描述互指),先落地能立刻降低后续所有工具的试错率,且几乎不引入回归风险;P10-B 是最大的功能缺口,但涉及删除语义,需要更充分的测试与开关灰度;P10-C 小而独立,可随时插入。
---
## 7. 明确不做(本轮)
| 项 | 理由 |
|---|---|
| 剪贴板只读 | 常含口令/令牌/私钥,「读即泄密」,且客户端无只读链路(维持 `Mcp_Design.md §10.7`) |
| 上传执行 / 下载执行 | 等价任意代码执行,与 `McpCmdWhitelist` 逐条加白的安全模型冲突 |
| 写 hosts 文件 | `CREATE_ALWAYS` 整文件覆盖 + 无回包,误操作导致目标机 DNS 全断 |
| 卸载软件 | `WinExec` 卸载串,无回包、可能弹 UAC 阻塞,无法确认结果 |
| 清除事件日志 / 隐藏开网页 / 卸载后门 | 当前 Windows 客户端**未实现**这些命令(死命令) |
| `Ctrl+Alt+Del` / 黑屏 | 客户端未实现,需客户端改动 |
| 10 个 `host_list_*` 合并为 1 个 | 体积收益 20%,discoverability 损失更大(见 §5.11) |
---
## 附录 A:本轮核对过的客户端命令清单
Windows 客户端**已实现**、可作为新工具基础、MCP 尚未使用:
```
COMMAND_DELETE_FILE → TOKEN_DELETE_FINISH client/file/FileManager.cpp:97
COMMAND_DELETE_DIRECTORY → TOKEN_DELETE_FINISH client/file/FileManager.cpp:106
COMMAND_CREATE_FOLDER → TOKEN_CREATEFOLDER_FINISH client/file/FileManager.cpp:116
COMMAND_RENAME_FILE → TOKEN_RENAME_FINISH client/file/FileManager.cpp:119
COMMAND_HOSTS_SET → (无回包, 整文件覆盖) client/MachineManager.cpp:318
COMMAND_APPUNINSTALL → (无回包, WinExec) client/MachineManager.cpp:160
COMMAND_SCREEN_BLOCK_INPUT → (无回包, 2 字节) client/ScreenManager.cpp:1198
COMMAND_KEYBOARD_OFFLINE → (无回包, 2 字节) client/KeyboardManager.cpp:125
COMMAND_KEYBOARD_CLEAR → (无回包, 1 字节) client/KeyboardManager.cpp:131
COMMAND_UPDATE → 升级链路 client/KernelManager.cpp:1466
COMMAND_UPLOAD_EXEC → 执行上传文件 client/KernelManager.cpp:880
COMMAND_PROXY → 端口转发 client/KernelManager.cpp:1039
COMMAND_SCREEN_WINDOW / _ROI → 流式窗口/区域捕获 client/ScreenManager.cpp:894 / :886
COMMAND_WEBCAM / COMMAND_AUDIO→ 流式音视频 client/KernelManager.cpp:1399 / :1414
```
> 已排除 `COMMAND_PROCESS_FREEZING` / `COMMAND_PROCESS_THAW`——它们**已被 `host_control_process` 使用**
> (`McpMachine.cpp:2107`),不属于缺口。
**定义了但 Windows 客户端未实现**(不可用):`COMMAND_CLEAN_EVENT`、`COMMAND_OPEN_URL_HIDE`、`COMMAND_OPEN_URL_SHOW`、`COMMAND_REMOVE`、`COMMAND_SCREEN_CTRL_ALT_DEL`、`COMMAND_SCREEN_BLANK`。
---
## 附录 B:本轮核对过的关键代码位置
| 主题 | 位置 |
|---|---|
| 工具注解登记表(54 项) | `server/2015Remote/McpInternal.cpp:368` |
| `tools/list` 构造 | `server/2015Remote/McpServer.cpp:1408` |
| `initialize` 结果构造 / HTTP 方法分派 | `McpServer.cpp:46` `BuildInitializeResult` / `:7622` 起 |
| 主机技术字段补全 | `server/2015Remote/McpServer.cpp:2018` `AppendHostTechnicalDetail` |
| 文件链路(列目录/搜索/下载) | `McpServer.cpp:2419` / `:8050` / `:6430` |
| 机器管理写工具范式 | `McpMachine.cpp:2531` `AddTool` / `:2127` `host_control_process` |
| `power_action`(发完即走) | `McpServer.cpp:5812` |
| `get_keylog`(固定窗口) | `McpServer.cpp:1558` / `:5985` |
| 配置键全集 | `2015RemoteDlg.cpp:2416` 起 + `McpSettingsDlg.cpp:227` / `:383` |
| 错误码表 | `docs/Mcp_Design.md §12` |
| 已修问题与实测 | `docs/Mcp_Test_Report_2026-10-25.md §0` |
---
## 附录 C:服务端接线点(P10-B 施工前必读)
MCP 子连接的分包路由有三层,新增一个「用子连接完成一次写操作」的工具时,**必须三处都改**,
少改任何一处都会出现「命令发不出去」「子连接泄漏」或「弹 MFC 窗口」:
| 层 | 位置 | 作用 | 不改的后果 |
|---|---|---|---|
| 1. 就绪包分流 | `McpServer::OnDriveList`(`McpServer.cpp:7832`) | 子连接建好后的第一个包(`TOKEN_DRIVE_LIST`)到达;按 `tool` 决定下发什么 | 沿用「空 path = 只列盘」判定 → 写命令永远发不出去,工具超时 |
| 2. 完成包投递 | `CMy2015RemoteDlg::MessageHandle`(`2015RemoteDlg.cpp:6003` 的 switch) | 三个 `TOKEN_*_FINISH` 目前无 case | 落到 `default:` 只打日志、不关子连接 → 子连接泄漏 + 工具等到超时 |
| 3. 迟到吸收 | `CMcpServer::MarkLateFirstPacketForTool`(`McpServer.cpp:7760`) | 工具放弃后吸收迟到的就绪包 | 目标机上**弹出 MCP 自己触发的文件管理器窗口** |
另一处相关:`NotifyProc`(`2015RemoteDlg.cpp:5581`)在 `ContextObject->hDlg` 非空时把包转给对话框,
MCP 路径的 `hDlg` 恒为 `NULL`,所以第 2 层一定会命中——这一点已核对,不是假设。
配置开关的接线也是三处:读取(`2015RemoteDlg.cpp:2416` 块)、对话框回填(`McpSettingsDlg.cpp:227`)、
落盘(`McpSettingsDlg.cpp:383`)。对话框是**纯代码构建**的(`McpSettingsDlg.cpp:128-186`),
插入一个 checkbox 需要重排其下所有控件的 y 坐标与窗口高度。
---
## 附录 D:P11 施工记录(2026-10-28)
零客户端改动,全部落在服务端(`McpServer.cpp` / `McpServer.h` / `McpMachine.cpp` /
`McpChat.cpp` / `McpInternal.{h,cpp}`)。
### D.1 `power_action` 的结果验证(§5.4)
- 新入参 `wait`(bool,默认 false)与 `wait_ms`(1000–600000,默认 60000),`wait_ms` 是
「等离线」与「等回线」**各自**的时限;`wait=false` 时也会校验 `wait_ms` 的取值范围。
- 输出从 `{ok}` 扩展为 `{ok, sent, went_offline, came_back, elapsed_ms}`:
`sent` 恒为 true(命令写进 socket),`went_offline` / `came_back` 由主连接的出现/消失判定
(`FindMainContext`,200ms 轮询),`elapsed_ms` 为整次调用的耗时。
- **超时不是错误**:`wait=true` 但没等到离线/回线时仍返回 `ok:true` 并在正文里写清「仍在
线」或「已离线但未回线」,让模型据此决定是否再等,而不是把「没等到」当成失败重试。
- `logout` 之后主机不会自动回线(需要人工登录),正文单独提示。
### D.2 破坏性工具统一 `dry_run`(§5.5)
| 工具 | `dry_run=true` 时的行为 |
|---|---|
| `kill_process` | 只取一次进程列表,回 `{ok, dry_run, targets:[{pid,name,path}], missing:[pid...]}`,**不下发终止命令**;一个都匹配不到返回 `-32009` |
| `operate_window` | 只取一次窗口列表,回 `{ok, dry_run, action, window}`;窗口不存在返回 `-32009` |
| `host_control_process` / `_window` / `_service` / `_task` | 只做目标存在性校验,回 `{ok, dry_run, action, target, state, detail}`(detail 是被影响对象的原始字段) |
实现要点:dry run 的挂起项以 `"<tool>/dryrun"` 登记,`OnSystemReady` 只认 `kill_process` /
`operate_window` 两个**精确**工具名,因此不会误发后续写命令;迟到首包仍按既有逻辑吸收。
### D.3 `-32012` 与 `-32008` 别名(§5.6)
- 两个真实站点(`exec_command` 的 shell 元字符、`terminal_exec` 的 `&`/`|`/换行)改为
`McpInternal::kErrValidation = -32012`;`kErrValidationOld = -32008` 保留为历史别名,不再新增使用。
- `initialize.instructions` 的错误码表与 `docs/Mcp_Design.md §12` 同步;`-32800` 一并登记。
### D.4 `notifications/progress` 与 `notifications/cancelled`(§5.9)
**传输**:本服务端原本每个 POST 只回一个 JSON。带 `params._meta.progressToken` 的 `tools/call`
改走 MCP Streamable HTTP 允许的 `text/event-stream`(同一个 POST):
1. 工具在独立线程执行,`McpCallContext` 经 FLS(Fiber Local Storage)暴露给工具实现
——**不能用 `thread_local`**:本工程有 shellcode/MemoryModule 手工映射出来的线程,没有
PE 的 TLS 初始化,加一个静态 `thread_local` 就会让服务端启动约 1s 后跳飞(实测);
2. 进度通知与最终响应都从这个 SSE 流写出(`McpProgressChannel`,背压队列上限 64 条,
满了丢最旧——进度是「最新值有意义」的信号);
3. 不带 token 的请求完全不变(一次性 JSON)。
**进度上报点**(`McpCallProgress`,内部 1s 节流):
| 工具 | 进度含义 |
|---|---|
| `download_file` | `filesDone / (totalFiles - directoryCount)`;总量未知时退回已收字节数 |
| `upload_file` | 已发数据字节 / 待发数据字节总数(在 worker 的分块回调里累加) |
| `copy_files_c2c` | 源端只在最后回一包结果,因此不报中间进度;取消/超时按既有路径收尾 |
| `search_file` | 命中数在客户端,服务端只在收尾时报一次结果(见下) |
| `chat_wait` | 等待期无中间量,取消即时生效 |
**取消**:三条入口共用一个取消位(`McpCallContext::cancelled`)
- `notifications/cancelled`(`params.requestId` 按 JSON-RPC id 精确匹配,字符串与数字不混用);
- `mcp_cancel_session`(按 request_id / host id / session_id);
- SSE 流写失败(客户端已断开)。
所有长等待都改成「≤500ms 一片 + 每片检查取消位」(`WaitWithCancel`),取消后直接落到各函数
**既有的超时/放弃分支**:`MarkLateFirstPacketForTool` 照登、子连接照关、挂起项照删。因此取消
不需要第二套清理逻辑,也满足「取消后主机 1s 内释放」。取消导致的失败结果由分发层统一改写成
`-32800`(已经拿到成功结果则照实返回)。
### D.5 `mcp_list_sessions` / `mcp_cancel_session`(§5.10)
- `mcp_list_sessions`:一次快照列出在飞 `tools/call`(含 JSON-RPC `request_id`)、挂起中的一次性
请求、终端、远程控制、文件传输、远程交谈;字段 `host_id/kind/tool/session_id/request_id/busy/
elapsed_ms/idle_ms`,可选 `kind` 过滤。纯本地,**不受功能开关与只读模式限制**。
- `mcp_cancel_session`:按 `request_id`(精确)或 `id`/`session_id`(条件)取消,返回
`{cancelled, released, waited_ms, matched}`;最多等 2s 让工具线程走完清理,`released` 说明
主机是否真的松开。
- `-32003` 的文案统一追加占用者:`Device busy: another request is pending for this host
(tool=download_file, elapsed=12s)`。`DescribeBusy` 会排除发起本次错误的那个调用自身。
### D.6 已知边界
- SSE 请求会占住 httplib 的一个 worker 线程直到工具结束(线程池 32);单机管理场景足够,
不作为多租户端点使用。
- `search_file` 被取消时返回**已收到的部分结果**(`finished=false`),不是 `-32800`:搜索是只读
累积操作,部分结果对调用方更有用;它同样在 ≤1s 内释放主机。
- `mcp_cancel_session` 找不到匹配项时返回 `cancelled:0`(不是错误)——请求可能已经结束,
或 `request_id` 的 JSON 类型与调用时不一致。
+6 -6
View File
@@ -153,8 +153,8 @@ FindMainContext → -32002 主机不存在/离线
clientType==LNX/MAC → -32005 仅 Windows
command 为空 → -32602
mcp.IsReadonly() → -32006 只读模式默认开,需 McpReadonly=0
含 &|<>^ 五元字符 → -32008 防注入绕过白名单
含控制字符(\r\n 等 <0x20) → -32008 防换行拆分绕过白名单
含 &|<>^ 五元字符 → -32012 防注入绕过白名单(-32008 为历史别名)
含控制字符(\r\n 等 <0x20) → -32012 防换行拆分绕过白名单
白名单前缀校验 → -32007 不在白名单
```
@@ -237,7 +237,7 @@ SweepIdleTerminals(300)
ResolveTerminalSessionHost
session_id 为空 → -32602
command 为空 → -32602
command 含 & 或 | → -32008(正确性门,见 §4.6)
command 含 & 或 | → -32012(正确性门,见 §4.6)
nonce = 随机 8 hex
BeginTermCommand(devId, sessionId, command, nonce, subCtx, isPty)
→ false 则 -32002(不存在/不匹配/未就绪/忙碌/已关)
@@ -273,7 +273,7 @@ CloseTermSession(devId, sessionId)
### 4.6 正确性门 `&|`(非安全门)
`terminal_exec` **拒绝含 `&` 或 `|` 的命令**(`find_first_of("&|")`,含 `&&`/`||`/`|`),报 `-32008`。原因:哨兵包装 `cmd 2>&1 && echo ... || echo ...` 假定命令是「扁平」的,命令内含 `&`/`|` 会与包装的控制操作符合流、导致退出码失真/输出归属不清。
`terminal_exec` **拒绝含 `&` 或 `|` 的命令**(`find_first_of("&|")`,含 `&&`/`||`/`|`),报 `-32012`(历史别名 `-32008`)。原因:哨兵包装 `cmd 2>&1 && echo ... || echo ...` 假定命令是「扁平」的,命令内含 `&`/`|` 会与包装的控制操作符合流、导致退出码失真/输出归属不清。
- 这是**正确性限制,不是白名单**——持久终端本就不设白名单。
- 同样拒绝 `<0x20` 的控制字符(`\r`/`\n`):换行会把命令拆成多行、只有末行被哨兵包装,导致退出码与输出归属失真。
@@ -415,7 +415,7 @@ McpServer().SetTerminalEnabled(THIS_CFG.GetInt("settings", "McpTerminal", 0) !=
| `-32005` | 非 Windows | LNX/MAC 客户端 |
| `-32006` | 已禁用/只读 | `IsReadonly()` 或 `!IsTerminalEnabled()` |
| `-32007` | 白名单拒绝 | `IsCommandAllowed` false |
| `-32008` | 含禁用字符 | `exec_command` 的 `&|<>^`;`terminal_exec` 的 `&|` |
| `-32012` | 含禁用字符 | `exec_command` 的 `&|<>^`;`terminal_exec` 的 `&|`(早期版本用 `-32008`,同一语义) |
| `-32602` | 参数非法 | `ParseHostIdArg` 失败、缺 required 参数 |
| `-32700` | JSON 解析错误 | 请求体非合法 JSON-RPC |
@@ -446,7 +446,7 @@ McpServer().SetTerminalEnabled(THIS_CFG.GetInt("settings", "McpTerminal", 0) !=
### 10.5 stdout 里出现命令本身 / 哨兵
- 命令本身回显 = ConPTY 输入回显,已由 `StripEchoedCommand` 服务端剔除(§2.4)。若仍出现,检查是否该行因编码(非 PTY 老管道的 GBK)与 `echoedLine` 字节不一致而 `find` 不到——老管道本应无回显。
- 哨兵 `__MCP_DONE_...` 出现 = 哨兵截断/清洗异常,通常意味着命令含 `&|` 破坏了控制操作符链(持久终端会提前 `-32008` 拒绝,一次性会 `-32008` 拒绝五元字符)。
- 哨兵 `__MCP_DONE_...` 出现 = 哨兵截断/清洗异常,通常意味着命令含 `&|` 破坏了控制操作符链(持久终端会提前 `-32012` 拒绝,一次性会 `-32012` 拒绝五元字符)。
### 10.6 中文/乱码
+15
View File
@@ -2421,6 +2421,8 @@ BOOL CMy2015RemoteDlg::OnInitDialog()
McpServer().SetRemoteControlEnabled(THIS_CFG.GetInt("settings", "McpRemoteControl", 0) != 0);
// 文件传输开关:默认关;仅 download_file 门控(不要求只读关)。
McpServer().SetFileTransferEnabled(THIS_CFG.GetInt("settings", "McpFileTransfer", 0) != 0);
// P10-B 文件写入开关:默认关;delete_path / move_path / create_folder 需要它且只读关。
McpServer().SetFileWriteEnabled(THIS_CFG.GetInt("settings", "McpFileWrite", 0) != 0);
// P7 管理控制开关:默认关;要求只读关(McpReadonly=0)才生效(工具列表/分派双重门控)。
McpServer().SetManageEnabled(THIS_CFG.GetInt("settings", "McpManage", 0) != 0);
// P8 主机管理 / 连接管理工具族:总开关默认关(关闭时 16 个工具都不可见)。
@@ -7029,6 +7031,19 @@ VOID CMy2015RemoteDlg::MessageHandle(CONTEXT_OBJECT* ContextObject)
ContextObject->CancelIO();
break;
}
case TOKEN_DELETE_FINISH: // 文件写操作完成回包【P10-B】
case TOKEN_RENAME_FINISH:
case TOKEN_CREATEFOLDER_FINISH: {
// 客户端对四个写命令都是「做完就无条件回包」,这些 token 正常只在 FileManagerDlg
// 的 hDlg 路径里消费;MCP 的文件管理器子连接 hDlg 为 NULL,包会落在这里。
// KeepSub = 已转入复核、在同一子连接上补发了 COMMAND_LIST_FILES,留给 TOKEN_FILE_LIST
// 分支投递数据并 CancelIO;其余(与本请求无关的迟到包 / 复核下发失败)关掉子连接。
uint64_t devId = ContextObject->GetClientID();
if (McpServer().TakeFileOpFinish(devId, ContextObject, szBuffer, len)
!= CMcpServer::FileOpAck::KeepSub)
ContextObject->CancelIO();
break;
}
case TOKEN_DOWNLOAD_ERROR: { // download_file 无可用文件(新客户端)【MCP 结构化失败】
// 客户端在「传输子链接还没建立」时就在文件管理器子连接上回报,故此处不 CancelIO:
// 该子链接由 ClearFileTransfer 统一收尾(避免与 tool 线程的 CancelIO 竞争)。
+16 -6
View File
@@ -77,11 +77,7 @@ std::string OptStr(const Json::Value& args, const char* key) {
return Trim(GetStringArg(args, key));
}
bool IsWindowsClient(context* ctx) {
if (!ctx) return false;
CString t = ctx->GetAdditionalData(RES_CLIENT_TYPE);
return !(t == "LNX" || t == "MAC" || t == "APK");
}
// IsWindowsClient 来自 McpInternal(与 McpMachine.cpp、McpServer.cpp 同一份实现)。
struct HostTool {
uint64_t dev = 0;
@@ -494,6 +490,10 @@ static std::string BuildChatWait(const Json::Value& id, const Json::Value& args,
case CMcpServer::ChatWaitResult::Busy:
return BuildError(id, kErrBusy,
"Another chat_wait is already pending for this session");
case CMcpServer::ChatWaitResult::Cancelled:
// 会话本身仍然有效;回 -32800 让调用方知道是自己取消了等待。
return BuildError(id, kErrCancelled,
"Waiting cancelled by client; the chat session is still open");
case CMcpServer::ChatWaitResult::Closed:
case CMcpServer::ChatWaitResult::Timeout:
case CMcpServer::ChatWaitResult::Ok:
@@ -871,10 +871,14 @@ CMcpServer::ChatReadyResult CMcpServer::WaitChatReady(uint64_t device_id,
if (s->closed) return ChatReadyResult::Closed;
if (s->started && now >= s->readyAt) return ChatReadyResult::Ok;
if (now >= deadline) return ChatReadyResult::Timeout;
if (McpCallCancelled()) return ChatReadyResult::Timeout; // P11:取消按超时收尾
// 绑定通知到达后只需等到 readyAt,不要一直睡到整个 open 超时。
steady_clock::time_point wake = deadline;
if (s->started && s->readyAt < wake) wake = s->readyAt;
// 500ms 上限:唤醒即可响应取消。
const steady_clock::time_point slice = now + std::chrono::milliseconds(500);
if (slice < wake) wake = slice;
m_ChatCv.wait_until(lk, wake);
}
}
@@ -927,7 +931,11 @@ CMcpServer::ChatWaitResult CMcpServer::WaitChatMessages(
while (s->inbox.empty() && !s->closed) {
if (timeoutMs <= 0 || steady_clock::now() >= deadline) break;
m_ChatCv.wait_until(lk, deadline);
if (McpCallCancelled()) break; // P11:≤500ms 内响应取消
// 500ms 一片:允许取消及时生效;无取消时与整段等待等价。
auto until = steady_clock::now() + std::chrono::milliseconds(500);
if (until > deadline) until = deadline;
m_ChatCv.wait_until(lk, until);
}
while (!s->inbox.empty() && out.size() < maxMessages) {
@@ -943,6 +951,8 @@ CMcpServer::ChatWaitResult CMcpServer::WaitChatMessages(
s->waitBusy = false;
if (!s->closed) s->lastActiveAt = time(nullptr);
// 取消优先于「等到超时」:没有消息且是被取消唤醒的,如实回报(会话本身不受影响)。
if (out.empty() && McpCallCancelled() && !closed) return ChatWaitResult::Cancelled;
return timedOut ? ChatWaitResult::Timeout : ChatWaitResult::Ok;
}
+21 -2
View File
@@ -173,6 +173,12 @@ context* FindMainContext(CMy2015RemoteDlg* parent, uint64_t id) {
return found;
}
bool IsWindowsClient(context* ctx) {
if (!ctx) return false;
CString t = ctx->GetAdditionalData(RES_CLIENT_TYPE);
return !(t == "LNX" || t == "MAC" || t == "APK");
}
size_t BoundedStrlen(const char* p, size_t avail) {
size_t n = 0;
while (n < avail && p[n]) ++n;
@@ -364,7 +370,8 @@ struct ToolHints {
bool openWorld; // false = 只读服务端本机状态(主机列表、审计日志),不触达外部主机
};
// 53 个工具的语义登记表。新增工具必须在此登记(漏登记 → 走默认 destructiveHint=true)。
// 工具的语义登记表(全部工具,含开关门控后才会出现的)。新增工具必须在此登记
// (漏登记 → 走默认 destructiveHint=true)。
const ToolHints kToolHints[] = {
// --- 服务端本机只读 ---
{ "list_online_hosts", true, false, true, false },
@@ -376,17 +383,27 @@ const ToolHints kToolHints[] = {
{ "get_activity_history", true, false, true, true },
{ "get_audit_log", true, false, true, false },
{ "get_server_status", true, false, true, false },
// P11:在飞会话的观测与取消。取消只改服务端自己的等待状态(被取消的请求立即走既有
// 清理路径),不改主机数据;按 request_id/session_id 取消天然幂等,故非破坏且幂等。
{ "mcp_list_sessions", true, false, true, false },
{ "mcp_cancel_session", false, 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_keylog 默认只读;clear / set_offline 两个入参会改客户端状态(clear 还会删掉
// 已落盘的记录),故按「可写、可破坏」登记。
{ "get_keylog", false, true, false, 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 },
// --- 文件系统写操作(McpFileWrite)---
{ "delete_path", false, true, false, true },
{ "move_path", false, true, false, true },
{ "create_folder", false, false, true, true }, // 已存在时同样成功
{ "list_network_connections", true, false, true, true },
{ "host_list_processes", true, false, true, true },
{ "host_list_windows", true, false, true, true },
@@ -409,6 +426,8 @@ const ToolHints kToolHints[] = {
{ "remote_keyboard", false, false, false, true },
{ "remote_mouse", false, false, false, true },
{ "remote_clipboard", false, false, false, true }, // 覆盖对端剪贴板
// 锁定对端键鼠:不破坏数据,但会把真人挡在电脑外,按「可破坏且非幂等」登记。
{ "remote_block_input", false, true, false, true },
// --- 文件传输 ---
{ "upload_file", false, true, false, true }, // 覆盖/新增远端文件
{ "copy_files_c2c", false, true, false, true }, // 覆盖/新增目标主机文件
+16
View File
@@ -20,6 +20,18 @@ class context;
namespace McpInternal {
// ===== 错误码(-32000 系列,见 docs/Mcp_Design.md §12)=====
//
// -32012 参数被校验拒绝:参数内容非法、按 message 改正后重试即可(shell 元字符、
// 控制字符之类)。-32008 是同一语义的历史别名:早期实现用它,已发布的文档与客户端
// 可能仍在匹配,故保留不改;新代码一律用 -32012。
const int kErrValidation = -32012;
const int kErrValidationOld = -32008; // 历史别名,勿新增使用
// -32800 请求被客户端取消:收到 notifications/cancelled 或 mcp_cancel_session 后,
// 在飞的工具提前退出(走各自的超时清理路径),结果统一以这个码回报。
const int kErrCancelled = -32800;
// Json::Value → 紧凑 JSON 字符串
std::string JsonToString(const Json::Value& v);
@@ -67,6 +79,10 @@ bool ParseHostIdArg(const Json::Value& args, uint64_t& out, std::string& err);
// 在 m_HostList 中按 clientID 找在线主 context(锁内遍历 m_cs)。
context* FindMainContext(CMy2015RemoteDlg* parent, uint64_t id);
// 客户端是否为 Windows 形态(EXE/DLL/MEXE/SC/MDLL);LNX / MAC / APK 返回 false。
// 用于「只有 Windows 客户端实现了这个能力」的判断(注册表、窗口、服务等)。
bool IsWindowsClient(context* ctx);
// 有界 strlen:p 最多可读 avail 字节,返回 n < avail 表示遇到 '\0'。
size_t BoundedStrlen(const char* p, size_t avail);
+85 -19
View File
@@ -113,13 +113,7 @@ std::string OptStr(const Json::Value& args, const char* key) {
return Trim(GetStringArg(args, key));
}
// Utf8ToCpExact / IsValidUtf8 由 McpInternal 提供(McpChat.cpp 共用)。
bool IsWindowsClient(context* ctx) {
if (!ctx) return false;
CString t = ctx->GetAdditionalData(RES_CLIENT_TYPE);
return !(t == "LNX" || t == "MAC" || t == "APK");
}
// Utf8ToCpExact / IsValidUtf8 / IsWindowsClient 由 McpInternal 提供(McpChat.cpp 共用)。
std::string EndpointAddr(const std::string& ep) {
size_t c = ep.rfind(':');
@@ -266,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;
@@ -309,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,
@@ -866,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;
@@ -1048,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);
}
}
@@ -1105,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);
}
}
@@ -2147,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;
@@ -2215,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;
@@ -2310,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")) {
@@ -2465,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,
@@ -2733,7 +2795,7 @@ void AppendTools(Json::Value& tools) {
props["name"] = PropStr(u8"按进程名子串过滤");
props["arch"] = PropStrEnum(u8"按架构过滤", { "x86", "x64" });
AddTool(tools, "host_list_processes",
u8"列出在线 Windows 主机的进程(主机管理「进程」标签页)。返回 PID、架构、窗口标题、路径、优先级、线程数、用户、工作集与文件大小。",
u8"列出在线 Windows 主机的进程(主机管理「进程」标签页)。返回 PID、架构、窗口标题、路径、优先级、线程数、用户、工作集与文件大小。首选:与 list_processes 同源但字段更全,并支持服务端过滤(pid / name / arch),仅在它没有出现在 tools/list 里(McpMachine=0)时退回 list_processes。",
ReadInputSchemaBatch(props), MakeListOutputSchema("processes", ProcessItemSchema()));
}
{
@@ -2741,7 +2803,7 @@ void AppendTools(Json::Value& tools) {
props["pid"] = PropInt(u8"按所属进程 PID 过滤");
props["title"] = PropStr(u8"按窗口标题子串过滤");
AddTool(tools, "host_list_windows",
u8"列出在线 Windows 主机上当前可见的顶层窗口(主机管理「窗口」标签页)。只包含可见窗口,故隐藏后窗口会从结果中消失。hwnd 可用于 host_control_window。",
u8"列出在线 Windows 主机上当前可见的顶层窗口(主机管理「窗口」标签页)。只包含可见窗口,故隐藏后窗口会从结果中消失。hwnd 可用于 host_control_window 或 operate_window。首选:支持服务端过滤(pid / title),仅在它没有出现在 tools/list 里(McpMachine=0)时退回 list_windows。",
ReadInputSchemaBatch(props), MakeListOutputSchema("windows", WindowItemSchema()));
}
{
@@ -2786,7 +2848,7 @@ void AppendTools(Json::Value& tools) {
props["status"] = PropStr(u8"按状态子串过滤,如 Running");
props["start_type"] = PropStr(u8"按启动类型子串过滤,如 Auto");
AddTool(tools, "host_list_win32_services",
u8"列出在线 Windows 主机的 Win32 服务(主机管理「服务」标签页之一)。返回显示名、描述、状态、启动类型、登录身份、服务名与可执行路径;服务名可用于 host_control_service。",
u8"列出在线 Windows 主机的 Win32 服务(主机管理「服务」标签页之一)。返回显示名、描述、状态、启动类型、登录身份、服务名与可执行路径;服务名可用于 host_control_service。首选:支持服务端过滤(name / status),仅在它没有出现在 tools/list 里(McpMachine=0)时退回 list_services。",
ReadInputSchemaBatch(props), MakeListOutputSchema("services", ServiceItemSchema()));
}
{
@@ -2843,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());
}
@@ -2860,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(最小化)。动作后重新枚举可见窗口复核:hide 后 hwnd 应消失,其余动作后仍应存在。不提供关闭窗口。",
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());
}
@@ -2871,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());
}
@@ -2882,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());
}
File diff suppressed because it is too large. Load diff
+159 -3
View File
@@ -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。
@@ -263,6 +312,28 @@ public:
// 屏幕子连接断开(OfflineProc 调用):擦除该子连接对应的会话 + 路由(幂等)。
void OnScreenControlClosed(context* subCtx);
// ===== P10-C:键鼠锁定(remote_block_input)=====
// 锁定状态记在会话上,报文由调用方在锁外发([COMMAND_SCREEN_BLOCK_INPUT][0|1])。
// 必须在 BeginScreenCtrlAction 之后调用(busy 期间会话不会被并发擦除,状态才有意义)。
// block=true 时以 maxBlockMs 为自动解锁期限。autoUnblocked 输出「上一次锁定是否因
// 超过 maxBlockMs 被服务端自动解除」(取走后清除),供工具结果标注。
// 返回 false = 会话已不存在(防御;正常不会发生)。
bool ScreenCtrlSetBlock(uint64_t device_id, const std::string& sessionId, bool block,
int maxBlockMs, bool& autoUnblocked);
// 该会话此刻是否锁定着对端键鼠(仅审计用:remote_close 要能说明自己强制解了锁)。
bool IsScreenCtrlBlocked(uint64_t device_id, const std::string& sessionId);
// 键鼠锁定的强制解除:关闭会话 / idle 回收 / 超期自动解锁时必须先发 block=false,
// 否则客户端进程还活着就会一直 BlockInput(人进不来)。三处实现:
// 1) CloseScreenCtrlSession / SweepIdleScreenCtrl —— 擦会话前发(见 .cpp);
// 2) WatchdogScreenBlock —— 每 500ms 扫描超过 blockUntil 的会话;
// 3) OnScreenControlClosed —— 子连接已断,无从下发,只能靠客户端进程退出(既有局限)。
// 另一个既有局限:Windows 要求调用进程有管理员权限(或 UIAccess)才允许 BlockInput,
// 客户端忽略返回值,低权限下会静默不生效——服务端无从得知,故工具结果只承诺「已送达」。
void BlockWatchdogLoop();
void WatchdogScreenBlock();
// ===== P6:MCP 文件传输(download_file,V2 协议)=====
// 下载走 CMD_DOWN_FILES_V2 → 客户端新开流式子连接回传 COMMAND_SEND_FILE_V2 /
// COMMAND_FILE_COMPLETE_V2(dstClientID==0)。会话按 device_id 键控,单设备单传输;
@@ -270,6 +341,12 @@ public:
void SetFileTransferEnabled(bool enabled) { m_fileTransferEnabled = enabled; }
bool IsFileTransferEnabled() const { return m_fileTransferEnabled; }
// ===== P10-B:文件系统写操作(delete_path / move_path / create_folder)=====
// 独立开关 McpFileWrite(默认关),并要求 McpReadonly=0。不复用 McpFileTransfer:
// 上传是「覆盖」,删除是「毁灭」,风险等级不同,必须能分别关掉。
void SetFileWriteEnabled(bool enabled) { m_fileWriteEnabled = enabled; }
bool IsFileWriteEnabled() const { return m_fileWriteEnabled; }
// 该 host 是否有进行中的文件传输会话(MessageHandle 分派守卫)。
bool IsFileTransferPending(uint64_t device_id);
@@ -377,7 +454,28 @@ public:
bool OnServiceReady(uint64_t device_id, context* subCtx);
// 工具线程:等待写确认包(第二个同 token 包);超时/空数据清挂起并 CancelIO 子连接。
bool WaitPendingWrite(uint64_t device_id, std::vector<BYTE>& out, int timeoutMs);
// phaseOut(可空):返回超时/成功那一刻所处的阶段(见 P10-B 的 phase),供调用方区分
// 「连完成包都没收到」与「完成包已到、复核没回来」。
bool WaitPendingWrite(uint64_t device_id, std::vector<BYTE>& out, int timeoutMs,
int* phaseOut = nullptr);
// ===== P10-B:文件系统写操作(delete_path / move_path / create_folder)=====
// 链路与 P7 同构(主连接 COMMAND_LIST_DRIVE → 子连接首包 TOKEN_DRIVE_LIST → 同一子连接
// 上发写命令 → 等 TOKEN_*_FINISH),但多一个阶段:客户端的完成包是无条件回包
// (忽略 DeleteFile/MoveFile/MakeSureDirectoryPathExists 的返回值),所以收到后不直接
// 收尾,而在同一子连接上补发一次 COMMAND_LIST_FILES 复核(phase 0 = 等完成包,
// phase 1 = 等复核列目录,两阶段共用一个超时)。
//
// verifyPath 是复核要列的父目录(客户端 ANSI/GBK,空 = 不复核,直接投递完成包)。
bool BeginPendingFileOp(uint64_t device_id, const std::string& tool,
const std::vector<BYTE>& followUp, const std::string& verifyPath);
// MessageHandle(TOKEN_DELETE_FINISH / TOKEN_RENAME_FINISH / TOKEN_CREATEFOLDER_FINISH) 调用。
// NotMine 与本请求无关(迟到的孤儿包)→ 调用方 CancelIO 收尾;
// KeepSub 已转入 phase 1、在同一子连接上补发了列目录 → 调用方不关子连接;
// CloseSub 已投递最终数据(无复核目标 / 复核包发不出去)→ 调用方 CancelIO 收尾。
enum class FileOpAck { NotMine, KeepSub, CloseSub };
FileOpAck TakeFileOpFinish(uint64_t device_id, context* subCtx, const BYTE* data, ULONG len);
// ===== 迟到首包吸收(工具放弃后不再弹出 MFC 对话框)=====
// 工具超时/失败清掉挂起后,客户端仍可能才把应答首包发上来(列盘、服务列表、注册表、
@@ -482,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,
@@ -516,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();
@@ -561,6 +692,9 @@ private:
McpTlsProxy m_tlsProxy; // HTTPS 前端(仅在 m_httpsEnabled 时启动)
std::thread m_thread;
std::atomic<bool> m_running{false};
// 键鼠锁定看门狗(P10-C):m_blockStop 置位后线程在下一次 100ms 切片退出。
std::thread m_blockThread;
std::atomic<bool> m_blockStop{false};
std::string m_token;
std::string m_bind; // Start 传入的监听地址
int m_port = 0; // Start 传入的监听端口
@@ -574,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 字节)
@@ -602,6 +738,9 @@ private:
std::vector<std::vector<BYTE>> searchRecords; // 已收集的 TOKEN_SEARCH_FILE_LIST 原始包
size_t searchBytes = 0;
bool searchFinished = false; // 已收到 TOKEN_SEARCH_FILE_FINISH
// ===== P10-B:文件写工具(delete_path / move_path / create_folder)=====
int phase = 0; // 0=等 TOKEN_*_FINISH;1=等复核用的 TOKEN_FILE_LIST
std::string verifyPath; // phase 1 要列的父目录(客户端 ANSI/GBK)
bool searchStopSent = false; // 已下发 COMMAND_FILES_SEARCH_STOP
bool searchTruncated = false; // 命中收集上限,后续匹配被丢弃
};
@@ -609,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;
@@ -662,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;
@@ -685,8 +830,14 @@ 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 是服务端认为的锁定状态(唯一真相,用于强制解锁);
// blockUntil 是自动解锁期限;blockAutoReleased 待下一次 remote_block_input 上报。
bool inputBlocked = false;
std::chrono::steady_clock::time_point blockUntil{};
bool blockAutoReleased = false;
};
std::mutex m_ScreenCtrlMutex;
std::map<uint64_t, ScreenCtrlSession> m_ScreenCtrlSessions; // device_id → 会话
@@ -725,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;
@@ -750,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;
@@ -778,6 +933,7 @@ private:
bool m_terminalEnabled = false; // 持久终端开关(默认关;要求 m_readonly=false)
bool m_remoteControlEnabled = false; // 远程控制开关(默认关;要求 m_readonly=false)
bool m_fileTransferEnabled = false; // 文件传输开关(默认关;download_file)
bool m_fileWriteEnabled = false; // P10-B 文件写入开关(默认关;要求 m_readonly=false)
bool m_manageEnabled = false; // P7 管理控制开关(默认关;要求 m_readonly=false)
bool m_machineEnabled = false; // P8 主机管理族总开关(默认关;16 个 host_* 工具)
bool m_machineDangerousEnabled = false; // P8 高风险子集(冻结/解冻进程、停止/重启服务)
+14 -2
View File
@@ -162,6 +162,9 @@ BOOL CMcpSettingsDlg::OnInitDialog()
m_btnFileTransfer.Create(_TR("启用文件传输(download_file)"),
WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_AUTOCHECKBOX,
r0, this, IDC_MCP_FILETRANSFER);
m_btnFileWrite.Create(_TR("启用文件写入(删除/改名/建目录,不可恢复)"),
WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_AUTOCHECKBOX,
r0, this, IDC_MCP_FILEWRITE);
m_btnManage.Create(_TR("启用管理操作(进程/窗口/服务/电源)"),
WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_AUTOCHECKBOX,
r0, this, IDC_MCP_MANAGE);
@@ -207,6 +210,7 @@ BOOL CMcpSettingsDlg::OnInitDialog()
m_btnTerminal.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_btnRemoteControl.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_btnFileTransfer.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_btnFileWrite.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_btnManage.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_btnMachine.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
m_btnMachineDangerous.SendMessage(WM_SETFONT, (WPARAM)hFont, MAKELPARAM(TRUE, 0));
@@ -228,6 +232,7 @@ BOOL CMcpSettingsDlg::OnInitDialog()
int terminal = THIS_CFG.GetInt("settings", "McpTerminal", 0);
int remoteControl = THIS_CFG.GetInt("settings", "McpRemoteControl", 0);
int fileTransfer = THIS_CFG.GetInt("settings", "McpFileTransfer", 0);
int fileWrite = THIS_CFG.GetInt("settings", "McpFileWrite", 0);
int manage = THIS_CFG.GetInt("settings", "McpManage", 0);
int machine = THIS_CFG.GetInt("settings", "McpMachine", 0);
int machineDangerous = THIS_CFG.GetInt("settings", "McpMachineDangerous", 0);
@@ -250,6 +255,7 @@ BOOL CMcpSettingsDlg::OnInitDialog()
m_btnTerminal.SetCheck(terminal ? BST_CHECKED : BST_UNCHECKED);
m_btnRemoteControl.SetCheck(remoteControl ? BST_CHECKED : BST_UNCHECKED);
m_btnFileTransfer.SetCheck(fileTransfer ? BST_CHECKED : BST_UNCHECKED);
m_btnFileWrite.SetCheck(fileWrite ? BST_CHECKED : BST_UNCHECKED);
m_btnManage.SetCheck(manage ? BST_CHECKED : BST_UNCHECKED);
m_btnMachine.SetCheck(machine ? BST_CHECKED : BST_UNCHECKED);
m_btnMachineDangerous.SetCheck(machineDangerous ? BST_CHECKED : BST_UNCHECKED);
@@ -323,6 +329,7 @@ void CMcpSettingsDlg::OnOK()
bool terminal = (m_btnTerminal.GetCheck() == BST_CHECKED);
bool remoteControl = (m_btnRemoteControl.GetCheck() == BST_CHECKED);
bool fileTransfer = (m_btnFileTransfer.GetCheck() == BST_CHECKED);
bool fileWrite = (m_btnFileWrite.GetCheck() == BST_CHECKED);
bool manage = (m_btnManage.GetCheck() == BST_CHECKED);
bool machine = (m_btnMachine.GetCheck() == BST_CHECKED);
bool machineDangerous = (m_btnMachineDangerous.GetCheck() == BST_CHECKED);
@@ -384,6 +391,7 @@ void CMcpSettingsDlg::OnOK()
THIS_CFG.SetInt("settings", "McpTerminal", terminal ? 1 : 0);
THIS_CFG.SetInt("settings", "McpRemoteControl", remoteControl ? 1 : 0);
THIS_CFG.SetInt("settings", "McpFileTransfer", fileTransfer ? 1 : 0);
THIS_CFG.SetInt("settings", "McpFileWrite", fileWrite ? 1 : 0);
THIS_CFG.SetInt("settings", "McpManage", manage ? 1 : 0);
THIS_CFG.SetInt("settings", "McpMachine", machine ? 1 : 0);
THIS_CFG.SetInt("settings", "McpMachineDangerous", machineDangerous ? 1 : 0);
@@ -398,8 +406,9 @@ void CMcpSettingsDlg::OnOK()
// 拆成多段可翻译的单行键,中间用 \r\n 连接(多行键无法在 INI 中表示)
MessageBox(_TR("MCP 设置已保存。") + _T("\r\n") +
_TR("启用/端口/绑定地址/Token/只读/白名单/持久终端/远程控制/文件传输/管理操作/主机管理/危险主机操作的改动需重启程序生效。") + _T("\r\n") +
_TR("持久终端、远程控制与管理操作仅在只读模式关闭时生效。") + _T("\r\n") +
_TR("启用/端口/绑定地址/Token/只读/白名单/持久终端/远程控制/文件传输/文件写入/管理操作/主机管理/危险主机操作的改动需重启程序生效。") + _T("\r\n") +
_TR("持久终端、远程控制、管理操作与文件写入仅在只读模式关闭时生效。") + _T("\r\n") +
_TR("文件写入包含删除(不可恢复)、改名与建目录;删除会拒绝盘符根与系统目录。") + _T("\r\n") +
_TR("主机管理的写操作需只读模式关闭;冻结/解冻进程、停止/重启服务还需启用危险主机操作。") + _T("\r\n") +
_TR("远程交谈开关的改动需重启程序生效。") + _T("\r\n") +
_TR("键盘记录开关的改动需重启程序生效。") + _T("\r\n") +
@@ -463,6 +472,9 @@ void CMcpSettingsDlg::LayoutControls(int cx, int cy)
m_btnFileTransfer.MoveWindow(margin, y, cx - margin * 2, 22);
y += 30;
m_btnFileWrite.MoveWindow(margin, y, cx - margin * 2, 22);
y += 30;
m_btnManage.MoveWindow(margin, y, cx - margin * 2, 22);
y += 30;
+2
View File
@@ -45,6 +45,7 @@ private:
IDC_MCP_KEY = 1017, // 私钥路径编辑框(PKCS#8)
IDC_MCP_CERT_BROWSE = 1018, // 证书路径「浏览」按钮
IDC_MCP_KEY_BROWSE = 1019, // 私钥路径「浏览」按钮
IDC_MCP_FILEWRITE = 1020, // 「启用文件写入」复选框(删除/改名/建目录,要求只读关)
};
CButton m_btnEnable;
@@ -54,6 +55,7 @@ private:
CButton m_btnTerminal;
CButton m_btnRemoteControl;
CButton m_btnFileTransfer;
CButton m_btnFileWrite;
CButton m_btnManage;
CButton m_btnMachine;
CButton m_btnMachineDangerous;
+564 -8
View File
@@ -1,10 +1,22 @@
<#
服务端 MCP 只读冒烟测试。
服务端 MCP 冒烟测试。
只调用「不会改变任何状态」的工具(列表/详情类),断言结构化字段齐全、
默认只调用「不会改变任何状态」的工具(列表/详情类),断言结构化字段齐全、
分页字段正确、鉴权与请求体上限生效。可在发布前对着任一台在线主机跑一遍,
确认 MCP 链路与改动前相比没有回归。
唯一会写目标机的部分是 [4c] 文件写入,且必须显式给 -FileWriteDir 才会跑:
它在那个目录下建一个 mcp_smoke_xxxx 沙箱,走完 create/upload/rename/delete
后整棵删掉,不碰沙箱以外的任何东西。
[6] 是 P11 的验收:-32012(校验拒绝,历史别名 -32008 不再出现)、dry_run
只校验不下发、mcp_list_sessions / mcp_cancel_session 与 notifications/cancelled
的取消路径(取消后 1s 内释放主机、被取消的请求回 -32800)、以及 SSE 进度通知。
其中「真实取消」会起一条能在目标机跑够 ~25s 的无副作用命令(Windows 上是
ping -n 25 127.0.0.1,没有 exec_command 时退回 get_keylog 20s),1s 后取消;
命令本身会在目标机上自己跑完,不影响结果。SSE 进度一节同样要求 -FileWriteDir,
会往那个目录上传一个 4 MB 临时文件并在结束时删掉。
用法:
$env:YAMA_MCP_TOKEN = '<token>' # 与 service 的 McpToken 一致
powershell -ExecutionPolicy Bypass -File tools\mcp_smoke.ps1
@@ -16,10 +28,16 @@
-HostId 指定在线主机 id;缺省取 list_online_hosts 的第一台
-SkipHost 只测服务端本机工具,不触达远程主机(无在线主机时用)
-SearchPath 可选,跑 search_file 测试的搜索根目录(如 C:\Windows\Fonts)。
不指定就跳过:客户端递归用无界 wsprintf 拼 MAX_PATH 缓冲,
深目录会栈溢出(Debug 客户端弹 Run-Time Check Failure #2)。
不指定就跳过:没有安全的默认根目录,从盘符根扫描很慢,且路径超过
MAX_PATH 的条目会被客户端静默跳过(8f718d9 起不再栈溢出),通常先撞
10000 条上限,测出来的是「部分结果」而不是功能是否可用。
-AuditLog 可选,服务端审计日志路径(如 Bin\logs\mcp_audit.log)。给了才断言
-32006 拒绝会写一条 CALL_DENIED。
-FileWriteDir 可选,跑 delete_path / move_path / create_folder 的目标机目录
(必须已存在且可写,如 C:\Users\Public 或 C:\Temp)。脚本只在其下
新建 mcp_smoke_xxxx 沙箱并在结束时删掉它。不指定就跳过这一节。
注意 upload_file 的 local_path 指的是服务端本机路径,所以这一节要求
冒烟脚本与服务端在同一台机器上(默认的 127.0.0.1 即如此)。
退出码:0 全部通过;1 有失败项。token 不会被打印。
#>
@@ -29,10 +47,14 @@ param(
[string]$HostId = '',
[switch]$SkipHost,
[string]$SearchPath = '',
[string]$AuditLog = ''
[string]$AuditLog = '',
[string]$FileWriteDir = ''
)
$ErrorActionPreference = 'Stop'
# Start-RpcAsync 用 HttpClient 发并发请求;Windows PowerShell 5.1 默认没加载这个程序集,
# 而类型字面量在执行该语句时就要能解析,所以放在脚本开头加载。
try { Add-Type -AssemblyName System.Net.Http -ErrorAction Stop } catch { }
$script:pass = 0
$script:fail = 0
$script:failures = @()
@@ -86,6 +108,58 @@ function HasPaging($obj) {
return $true
}
# 工具是否出现在 tools/list 里:不可见多半是开关关着(正常配置),相关断言跳过而不是报失败。
function HasTool([string]$name) {
return (@($tools | Where-Object { $_.name -eq $name }).Count -gt 0)
}
# 并发发起一个 tools/call:取消测试要在请求还在飞的时候去查表、去取消,
# 单线程的 Invoke-WebRequest 做不到。返回句柄交给 Receive-RpcAsync 收尾。
#
# 用 HttpClient.SendAsync(真异步,立即返回 Task)。别用 HttpWebRequest + BeginGetResponse:
# 实测 EndGetResponse 之前 BeginGetResponse 自己就会阻塞到响应头到达(服务端在工具跑完
# 才写响应头),于是「异步」调用其实是同步的,被测的长调用根本没在飞。
$script:HttpClient = $null
function Get-SmokeHttpClient() {
if (-not $script:HttpClient) {
$c = New-Object System.Net.Http.HttpClient
$c.Timeout = [TimeSpan]::FromSeconds(180)
$script:HttpClient = $c
}
return $script:HttpClient
}
function Start-RpcAsync([string]$json) {
$req = New-Object System.Net.Http.HttpRequestMessage([System.Net.Http.HttpMethod]::Post, $Base)
$req.Content = New-Object System.Net.Http.StringContent($json, [System.Text.Encoding]::UTF8, 'application/json')
$req.Headers.Add('Authorization', 'Bearer ' + $Token)
$req.Headers.Add('Accept', 'application/json, text/event-stream')
return @{ Request = $req; Task = (Get-SmokeHttpClient).SendAsync($req) }
}
function Receive-RpcAsync($handle) {
$resp = $null
try {
$resp = $handle.Task.GetAwaiter().GetResult() # 非 2xx 不抛异常(没调 EnsureSuccessStatusCode)
return $resp.Content.ReadAsStringAsync().GetAwaiter().GetResult()
} catch {
return ''
} finally {
if ($resp) { $resp.Dispose() }
$handle.Request.Dispose()
}
}
# 带 Accept: text/event-stream 的请求:带 _meta.progressToken 的 tools/call 会以
# chunked SSE 回应,Invoke-WebRequest 读完整条流后一次性返回正文。
function Send-Sse([string]$json, [string]$auth) {
$bytes = [System.Text.Encoding]::UTF8.GetBytes($json)
$headers = @{ Authorization = 'Bearer ' + $auth; Accept = 'application/json, text/event-stream' }
$resp = Invoke-WebRequest -Uri $Base -Method Post -Body $bytes -ContentType 'application/json' `
-Headers $headers -TimeoutSec 300 -UseBasicParsing
return @{ Status = [int]$resp.StatusCode; Body = [string]$resp.Content
ContentType = [string]$resp.Headers['Content-Type'] }
}
# 结果外露(docs/Mcp_Design.md §14):content 末尾必须有一个可解析的 JSON 文本块,
# 内容与 structuredContent 对应。只读 content 的客户端(WorkBuddy)靠它拿到 id。
function HasJsonText($rpc) {
@@ -118,6 +192,8 @@ Check '请求体超过 2 MB 返回 413' ($o.Status -eq 413) ("status=" + $o.Stat
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)
# initialize.instructions 是模型唯一的「隐性知识」入口(主机 id 形态、开关、错误码、编排)。
Check 'initialize 带非空 instructions' (([string]$init.result.instructions).Length -gt 100)
$tl = Rpc 'tools/list' @{} $null $null
$tools = @($tl.result.tools)
@@ -134,6 +210,12 @@ $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)
# P11:在飞会话的观测 / 取消入口必须一直可见——它是卡住请求的唯一出路,
# 因此不受功能开关与只读模式限制(只读时也在列表里)。
foreach ($n in @('mcp_list_sessions', 'mcp_cancel_session')) {
Check ('tools/list 含 ' + $n) (@($tools | Where-Object { $_.name -eq $n }).Count -eq 1)
}
# ===== 2b. 协议层错误码 =====
Write-Host "`n[2b] 协议层错误码"
$um = Rpc 'bogus/method' @{} $null $null
@@ -210,12 +292,64 @@ if (-not $SkipHost) {
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))
# capabilities:这台主机本身能做什么(服务端开关在 get_server_status.switches)。
# 逐项都要能对上真实门控,所以除了「齐全」还要断言 platform 与 registry 的一致性。
$caps = $h.capabilities
Check 'get_host_detail 带 capabilities.platform' ($null -ne $caps -and [string]$caps.platform -ne '')
$capFlags = @('screenPreview', 'remoteControl', 'fileTransferV2', 'c2cPaths', 'registry')
$missing = @($capFlags | Where-Object {
$null -eq $caps -or $null -eq $caps.$_ -or $caps.$_.GetType() -ne [bool]
})
Check 'capabilities 五个布尔位齐全' ($missing.Count -eq 0) ("missing=" + ($missing -join ','))
$isWin = @('DLL', 'EXE', 'MEXE', 'SC', 'MDLL') -contains [string]$caps.platform
Check 'capabilities.registry 与平台一致(仅 Windows)' ($caps.registry -eq $isWin) `
("platform=" + $caps.platform + " registry=" + $caps.registry)
if (@('MAC', 'APK') -contains [string]$caps.platform) {
Check 'capabilities.remoteControl 对 MAC/APK 为 false' ($caps.remoteControl -eq $false) `
("platform=" + $caps.platform)
}
$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)
# 服务端过滤(P10-A §5.3):过滤在分页之前生效——total 是命中数,totalAll 仍是全量。
$firstProc = @($ps.processes)[0]
if ($firstProc -and [string]$firstProc.name) {
$pname = [string]$firstProc.name
$byName = Rpc '' $null 'list_processes' @{ id = $HostId; name = $pname; limit = 100 }
$bn = $byName.result.structuredContent
# totalAll 是「过滤前的总数」,两次调用之间目标机的进程本来就会增减(实测差过 1),
# 所以留一点余量:要断言的是「过滤没有把 totalAll 一起缩掉」,不是快照完全相等。
$drift = [Math]::Abs([int]$bn.totalAll - [int]$ps.totalAll)
Check 'list_processes name 过滤命中且 totalAll 不变' `
($byName.error -eq $null -and $drift -le 10 -and
[int]$bn.total -gt 0 -and [int]$bn.total -le [int]$bn.totalAll) `
("total=" + $bn.total + " totalAll=" + $bn.totalAll + " baseAll=" + $ps.totalAll + " drift=" + $drift)
$lower = $pname.ToLowerInvariant()
Check 'list_processes name 过滤结果都含该名字' `
(@($bn.processes | Where-Object { -not ([string]$_.name).ToLowerInvariant().Contains($lower) }).Count -eq 0)
}
if ($firstProc -and $null -ne $firstProc.pid) {
$ppid = [int]$firstProc.pid
$byPid = Rpc '' $null 'list_processes' @{ id = $HostId; pid = $ppid; limit = 100 }
$bp = $byPid.result.structuredContent
Check 'list_processes pid 过滤只返回该进程' `
($byPid.error -eq $null -and [int]$bp.total -ge 1 -and
@($bp.processes | Where-Object { [int]$_.pid -ne $ppid }).Count -eq 0) `
("pid=" + $ppid + " total=" + $bp.total)
# 6b 的 dry_run 断言要拿一个真能操作的进程:pid 0 是内核伪进程([System Process]),
# kill_process 按约定拒绝非零以外的 PID,host_control_process 也认不出它。
$sample = Rpc '' $null 'list_processes' @{ id = $HostId; limit = 50 }
if ($null -eq $sample.error) {
$realProc = @($sample.result.structuredContent.processes | Where-Object { [int]$_.pid -gt 4 })[0]
if ($realProc) { $ppid = [int]$realProc.pid }
}
}
$wins = Rpc '' $null 'list_windows' @{ id = $HostId; limit = 3 }
Check 'list_windows 正常返回' ($wins.error -eq $null -and (HasPaging $wins.result.structuredContent))
@@ -229,8 +363,8 @@ if (-not $SkipHost) {
$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 并挂住搜索线程)。所以默认不跑,
# search_file:没有安全的默认搜索根。从盘符根扫描很慢,客户端会静默跳过超过
# MAX_PATH 的路径(8f718d9 起不再栈溢出),通常先撞 10000 条上限。所以默认不跑,
# 需要时用 -SearchPath 指定一个中浅层目录(如 C:\Windows\Fonts)。
if ($SearchPath) {
$search = Rpc '' $null 'search_file' @{ id = $HostId; path = $SearchPath; pattern = '*.exe'; limit = 3; timeout_ms = 5000 }
@@ -259,7 +393,7 @@ if (-not $SkipHost) {
($bad.error -and [int]$bad.error.code -eq -32602)
}
} else {
Write-Host " 未指定 -SearchPath,跳过 search_file 测试(深目录会触发客户端已知的 MAX_PATH 栈溢出)。" -ForegroundColor Yellow
Write-Host " 未指定 -SearchPath,跳过 search_file 测试(默认根目录扫得慢且结果不全)。" -ForegroundColor Yellow
}
}
@@ -267,6 +401,26 @@ if (-not $SkipHost) {
$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)
# get_keylog.offlineRecord(P10-A):客户端就绪包里带「离线记录」标志,老客户端只发 1 字节,
# 此时服务端按设计省略该字段——缺省与布尔都算通过,但要把是哪种情况说出来。
if (@($tools | Where-Object { $_.name -eq 'get_keylog' }).Count -gt 0) {
$kl = Rpc '' $null 'get_keylog' @{ id = $HostId; duration_ms = 1000; max_bytes = 4096 }
if ($kl.error) {
Check 'get_keylog 正常返回' $false ([string]$kl.error.message)
} else {
$ks = $kl.result.structuredContent
$hasFlag = $ks.PSObject.Properties.Name -contains 'offlineRecord'
Check 'get_keylog.offlineRecord 为布尔(老客户端可缺省)' `
((-not $hasFlag) -or $ks.offlineRecord.GetType() -eq [bool]) `
("offlineRecord=" + $ks.offlineRecord)
if (-not $hasFlag) {
Write-Host " 主机未上报离线记录标志(老客户端),offlineRecord 缺省属预期。" -ForegroundColor Yellow
}
}
} else {
Write-Host " get_keylog 未开启(McpKeylog),跳过键盘记录读取。" -ForegroundColor Yellow
}
}
# ===== 4b. 结构化失败(新客户端:TOKEN_*_ERROR → -32009/-32010) =====
@@ -314,6 +468,153 @@ if (-not $SkipHost -and $drive) {
}
}
# ===== 4c. 文件写入(P10-B:delete_path / move_path / create_folder) =====
# 客户端对删除文件/删除目录/建目录/改名四条命令都是「做完就无条件回完成包」,ok 只证明命令送达;真正的结论在
# verified(true=复核看到状态变了,false=复核看到没变,null=复核没做成)。所以这一节只断言
# verified,不看 ok。顺带覆盖两处只有真机才暴露的坑:建目录要在路径末尾补反斜杠,
# 以及复核要读 LookupInListing 的 isDir 出参。
function Detail($r) {
if ($null -ne $r -and $null -ne $r.error) { return [string]$r.error.message }
$c = @($r.result.content)
if ($c.Count -gt 0) { return [string]$c[0].text }
return ''
}
function ErrCode($r) {
if ($null -eq $r -or $null -eq $r.error) { return 0 }
return [int]$r.error.code
}
function OkVerified($r) {
if ($null -eq $r -or $null -ne $r.error) { return $false }
$s = $r.result.structuredContent
return (($s.ok -eq $true) -and ($s.verified -eq $true))
}
function ListingNames([string]$path) {
$r = Rpc '' $null 'list_files' @{ id = $HostId; path = $path; limit = 100 }
if ($r.error) { return @() }
return @($r.result.structuredContent.files | ForEach-Object { [string]$_.name })
}
$writeTools = @($tools | Where-Object { $_.name -in @('delete_path', 'move_path', 'create_folder') })
if ($writeTools.Count -lt 3) {
Write-Host "`n[4c] 文件写入:工具未出现(McpFileWrite 关或 McpReadonly 开),跳过。" -ForegroundColor Yellow
} elseif ($SkipHost -or -not $HostId) {
Write-Host "`n[4c] 文件写入:没有在线主机,跳过。" -ForegroundColor Yellow
} elseif (-not $FileWriteDir) {
Write-Host "`n[4c] 文件写入:未给 -FileWriteDir,跳过(这一节会在目标机上建/删文件)。" -ForegroundColor Yellow
} else {
Write-Host "`n[4c] 文件写入 (根=$FileWriteDir)"
$sandbox = $FileWriteDir.TrimEnd('\') + '\mcp_smoke_' + (Get-Random -Minimum 10000 -Maximum 99999)
$uploadedName = ''
try {
# 一次建两层:既测「中间层一并创建」,也测路径末尾的反斜杠(少了它,客户端
# MakeSureDirectoryPathExists 会把最后一级当成文件名,只建中间层)。
$deep = $sandbox + '\sub\deep'
$mk = Rpc '' $null 'create_folder' @{ id = $HostId; path = $deep }
Check 'create_folder 建嵌套目录 verified=true' (OkVerified $mk) (Detail $mk)
$names = ListingNames $sandbox
Check 'create_folder 后父目录里能看到它' ($names -contains 'sub') ("names=" + ($names -join ','))
# upload_file 的返回值只有摘要,用列表复核它到底落没落盘
$localFile = Join-Path $env:TEMP ('mcp_smoke_upload_' + (Get-Random -Minimum 1000 -Maximum 9999) + '.txt')
Set-Content -LiteralPath $localFile -Value 'mcp smoke' -Encoding ascii
$uploadedName = [System.IO.Path]::GetFileName($localFile)
$uploadOk = $false
if (@($tools | Where-Object { $_.name -eq 'upload_file' }).Count -gt 0) {
$up = Rpc '' $null 'upload_file' @{ id = $HostId; local_path = $localFile; remote_dir = $sandbox }
$uploadOk = ($null -eq $up.error)
Check 'upload_file 正常返回' $uploadOk (Detail $up)
} else {
Write-Host " upload_file 未开启,跳过上传/改名/删文件三连。" -ForegroundColor Yellow
}
if ($uploadOk) {
Check 'upload_file 后沙箱里能看到该文件' ((ListingNames $sandbox) -contains $uploadedName)
$renamed = $uploadedName -replace '\.txt$', '_renamed.txt'
$mv = Rpc '' $null 'move_path' @{ id = $HostId; from = ($sandbox + '\' + $uploadedName); to = ($sandbox + '\' + $renamed) }
Check 'move_path 改名 verified=true' (OkVerified $mv) (Detail $mv)
$names = ListingNames $sandbox
Check 'move_path 后新名字出现、旧名字消失' `
(($names -contains $renamed) -and -not ($names -contains $uploadedName)) ("names=" + ($names -join ','))
$uploadedName = $renamed
$rm = Rpc '' $null 'delete_path' @{ id = $HostId; path = ($sandbox + '\' + $renamed) }
Check 'delete_path 删文件 verified=true' (OkVerified $rm) (Detail $rm)
Check 'delete_path 后文件不在列表里' (-not ((ListingNames $sandbox) -contains $renamed))
} elseif (@($tools | Where-Object { $_.name -eq 'upload_file' }).Count -gt 0) {
# 上传失败时改名/删文件没有对象,跳过而不是再报两条失败(upload_file 那条已经记了)
Write-Host " 上一步 upload_file 失败,跳过改名/删文件。" -ForegroundColor Yellow
}
Remove-Item -LiteralPath $localFile -Force -ErrorAction SilentlyContinue
# 非 ASCII 路径:服务端按 UTF-8 校验、只转一次 GBK,客户端再用 A 接口落盘
$cnDir = $sandbox + '\中文目录'
$cn = Rpc '' $null 'create_folder' @{ id = $HostId; path = $cnDir }
Check 'create_folder 中文路径 verified=true' (OkVerified $cn) (Detail $cn)
$cnRm = Rpc '' $null 'delete_path' @{ id = $HostId; path = $cnDir; recursive = $true }
Check 'delete_path 中文路径 verified=true' (OkVerified $cnRm) (Detail $cnRm)
# recursive=false 落在目录上:客户端 DeleteFile 失败且不回错误包 → 复核必须说 false
$mk2 = Rpc '' $null 'create_folder' @{ id = $HostId; path = ($sandbox + '\asdir') }
if (OkVerified $mk2) {
$bad = Rpc '' $null 'delete_path' @{ id = $HostId; path = ($sandbox + '\asdir') }
Check 'delete_path 对目录用 recursive=false 时 verified=false' `
(($null -eq $bad.error) -and ($bad.result.structuredContent.ok -eq $true) -and
($bad.result.structuredContent.verified -eq $false)) (Detail $bad)
}
# 越界与参数拒绝:全部发生在服务端,不该触达目标机
$fwDrive = if ($drive) { $drive } else { $FileWriteDir.Substring(0, 2) }
$fwRoot = $fwDrive.TrimEnd('\')
$longPath = $sandbox + '\' + ('a' * 220)
$cases = @(
@{ name = '盘符根'; tool = 'delete_path'; args = @{ id = $HostId; path = $fwRoot }; code = -32602 }
@{ name = '系统目录'; tool = 'delete_path'; args = @{ id = $HostId; path = ($fwRoot + '\Windows\Temp') }; code = -32602 }
@{ name = '含 %VAR%'; tool = 'delete_path'; args = @{ id = $HostId; path = '%TEMP%\mcp_smoke_x' }; code = -32602 }
@{ name = '相对路径'; tool = 'create_folder'; args = @{ id = $HostId; path = 'mcp_smoke_x' }; code = -32602 }
@{ name = '超长路径'; tool = 'create_folder'; args = @{ id = $HostId; path = $longPath }; code = -32602 }
@{ name = 'from 与 to 相同'; tool = 'move_path'; args = @{ id = $HostId; from = $deep; to = $deep.ToUpperInvariant() }; code = -32602 }
@{ name = '主机不在线'; tool = 'create_folder'; args = @{ id = '1'; path = ($sandbox + '\x') }; code = -32002 }
)
foreach ($c in $cases) {
$r = Rpc '' $null $c.tool $c.args
Check ('参数被拒:' + $c.name + ' 返回 ' + $c.code) ((ErrCode $r) -eq $c.code) (Detail $r)
}
# 收尾:整棵删掉沙箱,并用父目录列表复核
$rmAll = Rpc '' $null 'delete_path' @{ id = $HostId; path = $sandbox; recursive = $true }
Check 'delete_path 递归删沙箱 verified=true' (OkVerified $rmAll) (Detail $rmAll)
$fwParent = $FileWriteDir.TrimEnd('\')
Check '沙箱已不在父目录里' (-not ((ListingNames $fwParent) -contains [System.IO.Path]::GetFileName($sandbox)))
} finally {
# 中途失败时也要尽量不把沙箱留在目标机上(尽力而为,不再断言)
$null = Rpc '' $null 'delete_path' @{ id = $HostId; path = $sandbox; recursive = $true }
}
}
# ===== 4d. 键鼠锁定(P10-C:remote_block_input)参数校验 =====
# 这里刻意不真的锁定对端:冒烟测试常常跑在操作者自己的电脑上(客户端与服务端同机),
# 真锁会把正在用电脑的人挡在外面。锁定 / 到期自动解除 / remote_close 强制解除只能人工旁观
# 目标机来验证(见 docs/Mcp_Next_Plan.md §3.1),本节只覆盖服务端就能判定的拒绝分支。
$blockTool = @($tools | Where-Object { $_.name -eq 'remote_block_input' }).Count -gt 0
if (-not $blockTool) {
Write-Host "`n[4d] 键鼠锁定:remote_block_input 未出现(McpRemoteControl=0 或 McpReadonly=1),跳过。" -ForegroundColor Yellow
} elseif ($SkipHost -or -not $HostId) {
Write-Host "`n[4d] 键鼠锁定:没有在线主机,跳过。" -ForegroundColor Yellow
} else {
Write-Host "`n[4d] 键鼠锁定(参数校验)"
$blockCases = @(
@{ name = '缺 block'; args = @{ id = $HostId; session_id = 'mcp_smoke_no_such' }; code = -32602 }
@{ name = 'block 非布尔'; args = @{ id = $HostId; session_id = 'mcp_smoke_no_such'; block = 'maybe' }; code = -32602 }
@{ name = 'max_block_ms 越界'; args = @{ id = $HostId; session_id = 'mcp_smoke_no_such'; block = $true; max_block_ms = 500 }; code = -32602 }
@{ name = '会话不存在'; args = @{ id = $HostId; session_id = 'mcp_smoke_no_such'; block = $true }; code = -32002 }
@{ name = '主机不在线'; args = @{ id = '1'; session_id = 'mcp_smoke_no_such'; block = $true }; code = -32002 }
)
foreach ($c in $blockCases) {
$r = Rpc '' $null 'remote_block_input' $c.args
Check ('键鼠锁定:' + $c.name + ' 返回 ' + $c.code) ((ErrCode $r) -eq $c.code) (Detail $r)
}
}
# ===== 5. 策略拒绝(-32006) =====
# 只在某个开关确实关闭时才有意义,所以先读 get_server_status 的 switches 再挑一个关着的功能。
# 全部开启时跳过(不算失败)——这条不是每次都能测,但测到时能证明拒绝路径与审计都还在。
@@ -343,6 +644,261 @@ if ($offGate) {
Write-Host " 所有功能开关都开着,跳过 -32006 检查(关掉任一开关再跑一次可覆盖)。" -ForegroundColor Yellow
}
# ===== 6. P11:校验码 / dry_run / 在飞会话观测与取消 / SSE 进度 =====
# 每条都对应 P11 的一条验收:
# 6a -32012(校验拒绝)取代历史别名 -32008;
# 6b dry_run 统一「只校验目标、不下发动作」;
# 6c mcp_list_sessions 快照 + mcp_cancel_session 与 notifications/cancelled 的取消,
# 以及「取消后主机 1s 内释放」(用 get_server_status.sessions.pending 复核);
# 6d 带 _meta.progressToken 的 tools/call 走 text/event-stream,长任务的进度通知计数 > 0。
Write-Host "`n[6] P11 校验码、dry_run 与中断"
# 取消测试要同时挂着长请求、还要再发短请求,需要比 .NET 默认(每主机 2 条)更多的连接。
[System.Net.ServicePointManager]::DefaultConnectionLimit = 16
$p11Host = (-not $SkipHost) -and [bool]$HostId
$isWindowsHost = ($null -eq $caps) -or (@('DLL', 'EXE', 'MEXE', 'SC', 'MDLL') -contains [string]$caps.platform)
# 6a. -32012:命令里的 shell 元字符属于「参数被校验拒绝」,不是白名单拒绝(-32007)
if ($p11Host -and (HasTool 'exec_command')) {
$badCmd = Rpc '' $null 'exec_command' @{ id = $HostId; command = 'dir & whoami' }
Check 'exec_command 含 shell 元字符返回 -32012' ((ErrCode $badCmd) -eq -32012) (Detail $badCmd)
Check '校验拒绝不再使用历史别名 -32008' ((ErrCode $badCmd) -ne -32008) (Detail $badCmd)
} else {
Write-Host " exec_command 不可用,跳过 -32012 检查。" -ForegroundColor Yellow
}
# 6b. dry_run:只取一次快照校验目标存在,结构化结果带 dry_run=true,
# 且不能出现「动作后才有」的字段(remaining / changed)——那意味着动作真的下发了。
if ($p11Host -and (HasTool 'kill_process')) {
$drBad = Rpc '' $null 'kill_process' @{ id = $HostId; pids = @(4); dry_run = 'yes' }
Check 'kill_process dry_run 非布尔返回 -32602' ((ErrCode $drBad) -eq -32602) (Detail $drBad)
if ($null -ne $ppid) {
$dr = Rpc '' $null 'kill_process' @{ id = $HostId; pids = @($ppid); dry_run = $true }
$drs = $dr.result.structuredContent
Check 'kill_process dry_run=true 只校验(targets/missing,无 remaining)' `
(($null -eq $dr.error) -and ($drs.dry_run -eq $true) -and
(@($drs.targets).Count -ge 1) -and
($drs.PSObject.Properties.Name -contains 'missing') -and
-not ($drs.PSObject.Properties.Name -contains 'remaining')) (Detail $dr)
}
} else {
Write-Host " kill_process 不可用,跳过该 dry_run 检查。" -ForegroundColor Yellow
}
$win0 = $null
if ($null -ne $wins -and $null -ne $wins.result) { $win0 = @($wins.result.structuredContent.windows)[0] }
if ($p11Host -and (HasTool 'operate_window') -and $win0 -and $null -ne $win0.hwnd) {
$owBad = Rpc '' $null 'operate_window' @{ id = $HostId; hwnd = $win0.hwnd; action = 'restore'; dry_run = 'yes' }
Check 'operate_window dry_run 非布尔返回 -32602' ((ErrCode $owBad) -eq -32602) (Detail $owBad)
$ow = Rpc '' $null 'operate_window' @{ id = $HostId; hwnd = $win0.hwnd; action = 'restore'; dry_run = $true }
$ows = $ow.result.structuredContent
Check 'operate_window dry_run=true 只校验(window 有值、无 changed)' `
(($null -eq $ow.error) -and ($ows.dry_run -eq $true) -and ($null -ne $ows.window) -and
-not ($ows.PSObject.Properties.Name -contains 'changed')) (Detail $ow)
} else {
Write-Host " operate_window 不可用(或没有可见窗口),跳过该 dry_run 检查。" -ForegroundColor Yellow
}
if ($p11Host -and (HasTool 'host_control_process') -and $null -ne $ppid) {
$hc = Rpc '' $null 'host_control_process' @{ id = $HostId; action = 'freeze'; pid = $ppid; dry_run = $true }
$hcs = $hc.result.structuredContent
Check 'host_control_process dry_run=true 只校验(state/detail,无 changed)' `
(($null -eq $hc.error) -and ($hcs.dry_run -eq $true) -and ([string]$hcs.target -ne '') -and
-not ($hcs.PSObject.Properties.Name -contains 'changed')) (Detail $hc)
} else {
Write-Host " host_control_process 不可用,跳过该 dry_run 检查。" -ForegroundColor Yellow
}
# 6c. 观测与取消。参数拒绝 / 空命中先测(不依赖主机),真实取消再单独跑。
$ls0 = Rpc '' $null 'mcp_list_sessions' @{}
Check 'mcp_list_sessions 返回 sessions/count' `
(($null -eq $ls0.error) -and ($null -ne $ls0.result.structuredContent.sessions) -and
([int]$ls0.result.structuredContent.count -eq @($ls0.result.structuredContent.sessions).Count)) (Detail $ls0)
$lsBad = Rpc '' $null 'mcp_list_sessions' @{ kind = 'zzz-no-such-kind' }
Check 'mcp_list_sessions 非法 kind 返回 -32602' ((ErrCode $lsBad) -eq -32602) (Detail $lsBad)
$cnBad = Rpc '' $null 'mcp_cancel_session' @{}
Check 'mcp_cancel_session 缺参数返回 -32602' ((ErrCode $cnBad) -eq -32602) (Detail $cnBad)
$cnNone = Rpc '' $null 'mcp_cancel_session' @{ request_id = 'zzz-no-such-request' }
Check 'mcp_cancel_session 未命中返回 cancelled=0' `
(($null -eq $cnNone.error) -and ([int]$cnNone.result.structuredContent.cancelled -eq 0)) (Detail $cnNone)
# 真实取消:起一个确定会跑够 20s+ 的无副作用调用,等它进了在飞表再取消。
# Windows 主机用 exec_command 跑 ping(白名单内、不需要管理员),其他平台退回 get_keylog。
$longCall = $null
if ($p11Host) {
if ((HasTool 'exec_command') -and $isWindowsHost) {
$longCall = @{ tool = 'exec_command'
args = @{ id = $HostId; command = 'ping -n 25 127.0.0.1'; timeout_ms = 60000 } }
} elseif (HasTool 'get_keylog') {
$longCall = @{ tool = 'get_keylog'; args = @{ id = $HostId; duration_ms = 20000; max_bytes = 4096 } }
}
}
function Wait-Session([string]$rid, [int]$tries = 40) {
# 轮询 mcp_list_sessions 直到出现这次调用(或超时),返回快照项。
for ($i = 0; $i -lt $tries; $i++) {
Start-Sleep -Milliseconds 100
$snap = Rpc '' $null 'mcp_list_sessions' @{ kind = 'call' }
if ($null -eq $snap.error) {
$hit = @($snap.result.structuredContent.sessions | Where-Object { [string]$_.request_id -eq $rid })[0]
if ($hit) { return $hit }
}
}
return $null
}
if (-not $longCall) {
Write-Host " 没有能跑长的工具(exec_command/get_keylog),跳过取消与 SSE 进度检查。" -ForegroundColor Yellow
} else {
$rid = 'p11-cancel-' + (Get-Random -Minimum 1000 -Maximum 9999)
$payload = @{ jsonrpc = '2.0'; id = $rid; method = 'tools/call'
params = @{ name = $longCall.tool; arguments = $longCall.args } } |
ConvertTo-Json -Depth 8 -Compress
$h = Start-RpcAsync $payload
$seen = Wait-Session $rid
Check '在飞调用出现在 mcp_list_sessions 里' ($null -ne $seen) ("request_id=" + $rid)
if (-not $seen) {
$null = Receive-RpcAsync $h
Check '取消测试的前置条件(长调用进入在飞表)' $false '长任务没有进入在飞表,取消路径未验证'
} else {
Check '会话快照字段齐全(host_id/kind/tool/elapsed_ms)' `
((([string]$seen.host_id) -eq $HostId) -and ([string]$seen.kind -eq 'call') -and
([string]$seen.tool -eq $longCall.tool) -and ($null -ne $seen.elapsed_ms)) `
("host_id=" + $seen.host_id + " kind=" + $seen.kind + " tool=" + $seen.tool)
# -32003 的正文要点名占用者(P11 之前只有一句通用话)。它来自「同一主机的一次性
# 待响应请求单飞行」:exec_command 走的是终端子连接,与 list_processes 这类请求
# 并不互斥,所以占用者要用「并发打同一台主机」来制造,而不是拿长调用去当占用者。
if (HasTool 'list_processes') {
$raceHandles = @()
for ($i = 0; $i -lt 8; $i++) {
$raceHandles += Start-RpcAsync (@{ jsonrpc = '2.0'; id = ('race-' + $i); method = 'tools/call'
params = @{ name = 'list_processes'
arguments = @{ id = $HostId; limit = 5 } } } |
ConvertTo-Json -Depth 8 -Compress)
}
$raceErrs = @()
foreach ($rh in $raceHandles) {
$rb = [string](Receive-RpcAsync $rh)
$rj = $null
try { $rj = $rb | ConvertFrom-Json } catch { continue }
if ($null -ne $rj.error) { $raceErrs += $rj }
}
$busy = @($raceErrs | Where-Object { [int]$_.error.code -eq -32003 })[0]
Check '并发请求同一主机时被拒的返回 -32003 且点名占用者' `
(($null -ne $busy) -and ([string]$busy.error.message).Contains('tool=')) `
(($raceErrs | ForEach-Object { [string]$_.error.message }) -join ' | ')
}
$cn = Rpc '' $null 'mcp_cancel_session' @{ request_id = $rid }
$cns = $cn.result.structuredContent
Check 'mcp_cancel_session 按 request_id 取消' `
(($null -eq $cn.error) -and ([int]$cns.cancelled -eq 1)) (Detail $cn)
Check '取消后主机 1s 内释放' `
(($cns.released -eq $true) -and ([int]$cns.waited_ms -le 1000)) `
("released=" + $cns.released + " waited_ms=" + $cns.waited_ms)
$body = [string](Receive-RpcAsync $h)
$jr = $null
try { $jr = $body | ConvertFrom-Json } catch { }
if ($body.Length -gt 160) { $body = $body.Substring(0, 160) }
Check '被取消的请求回 -32800' (($null -ne $jr) -and ($null -ne $jr.error) -and
([int]$jr.error.code -eq -32800)) $body
# 交叉核对:get_server_status 的 sessions.pending 应回到 0,主机能再次正常调用
$st2 = (Rpc '' $null 'get_server_status' @{}).result.structuredContent.status
Check '取消后 get_server_status 无挂起(sessions.pending=0)' `
([int]$st2.sessions.pending -eq 0) ("pending=" + $st2.sessions.pending)
if (HasTool 'list_processes') {
$again = Rpc '' $null 'list_processes' @{ id = $HostId; limit = 1 }
Check '取消后主机可再次正常调用' ($null -eq $again.error) (Detail $again)
}
# notifications/cancelled:与 mcp_cancel_session 等价的通知路径(202 无响应体)
$rid2 = 'p11-notify-' + (Get-Random -Minimum 1000 -Maximum 9999)
$payload2 = @{ jsonrpc = '2.0'; id = $rid2; method = 'tools/call'
params = @{ name = $longCall.tool; arguments = $longCall.args } } |
ConvertTo-Json -Depth 8 -Compress
$h2 = Start-RpcAsync $payload2
$seen2 = Wait-Session $rid2
if (-not $seen2) {
$null = Receive-RpcAsync $h2
Check '第二个长调用进入在飞表(通知取消前置)' $false '长任务没有进入在飞表'
} else {
$note = '{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":"' +
$rid2 + '","reason":"smoke"}}'
$nr = Send-Raw $note $Token
Check 'notifications/cancelled 返回 202' ($nr.Status -eq 202) ("status=" + $nr.Status)
$body2 = [string](Receive-RpcAsync $h2)
$jr2 = $null
try { $jr2 = $body2 | ConvertFrom-Json } catch { }
if ($body2.Length -gt 160) { $body2 = $body2.Substring(0, 160) }
Check '通知取消后请求回 -32800' (($null -ne $jr2) -and ($null -ne $jr2.error) -and
([int]$jr2.error.code -eq -32800)) $body2
# 通知路径没有「等释放」的返回值,只能自己轮询(≤2s)
$freed = $false
for ($i = 0; $i -lt 20 -and -not $freed; $i++) {
$snap3 = Rpc '' $null 'mcp_list_sessions' @{ kind = 'call' }
if (@($snap3.result.structuredContent.sessions |
Where-Object { [string]$_.request_id -eq $rid2 }).Count -eq 0) { $freed = $true }
else { Start-Sleep -Milliseconds 100 }
}
Check '通知取消后 2s 内从在飞表消失' $freed
}
}
}
# 6d. SSE:带 _meta.progressToken 的 tools/call 以 text/event-stream 回应。
# 先用一个立即返回的工具验证传输与收尾(进度天然为 0 条),再用一次真实上传验证进度。
$probe = '{"jsonrpc":"2.0","id":7001,"method":"tools/call","params":{"name":"get_server_status","arguments":{},"_meta":{"progressToken":"smoke-probe"}}}'
$sse = Send-Sse $probe $Token
Check 'SSE:Content-Type 是 text/event-stream' ($sse.ContentType -like 'text/event-stream*') $sse.ContentType
$sseProbeLast = $null
foreach ($line in ($sse.Body -split "`n")) {
if ($line.StartsWith('data: ')) { try { $sseProbeLast = ($line.Substring(6) | ConvertFrom-Json) } catch { } }
}
Check 'SSE:流末尾是完整 JSON-RPC 响应' `
(($null -ne $sseProbeLast) -and ([string]$sseProbeLast.id -eq '7001') -and
($null -ne $sseProbeLast.result) -and ($null -eq $sseProbeLast.error))
if (-not $p11Host -or -not $FileWriteDir -or -not (HasTool 'upload_file') -or -not (HasTool 'delete_path')) {
Write-Host " 未给 -FileWriteDir 或文件写入工具不可见,跳过 SSE 进度检查(进度 > 0 需一次真实长任务)。" -ForegroundColor Yellow
} else {
# 4 MB 分 64 KB 一片:即使局域网很快也能产生多个进度回调(首个回调不受 1s 节流限制)。
$progLocal = Join-Path $env:TEMP ('mcp_smoke_prog_' + (Get-Random -Minimum 1000 -Maximum 9999) + '.bin')
$fs = [System.IO.File]::Create($progLocal)
$chunk = New-Object byte[] (64 * 1024)
for ($i = 0; $i -lt 64; $i++) { $fs.Write($chunk, 0, $chunk.Length) }
$fs.Close()
$progName = [System.IO.Path]::GetFileName($progLocal)
# 注意:PowerShell 变量名大小写不敏感,别用 $tok —— 会覆盖掉 bearer token $Token。
$progToken = 'smoke-progress-' + (Get-Random -Minimum 1000 -Maximum 9999)
$sseBody = @{ jsonrpc = '2.0'; id = 7002; method = 'tools/call'
params = @{ name = 'upload_file'
arguments = @{ id = $HostId; local_path = $progLocal; remote_dir = $FileWriteDir }
_meta = @{ progressToken = $progToken } } } |
ConvertTo-Json -Depth 10 -Compress
try {
$up = Send-Sse $sseBody $Token
$progCount = ([regex]::Matches($up.Body, [regex]::Escape('notifications/progress'))).Count
Check 'SSE:长任务收到 notifications/progress(计数 > 0)' ($progCount -gt 0) ("count=" + $progCount)
Check 'SSE:进度通知回显 progressToken 且带 progress' `
(($up.Body -match ('"progressToken":"' + [regex]::Escape($progToken) + '"')) -and
($up.Body -match '"progress":'))
$upLast = $null
foreach ($line in ($up.Body -split "`n")) {
if ($line.StartsWith('data: ')) { try { $upLast = ($line.Substring(6) | ConvertFrom-Json) } catch { } }
}
Check 'SSE:流末尾是 upload_file 的最终响应(未取消)' `
(($null -ne $upLast) -and ([string]$upLast.id -eq '7002') -and
($null -ne $upLast.result) -and ($null -eq $upLast.error))
Check 'SSE 进度测试上传的文件已落盘' ((ListingNames $FileWriteDir) -contains $progName)
} finally {
$null = Rpc '' $null 'delete_path' @{ id = $HostId; path = ($FileWriteDir.TrimEnd('\') + '\' + $progName) }
Remove-Item -LiteralPath $progLocal -Force -ErrorAction SilentlyContinue
}
}
# ===== 汇总 =====
Write-Host ("`n通过 " + $script:pass + " 项,失败 " + $script:fail + " 项。") -ForegroundColor $(if ($script:fail -eq 0) { 'Green' } else { 'Red' })
if ($script:fail -gt 0) {