14 Commits
Author SHA1 Message Date
yuanyuanxianganddeepseek-flash 425d737ca0 Fix(mcp): harden terminal teardown and fill annotation gaps
OnTerminalClosed now erases the shell route and nulls the session pointer
before OfflineProc returns that context to the pool, and WaitTerminalReady
re-looks-up the session on every wake, failing with cleanup when it is gone,
closed, or has no sub-connection. Before, a waiter could CancelIO a recycled
context, or a late cleanup could unroute a connection that reused it.

terminal_close only set closed and expected a waiter to clean up, so after a
caller timeout the remote shell kept running and the slot stayed busy for an
hour. A waiters counter now separates the cases: with a waiter the close
hands off, without one it erases the session and cancels IO at once.
WaitTermCommand's closed branch keeps a truncated tail pollable instead of
dropping it, cancelling IO immediately, and the drained poll cleans up.

The write side had the same hazard. exec_command, terminal_exec and
http_probe wrote the command line after the prompt wait without rechecking
the sub-connection; IsTermSubCtxLive now skips the write when the shell has
died, and WaitTerminalDone reports closed on every failure path so callers
never CancelIO a pointer that may be back in the pool.

list_hosts, read_file and http_probe were missing from kToolHints and got
destructive defaults; the first two are now read-only/idempotent, http_probe
stays writable because its method can mutate the probed service.

Verified on the isolated Debug instance: the truncated tail drains without
gaps (12514 lines), a waiterless close frees the slot in 0.1s, and the
terminal, exec_command, http_probe, 8a/8b/8c and verify_tools checks pass.

Co-Authored-By: deepseek-flash
2026-11-12 18:27:07 +01:00
yuanyuanxianganddeepseek-flash 5841f27df9 Feature(mcp): unify window and service controls behind one name per state
operate_window / host_control_window and control_service / host_control_service were two
implementations of the same intent. tools/list now exposes exactly one of each pair,
chosen by McpMachine: the host_control_* names when host management is enabled, the
main-connection names when it is not.

The advertised tool accepts the union of actions. host_control_window routes close/show
to the main-connection implementation, which stays the only path with close/show
semantics and requires McpManage; the machine path keeps its post-action verification
for restore/hide/maximize/minimize/activate. host_control_service routes
set_auto/set_manual the same way and rejects dry_run for them instead of pretending to
run one. Both old names remain callable aliases, and service_name is accepted as an
alias for the machine tool's name parameter.

The manifest generator treats the two main-connection tools as !machine entries, so the
two-capture union still covers both states. tools/list is 49 entries when everything is
on (was 51) and 47 when host management is off; the response shrinks from 193,008 B to
168,634 B (-12.6%), short of the 15% estimate because state-conditional tools must stay
in the manifest. The plan document records that measurement and the reason.

Verified with a dedicated two-state test: visibility matrix, close/show and
set_auto/set_manual routing through dry_run and validation paths, alias dispatch, and
-32006 for host_* names when host management is off. Step 8a/8b regressions and
verify_tools --live still pass.

Co-Authored-By: deepseek-flash
2026-11-12 17:40:51 +01:00
yuanyuanxianganddeepseek-flash c73db530f4 Feature(mcp): hide the degraded list_* tools when host management is on
host_inspect now covers processes, windows and services, so with
McpMachine=1 the older list_processes / list_windows / list_services
entries only competed with it: same intent, two names, two long
descriptions to read before choosing. They no longer appear in
tools/list while host management is enabled, but their names still
dispatch, so callers that cached them keep working.

They must stay visible when McpMachine=0: that is the default state and
the only way such a server can list processes, windows or services, so
the entries sit behind !IsMachineEnabled() rather than being removed.
list_network_connections is deliberately not folded in: it reads the
connection-manager view (IPv6 rows, killable flag, numeric state) which
host_inspect's IPv4-only network aspect does not provide.

tools.json is now generated from two captures, all-switches-on plus
McpMachine=0, because neither state contains the whole surface; the
off-state entries are marked gate "!machine" and verify_tools.py skips
them when comparing against an all-on server. tools/list went from 54
to 51 entries and from 183,336 B to 171,929 B (-6.2%).

Co-Authored-By: deepseek-flash
2026-11-12 17:28:28 +01:00
yuanyuanxianganddeepseek-flash 59f0f16f74 Feature(mcp): merge the ten host_list_* tools into host_inspect
The ten read-only host-management tools (host_list_processes, windows,
network_state, software, browser_history, favorites, win32_services,
driver_services, scheduled_tasks, host_get_hosts_file) each carried a
name, description and schema for what is one connection to the host,
one tab id per aspect and one paged list shape. Ten entries made
tools/list hard to scan and took a large share of the description
budget.

They are now one tool, host_inspect(aspects[], ...), where aspects is a
required, deduplicated array of the ten former names. A single aspect
returns exactly what the old tool returned (same builder, same code
path), so output is byte-identical; several aspects are fetched over
separate managed sessions and merged into results.<aspect>, with
failures isolated in errors.<aspect> and isError only when every aspect
failed. Filters (pid/name/arch/title/url/publisher/folder/status/
start_type/process/protocol/ports/state/max_bytes) are still applied
server-side before paging and are ignored by aspects they don't apply
to.

The old names stay as dispatch aliases so existing callers keep working
but no longer appear in tools/list; the platform table, batch read-only
list, tool hints, instructions, generator tables and the captured
mcp/tools.json move to the new name (63 tools -> 54).

The description also notes that win32_services / driver_services need
an elevated client: a non-elevated one cannot open SCM and never
answers, so the call times out after ~12 s.

Co-Authored-By: deepseek-flash
2026-11-12 17:21:36 +01:00
yuanyuanxianganddeepseek-flash cac5adaafc Docs(mcp): distinguish client runtime log from business app logs
get_client_log reads the YAMA client's own in-memory ring buffer, but its
description could easily be read as "the logs of whatever program runs on
the host". That misreading sends callers looking for business logs into
the wrong tool and back out empty-handed.

The description now opens by saying this is not the business program's
log, points at read_file with offset=-N for reading files on the host,
and states that this tool is for client/connection troubleshooting.
read_file's description gains the same explicit offset=-N hint at the
tail where log-reading is recommended.

Descriptions only - no behavior change. mcp/tools.json regenerated from
the live capture.

Co-Authored-By: deepseek-flash
2026-11-12 17:02:54 +01:00
yuanyuanxianganddeepseek-flash 88269df548 Feature(mcp): merge the three host-list tools into list_hosts
list_online_hosts, search_hosts and list_all_hosts differed only in
whether offline hosts were included and in which filter fields they
accepted, which made the host-list surface confusing and duplicated
three handlers over the same CollectAllHosts snapshot.

They now share one tool, list_hosts(query?, online?=true,
include_offline?=false, group?, os?, client_type?, limit?, offset?).
The old names stay as aliases routed to the same handler, so existing
callers keep working, but tools/list exposes only list_hosts. The
legacy "offline" boolean of list_all_hosts is still honored, and
list_all_hosts keeps its online+offline default.

With offline history included the list is now ordered online-first:
the host library holds thousands of records, so the default page of
100 would otherwise be all stale entries and the online hosts a caller
can actually operate on would be buried behind paging.

instructions, every id-description string, the platform table, the
tools.json generator and the captured mcp/tools.json are updated to
the new name (65 tools -> 63).

Co-Authored-By: deepseek-flash
2026-11-12 17:01:16 +01:00
yuanyuanxianganddeepseek-flash 613aa7291a Feature(mcp): add http_probe for private-network HTTP checks
Run an HTTP/HTTPS request inside a shell on a managed host and return a
structured result: status code, headers, body (UTF-8 or base64), size and
elapsed time, so interface health on the host or its subnet can be checked
without a full remote-control session.

The safety boundary is hard-coded on the server, not in the shell script:
only http/https and IP literals (or localhost); only loopback and private
ranges (127/8, ::1, 10/8, 172.16/12, 192.168/16) are accepted; redirects
are not followed; the body is capped at 64KB; TLS certificates are
verified. Domain names are refused on purpose - resolving them on the
server would probe the wrong network.

Windows runs a single-line PowerShell 2.0-compatible script based on
HttpWebRequest. Accept/User-Agent/Referer are mapped to their dedicated
properties because .NET rejects them through Headers.Add. Linux uses curl
with temp files.

Payloads cross the terminal channel as 56-character base64 chunks with a
declared byte length. ConPTY re-emits the boundary character of lines
wider than 80 columns, so single-line base64 arrives corrupted; the length
check converts any remaining loss into an explicit error rather than
silent garbage.

The tool reuses an existing persistent terminal session. Sessions it
creates itself are closed after the command and kept only when the probe
timed out while still running. Platform gating: Windows and Linux only.

Co-Authored-By: deepseek-flash
2026-11-12 16:52:17 +01:00
yuanyuanxianganddeepseek-flash 697044d84b Feature(mcp): add read_file for byte-accurate remote text reads
read_file fetches a single remote file through the existing V2 download
channel into a per-call temp directory, decodes it, and deletes the temp
files on every exit path. It returns the file size, detected encoding, EOL
style, total line count, the requested slice (negative offset counts from
the end), a truncation flag and the whole file's SHA-256.

Encoding auto-detection follows BOM -> UTF-8 validity -> GBK fallback, and
utf-8/gbk/gb18030/latin1 can be forced. Files above 2MB and directories are
rejected from the first chunk, so nothing is written to disk for them.
The tool is gated by McpFileTransfer only: it never writes to the remote
host, so it stays available in readonly mode.

The V2 receive path now serves both download_file and read_file.

Co-Authored-By: deepseek-flash
2026-11-12 16:11:27 +01:00
yuanyuanxianganddeepseek-flash 0378e96470 Feature(mcp): let terminal_exec open or reuse a session implicitly
terminal_exec no longer requires session_id. Given a command and no
session_id, it reuses the host's persistent terminal session or opens one
through the same path as terminal_open, and reports session_id, is_pty and
reused in the result so the caller can keep using it. Polling still
requires the session token.

terminal_open now returns the existing session with reused:true instead of
-32003 when one is already active. An implicitly created session is
invisible to the caller, so rejecting would silently lock the host's single
terminal slot and leave exec_command failing with a busy error. A session
that is still starting, or one owned by a one-shot exec_command, still
answers -32003.

The server instruction line that told models to always pair terminal_open
with terminal_close is updated accordingly.

Co-Authored-By: deepseek-flash
2026-11-12 16:01:13 +01:00
yuanyuanxianganddeepseek-flash 3fe3a11494 Feature(mcp): keep terminal sessions on timeout and allow output polling
terminal_exec used to destroy the persistent session on timeout, so long
commands (robocopy, upgrade scripts) could never be observed: the collected
output was thrown away and the shell was killed. Waiting is now decoupled from
the command:

- WaitTermCommand delivers [delivered, ...) and no longer erases on timeout.
  It returns done:false plus the output produced so far; the session stays
  busy and polling continues until done:true with exit_code.
- Calling terminal_exec with only session_id polls (no command); command is
  optional and the result gains session_id / done / truncated / dropped_bytes
  / elapsed_ms.
- Request cancellation still destroys the session (-32800 path); shell exit
  and terminal_close deliver the remaining output and then clean up.
- Chunks are capped at max_output_bytes (default 64KB, newline-aligned); the
  per-command buffer is capped at 8MB and reports dropped_bytes; busy sessions
  are force-reclaimed after an hour so a host cannot stay busy forever.
- A finished command with undrained output returns -32003 with a drain hint
  instead of silently losing it when the next command clears the buffer.

Verified on an isolated Debug instance against a Windows host: a 3s timeout on
an 8s ping returns done:false + partial output and two polls finish it; a
277KB dir listing needs 5 polls and then accepts a new command; 200 echo lines
delivered in 12 chunks arrive exactly once in order; cancel returns -32800 and
destroys the session. tools.json regenerated (63 tools, PASS).

Co-Authored-By: deepseek-flash
2026-11-12 15:53:33 +01:00
yuanyuanxianganddeepseek-flash b63c97c5eb Feature(mcp): allow sc qc/enumdepend/sdshow in default command whitelist
exec_command's read-only default whitelist only listed `sc query`, so service
configuration inspection was rejected even though `sc qc` is a read. Add
`sc qc`, `sc enumdepend` and `sc sdshow`; `sc start/stop/config/create/delete`
stay rejected because matching is prefix based, and a comment says so.

verify_tools.py --live now prints the tools/list response size plus the
description / inputSchema / outputSchema breakdown, so shrinking tools/list can
be measured against a running server.

Verified on an isolated Debug instance (port 6555, local test client): sc
qc/enumdepend/sdshow/query succeed; powershell, icacls, net user, net
localgroup, sc start and `&` chaining still return -32007/-32012; tools.json
still matches the live tools/list (63 tools, PASS).

Co-Authored-By: deepseek-flash
2026-11-12 15:41:23 +01:00
yuanyuanxianganddeepseek-flash f5ac7ba45f Docs: revise MCP tool optimization plan against measured baseline
The v1 plan was written without measuring the live server. Re-measure and fix
it against the code:

- tools/list response is 193,008 B (tools array 136,692 B; description 31,874 /
  inputSchema 44,192 / outputSchema 49,320), not 103,158 B; the >=15% goal now
  refers to this baseline.
- TermSession::sentPos is the sentinel offset, not a delivered cursor, so
  P0-2 introduces a real `delivered` cursor instead of reusing it.
- The whitelist additions icacls / net user / net localgroup are writes under
  prefix matching; only sc qc / enumdepend / sdshow qualify.
- "file too large" uses -32602, not the invented -32011 (destination write
  failure).
- P0-3 gains four prerequisites (size pre-check, McpFileTransfer gate, RAII
  cleanup, sha256/lines_total semantics); P0-1 spells out the default-session
  slot hazard; the stage order is P0-4 first since it is the cheapest win.

Appendix B records how the baseline was measured (verify_tools.py --live).

Co-Authored-By: deepseek-flash
2026-11-12 15:41:20 +01:00
yuanyuanxianganddeepseek-flash 23fb50b7d4 Build: add server-linux target for cross-compiling the Go server
`build server-linux` now builds the Go server as a Linux/amd64 binary at
Bin\server_linux_amd64 instead of the Windows YamaGo_x64.exe, so the
artifact can be copied to a Linux host as-is. It reuses the go-server
flow: web asset sync, Release builds strip with -s -w (debug keeps
symbols), and the caller's GOOS/GOARCH/CGO_ENABLED are restored
afterwards so a direct .\build.ps1 run does not leak the cross-compile
environment into later builds.

UPX compression is skipped for Linux output (the script only ships
upx.exe for the Windows build) and logs a warning instead.

Verified: the generated binary is a stripped static ELF that runs under
WSL and prints its flags.

Co-Authored-By: deepseek-flash
2026-11-12 11:42:27 +01:00
yuanyuanxianganddeepseek-flash 81f0d6c031 Fix(server,client): keep web terminal alive across heartbeat reconnects
The Go server answered TOKEN_HEARTBEAT with a 33-byte CMD_HEARTBEAT_ACK,
while the Linux and Android clients gate the ACK on 1 + sizeof(HeartbeatACK)
(1025 bytes) and silently drop anything shorter. Their application-level ACK
watchdog therefore never got fed and disconnected the main connection every
60s. Each re-login replaced the whole hub.Device, wiping the screen/shell
sub-conn bindings that ride their own TCP connections, so a web terminal kept
receiving shell output while every keystroke was dropped — the "terminal goes
unresponsive after a while" symptom — and the shell could no longer be torn
down (orphan bash + leaked sockets).

Clients now accept the 32-byte old ACK (Windows already did), and the server
sends the full 1024-byte struct. Hub.Register carries the sub-conn session
state across a re-login, and the disconnect cleanup is pinned to the
connection it belongs to so a stale OnDisconnect cannot tear down a
registration that has already replaced it. A shell sub-conn that can no
longer be bound now tells the viewer instead of leaving the pane waiting.

Verified on aa: RTT restored, zero "Heartbeat ACK timeout" lines, main-conn
port stable; Go build/vet/test pass. Server deploy to the Go host is still
pending, so un-upgraded clients will keep reconnecting until then.

Co-Authored-By: deepseek-flash
2026-11-12 11:03:57 +01:00
18 changed files with 5224 additions and 3122 deletions

No files matched your search

+9 -3
View File
@@ -1484,9 +1484,15 @@ int DataProcess(void* /*user*/, PBYTE szBuffer, ULONG ulLength)
}
case CMD_HEARTBEAT_ACK:
if (ulLength >= 1 + (ULONG)sizeof(HeartbeatACK)) {
HeartbeatACK ack;
memcpy(&ack, szBuffer + 1, sizeof(HeartbeatACK));
// 完整结构 1024 字节;老服务端 / Go 服务端只回 HeartbeatACK_OldSize(32)。
// 短包同样要喂 ACK 看门狗,否则每 60s 断开重连一次。Windows 端按
// min(ulLength, 32) 兼容(KernelManager.cpp:2413)。
if (ulLength >= 1 + (ULONG)HeartbeatACK_OldSize) {
HeartbeatACK ack = {};
const size_t copyLen = (ulLength - 1 >= sizeof(HeartbeatACK))
? sizeof(HeartbeatACK)
: (size_t)(ulLength - 1);
memcpy(&ack, szBuffer + 1, copyLen);
uint64_t now = GetUnixMs();
g_lastHeartbeatAckMs.store(now, std::memory_order_relaxed);
int64_t rtt = (int64_t)now - (int64_t)ack.Time;
+3 -1
View File
@@ -1,8 +1,9 @@
@echo off
:: SimpleRemoter Quick Build Script
:: Usage: build.cmd [release|debug] [x64|x86|all] [server|clean|publish|go-server|serverd|client]
:: Usage: build.cmd [release|debug] [x64|x86|all] [server|clean|publish|go-server|server-linux|serverd|client]
:: go-server Build Go fallback server only -> Bin\YamaGo_x64.exe
:: go-server publish Same, plus UPX --best compression
:: server-linux Cross-compile Go server for Linux -> Bin\server_linux_amd64
:: serverd Debug server only (x64) -> Bin\Yama_x64d.exe
:: client Debug client (x64) -> x64\Debug\ghost.exe
@@ -23,6 +24,7 @@ if /i "%~1"=="server" (set EXTRA_ARGS=!EXTRA_ARGS! -ServerOnly& shift& goto :par
if /i "%~1"=="clean" (set EXTRA_ARGS=!EXTRA_ARGS! -Clean& shift& goto :parse_args)
if /i "%~1"=="publish" (set EXTRA_ARGS=!EXTRA_ARGS! -Publish& shift& goto :parse_args)
if /i "%~1"=="go-server" (set EXTRA_ARGS=!EXTRA_ARGS! -GoServer& shift& goto :parse_args)
if /i "%~1"=="server-linux" (set EXTRA_ARGS=!EXTRA_ARGS! -GoServerLinux& shift& goto :parse_args)
:: Debug presets: serverd = debug server x64 only, client = debug ghost x64 only
if /i "%~1"=="serverd" (set CONFIG=Debug& set PLATFORM=x64& set EXTRA_ARGS=!EXTRA_ARGS! -ServerOnly& shift& goto :parse_args)
if /i "%~1"=="client" (set CONFIG=Debug& set PLATFORM=x64& set EXTRA_ARGS=!EXTRA_ARGS! -ClientOnly& shift& goto :parse_args)
+35 -9
View File
@@ -18,7 +18,8 @@ param(
[switch]$ClientOnly, # Only build the client executable (ghost), skip server
[switch]$Clean, # Clean before build
[switch]$Publish, # Publish mode: rebuild all deps + x64 Release + UPX compress
[switch]$GoServer # Build Go fallback server (server/go) -> Bin/YamaGo_x64.exe
[switch]$GoServer, # Build Go fallback server (server/go) -> Bin/YamaGo_x64.exe
[switch]$GoServerLinux # Cross-compile the Go server for Linux -> Bin/server_linux_amd64
)
$ErrorActionPreference = "Stop"
@@ -32,11 +33,16 @@ $upxPath = Join-Path $rootDir "server\2015Remote\res\3rd\upx.exe"
function Build-GoServer {
param(
[string]$Configuration,
[switch]$Compress
[switch]$Compress,
# "linux" cross-compiles an ELF binary from Windows (CGO off). Output
# name matches the ReadMe/Makefile convention so the artifact can be
# scp'd as-is.
[ValidateSet("windows", "linux")]
[string]$TargetOS = "windows"
)
Write-Host ""
Write-Host "Building Go server (server/go)..." -ForegroundColor Magenta
Write-Host "Building Go server (server/go) for $TargetOS..." -ForegroundColor Magenta
$goCmd = Get-Command go -ErrorAction SilentlyContinue
if (-not $goCmd) {
@@ -63,14 +69,27 @@ function Build-GoServer {
if (-not (Test-Path $binDir)) { New-Item -ItemType Directory -Path $binDir -Force | Out-Null }
$outFile = Join-Path $binDir "YamaGo_x64.exe"
$outFile = if ($TargetOS -eq "linux") {
Join-Path $binDir "server_linux_amd64"
} else {
Join-Path $binDir "YamaGo_x64.exe"
}
# Release strips debug info for smaller binary; Debug keeps symbols.
$ldflags = if ($Configuration -eq "Debug") { "" } else { "-s -w" }
# Save the caller's Go env so a direct .\build.ps1 invocation does not
# leave GOOS=linux behind for later builds in the same shell.
$oldGoos = $env:GOOS
$oldGoarch = $env:GOARCH
$oldCgoEnabled = $env:CGO_ENABLED
Push-Location $goDir
try {
$env:GOOS = "windows"
$env:GOOS = $TargetOS
$env:GOARCH = "amd64"
# Cross-compiling for Linux requires a pure-Go build; the server has
# no cgo dependencies, so this is the normal configuration.
if ($TargetOS -eq "linux") { $env:CGO_ENABLED = "0" }
if ($ldflags) {
& go build -ldflags $ldflags -o $outFile ./cmd
} else {
@@ -79,6 +98,9 @@ function Build-GoServer {
$code = $LASTEXITCODE
} finally {
Pop-Location
$env:GOOS = $oldGoos
$env:GOARCH = $oldGoarch
$env:CGO_ENABLED = $oldCgoEnabled
}
if ($code -ne 0) {
@@ -92,7 +114,9 @@ function Build-GoServer {
# In-place UPX compression. Failure is a warning, not an error — the
# uncompressed binary is still usable, and UPX occasionally refuses on
# certain PE sections.
if ($Compress) {
if ($Compress -and $TargetOS -ne "windows") {
Write-Host "WARNING: UPX compression is skipped for $TargetOS output (script ships upx.exe only for the Windows build)." -ForegroundColor Yellow
} elseif ($Compress) {
Write-Host ""
Write-Host "UPX compressing Go server..." -ForegroundColor Magenta
if (-not (Test-Path $upxPath)) {
@@ -114,9 +138,11 @@ function Build-GoServer {
}
# Go-only fast path: skip MSBuild entirely. -Publish here means "compress the
# Go binary too" (not the full C++ publish flow).
if ($GoServer) {
$ok = Build-GoServer -Configuration $Config -Compress:$Publish
# Go binary too" (not the full C++ publish flow). -GoServerLinux cross-compiles
# the same server for Linux into Bin\server_linux_amd64.
if ($GoServer -or $GoServerLinux) {
$targetOS = if ($GoServerLinux) { "linux" } else { "windows" }
$ok = Build-GoServer -Configuration $Config -Compress:$Publish -TargetOS $targetOS
if (-not $ok) { exit 1 }
exit 0
}
+576
View File
@@ -0,0 +1,576 @@
# MFC MCP 工具优化方案(基于 ASM 工位实操数据)
> 版本:v2(2026-11-12 评审后修订) 状态:待评审 日期:2026-11-12
>
> v1 → v2 的实质修正(均以代码/实测为准,修订处在段首标「v2」):
> `tools/list` 基线改为实测 193,008 字节(v1 的 103,158 对不上任何历史版本);
> P0-2 的前提「`sentPos` 是已发送偏移」不成立(它是哨兵在 `data` 中的位置),并补齐
> 调用方 `CancelIO`、取消/超时分离、输出上限、busy 兜底四处实现细节;P0-4 白名单
> 剔除 `icacls` / `net user` / `net localgroup`(三者在带参数时是写命令);P1-2 说明
> 其实现仍需走 shell;P1-1/P2 的别名方案补齐平台表、instructions、网站页面等同步项。
>
> 数据来源:2026-11-12 一次完整的 7 机 ASM 工位故障处理 + 批量配置会话。
> 该会话共 **186 次 MCP 调用**,63 个工具里实际用到 **9 个**。本文所有使用频次、
> 命令分类、失败码都来自该会话的调用记录逐条统计,不是推断;凡属推断的地方会标注。
>
> 前置文档:`Mcp_Design.md`(协议/错误码)、`Mcp_Terminal_Design.md`(持久终端)、
> `Mcp_Next_Plan.md`(P10 起的能力扩展)、`Mcp_Machine_Design.md`(会话抽象)。
---
## 0. 结论摘要
1. **工具不缺,粒度不对。** 186 次调用里 109 次(58.6%)是 `terminal_exec`;按命令分类,
118 条里有 59% 是「读」(读文件/日志 37%、查服务状态 14%、查注册表 4%、列目录 4%),
这部分全部压在 `terminal_exec` 上;同时有 **30 个纯只读工具零调用**。原因是专用工具
一个标签页一个、粒度太细,而真实故障处理是「一条命令拿三样东西」。
2. **最大的单点浪费是会话管理。** `terminal_open` 20 次 + `terminal_close` 17 次 = **37 次调用(20%)**,
零信息产出。其中 9 个会话只跑了 1 条命令,即 3 次调用换 1 条命令。
3. **`terminal_exec` 超时会销毁会话,这是设计错误。** 命令超时说明进程可能还在跑,
此时丢掉 shell 恰好毁掉全部现场(cwd、环境变量、后台任务)。本次两次 `-32002`
都由此产生,每次都要重开会话并重跑命令。
4. **`read_file` 是唯一真正的功能缺口。** 读文件靠 `type`(`exec_command`,5 次)和
`Get-Content`/`Select-String`(`terminal_exec`,39 次),`.env` 对比还得 `download_file`
落盘再本地解析。而「读」正是最高频的需求。
5. **`exec_command` 的命令白名单在拦只读命令。** `sc qc AssemblyManager` 被拒(`-32007`),
而 109 次不受白名单约束的 `terminal_exec` 畅通无阻——这个安全门在当前用法下不产生保护,
只产生摩擦。根因是 `powershell` 完全不在白名单里,任何 PowerShell 一行都过不去。
---
## 1. 实测数据
### 1.1 工具使用分布(186 次调用 / 63 个工具)
| 调用数 | 工具 | 占比 |
|---:|---|---:|
| 109 | `terminal_exec` | 58.6% |
| 20 | `terminal_open` | 10.8% |
| 17 | `terminal_close` | 9.1% |
| 10 | `list_files` | 5.4% |
| 9 | `exec_command` | 4.8% |
| 7 | `get_screenshot` | 3.8% |
| 7 | `download_file` | 3.8% |
| 4 | `upload_file` | 2.2% |
| 3 | `search_hosts` | 1.6% |
**未调用 54 个,其中 30 个是纯只读**(`write=false && manage=false`)。30 个里有 26 个是
主机/服务端枚举类,另 4 个是 `chat_*`:
```
list_online_hosts list_all_hosts get_host_detail get_activity_history
get_foreground_window get_client_log get_keylog get_audit_log get_server_status
mcp_list_sessions mcp_cancel_session
list_processes list_windows list_services list_registry list_network_connections
host_list_processes host_list_windows host_list_network_state host_list_software
host_list_browser_history host_list_favorites host_list_win32_services
host_list_driver_services host_list_scheduled_tasks host_get_hosts_file
```
### 1.2 命令用途分布(118 条:109 条 `terminal_exec` + 9 条 `exec_command`)
| 目的 | 条数 | 占比 |
|---|---:|---:|
| 读文件 / 日志 | 44 | 37% |
| HTTP 探测本机 8003 | 25 | 21% |
| 查服务状态 | 17 | 14% |
| 其他 | 14 | 12% |
| 跑脚本 | 5 | 4% |
| 查注册表 | 5 | 4% |
| 列目录 | 5 | 4% |
| 查进程 | 2 | 2% |
| 写 / 复制 | 1 | 1% |
注意最后一行:**整场只有 1 条写命令(1%)**。危险操作占比极低,但权限模型把它和只读操作
混在同一档。
### 1.3 失败与超时
| 错误码 | 次数 | 场景 |
|---|---:|---|
| `-32002` | 2 | 命令超时/取消 → **会话被销毁** |
| `-32001` | 1 | `Timeout waiting for command output` |
| `-32007` | 1 | `sc qc AssemblyManager` 被白名单拒 |
| `-32009` | 2 | `download_file` 路径不存在(ASM-07 未装 ASM,属环境问题非工具问题) |
**真实失败率 6/186 = 3%**。工具稳定性没有问题,问题在效率和语义。
另有 **9 组完全重复的命令**(重复 `sc query`、重复 `Restart-Service`、重复 grep 日志),
全部是超时后重试——修掉 §2.2 后自然消失。
### 1.4 会话开销
- 20 次 `terminal_open` vs 17 次 `terminal_close` → **3 个会话没关**
- 会话粒度分布:19/16/13/11/9/7/7/6/5/4/3/1/1/1/1/1/1/1/1/1 条命令
(20 个会话、合计 109 条,与 §1.2 的 109 条 `terminal_exec` 自洽)
→ **9 个会话只跑了 1 条命令**
- 109 次 `terminal_exec` 里 **41 次(38%)显式传了 `timeout_ms`**
- 命令长度中位数 349 字符,最长 1302 字符;74 条命令含 ≥2 个分号(手工串联)
### 1.5 上下文成本
**v2 修订(实测)**:对运行中的服务端发一次 `tools/list`(只读请求,测法见附录 B),
响应 **193,008 字节**,其中 tools 数组本身 136,692 字节:
| 组成 | 字节 |
|---|---:|
| description 合计 | 31,874 |
| inputSchema 合计 | 44,192 |
| outputSchema 合计 | 49,320 |
按中英混合粗估 **40k–60k tokens**,每次会话建立 `tools/list` 都要付一遍;其中 30 个
零调用的只读工具贡献了相当一部分。
两个陷阱:
1. **不能拿 `mcp/tools.json` 当基线**——它是 222,803 字节的文件,且 `make_tools_json.py`
额外追加了 `_readme` / `gate` / `platforms` / `impl` 等**线上响应里没有**的元信息。
2. v1 写的 103,158 字节对不上任何历史版本(近 8 个提交的 `mcp/tools.json` 都在
217–223KB),应作废。
---
## 2. 五个问题(带代码位置)
### 2.1 会话管理占 20%,且没有「无会话执行」通道
**根因**:`BuildTerminalExec`(`McpServer.cpp:4920`)把 `session_id` 设为必填:
```
4932: std::string sessionId = GetStringArg(args, "session_id");
4933: if (sessionId.empty())
4934: return BuildError(id, -32602, "Missing required parameter: session_id");
```
要跑一条命令就必须先 `terminal_open`,跑完还要 `terminal_close`(否则靠
`kTermIdleTimeoutSec = 300`(`McpServer.cpp:4673`)五分钟回收)。一次性任务因此固定付
2 次额外调用。
### 2.2 超时销毁会话(设计错误)
**根因**:`WaitTermCommand`(`McpServer.cpp:10949`)在等待未命中时无条件销毁(`10958` 起):
```cpp
if (!signaled) { // 超时/取消 → 清理会话+路由
context* subCtx = it->second.subCtx;
MarkTermDestroyedLocked(device_id, it->second.sessionId,
McpCallCancelled()
? "Terminal session was destroyed because the request was cancelled; ..."
: "Terminal session was destroyed after this command timed out (waited "
+ std::to_string(timeoutMs) + " ms); call terminal_open again");
m_TermContextToDevice.erase(subCtx);
m_TermSessions.erase(it);
return false;
}
```
超时意味着「本次调用不愿再等」,**不意味着「命令失败了」**。`robocopy` 搬 30MB、
`Wait-AsmReady 180` 这类命令必然超时,但它们还在正常跑。此时 `erase(it)` 把
`subCtx`、已收集的 `data`、`sentPos` 全扔了。
**v2 更正:`sentPos` 不是「已发送偏移」。** 它是**哨兵在 `data` 中的位置**
(`McpServer.h:820` 注释;`McpServer.cpp:10768` 由 `FindSentinel` 写入),成功分支用它
把输出**截断到哨兵之前**,并不记录「已经交给调用方多少字节」:
```
10989: if (it->second.sentPos <= it->second.data.size())
10990: out.assign(it->second.data.begin(), it->second.data.begin() + it->second.sentPos);
```
而且 `BeginTermCommand` 在每条新命令开始时 `data.clear(); sentPos = 0`(`10925-10926`)。
所以「增量回传」需要新增一个真正的交付游标,见 P0-2。
另外,超时路径的问题不止少了一个游标:调用方在 `WaitTermCommand` 返回 false 后
**立即 `subCtx->CancelIO()`**(`McpServer.cpp:4999`),shell 进程随即退出。只改
`WaitTermCommand` 而不改这一行,会话即使留着也是死壳。
### 2.3 默认超时与真实任务不匹配
`McpToolTimeoutMs` 默认 **20000ms**(`McpServer.h:968`),上限 600000(`McpServer.h:541`)。
本次 38% 的调用要手工调大。升级脚本、服务重启、包复制都超过 20 秒。
顺带:`McpServer.h:541` 的注释写的是「调到 60s 更实用」,但成员初始值仍是 20000,
`2015RemoteDlg.cpp:2588` 读 ini 的缺省值也是 20000——注释与代码不一致,实现时统一。
### 2.4 没有 `read_file`
现状三条路都不合适:
| 路径 | 问题 |
|---|---|
| `exec_command` + `type` | 白名单里有 `type`,但只能整文件输出,无法分页;GBK 文件直接乱码 |
| `terminal_exec` + `Get-Content` | 要开会话、要处理引号转义、编码不可控、输出混着提示符回显 |
| `download_file` 落盘再读 | 3.6KB 的 `.env` 也要走完整 V2 传输 + 主控落盘 + 本地解析 |
`download_file` 在本次用了 7 次且 0 失败,说明**服务端作为 V2 接收端已经可用**——
这是实现 `read_file` 的现成基础(见 §3 P0-3)。
### 2.5 白名单在拦只读命令
**根因**:`kDefaultCmdWhitelist`(`McpServer.cpp:3817`):
```cpp
"dir,type,cd,chdir,ver,hostname,whoami,where,tasklist,systeminfo,ipconfig,netstat,"
"path,set,find,findstr,reg query,sc query,"
"ping,tracert,nslookup,getmac,driverquery,query,gpresult,"
"arp -a,route print,schtasks /query";
```
- 有 `sc query`,**没有 `sc qc`** → 本次被拒(`McpServer.cpp:4115`)
- **`powershell` 完全不在表里** → 任何 PowerShell 一行都过不去,这才是根因。
本次 9 次 `exec_command` 里 5 次是 `type`、3 次是 `sc query`/`sc qc`、1 次 `whoami`,
全是 cmd 内置;所有需要 PowerShell 的都改走不受约束的 `terminal_exec`。
白名单用前缀匹配(`IsCommandAllowed`,`McpServer.cpp:3862`),所以补 `sc qc` 是一行的事。
但补 `powershell` 等于放开一切,必须单独评审。
---
## 3. 优化方案
### P0-1 `terminal_exec` 允许不带 `session_id`
**改法**:`session_id` 从必填改为可选。
```
terminal_exec(id, command?, session_id?, timeout_ms?)
```
- 给 `command` + 不给 `session_id`:复用该 host 的「默认会话」;不存在则内部走
`terminal_open` 的同一路径建一个,**不对外暴露 open/close**。
- 默认会话与普通会话同受 `kTermIdleTimeoutSec = 300` 回收,无需新的回收逻辑。
- 输出新增 `session_id` 与 `reused: true|false`,让调用方能判断是否可继续复用。
- 现有调用全部带 `session_id`,行为不变;`session_id` 写错仍返回 `-32002`。
**影响**:本次 37 次 open/close 里,至少 9 个单命令会话(27 次调用)可压到 9 次,省 18 次。
批量配置那类「每台 6 次」的流程可压到每台 2–3 次。
**风险**:与 `-32003 Device busy` 的交互。默认会话正在跑别的命令时,仍应返回 `-32003`
而不是排队——排队会让调用方无从判断要等多久。
**风险 2(v2 补充):默认会话会悄悄占住整台主机的终端槽。** `m_TermSessions` 每设备
只有一条,`BeginTermPending` 在已有会话时直接拒绝(`McpServer.cpp:10792`),所以自动创建
的默认会话会让后续 `exec_command` 和用户主动的 `terminal_open` 都报 `-32003`,而调用方
看不到任何显式会话。处理方式:`terminal_open` 撞上默认会话时**返回该 session_id
(`reused: true`)而不是报错**,并在它的 description 里写明这一点。
**验收**:同一 host 连续 3 条命令,调用序列为 3 次 `terminal_exec`,无 open/close。
### P0-2 超时改为「返回部分输出 + 可继续轮询」,不销毁会话
**改法**:`WaitTermCommand`(`McpServer.cpp:10949`)的超时分支(`10958`)不再 `erase`,
并补齐 v1 漏掉的实现细节。
超时后:
1. 保留 `m_TermSessions` 条目,`busy` 保持 `true`(命令确实还在跑)
2. 把已收集的 `data` 从**新增的交付游标 `delivered`** 起返回(v1 误以为 `sentPos` 是
这个游标,实际它是哨兵位置),返回后 `delivered = data.size()`
3. 返回**成功**结果:`isError:false` + `{session_id, done:false, output, elapsed_ms}`。
`BuildError` 只能产出 `{error:{code,message}}`(`McpInternal.cpp:83`),错误响应里没有
`structuredContent`,模型侧也会按失败处理——「超时但命令还在跑」不该是错误
4. 不必新增 `overdue` 字段:`SweepIdleTerminals` 本来就跳过 `busy` 会话(`11026`)
继续取输出的方式:**同一个工具,只传 `session_id` 不传 `command`**,进入 wait 模式:
- 再次等待,命中哨兵则返回增量 + `done:true` + `exit_code`
- 再次超时则继续返回增量 + `done:false`,不销毁
**v2 必须同时改的三处**:
- **调用方不再杀 shell**:`BuildTerminalExec` 在 `WaitTermCommand` 返回 false 后调用
`subCtx->CancelIO()`(`4999-5000`),必须改成只在「真正失败」时取消;超时保留路径不取消。
- **取消与超时分开**:`McpCallCancelled()` 为真表示处理线程已经走了、不会有人再来轮询,
必须照旧销毁(与 `-32800` 的语义一致);只有真超时才保留。
- **输出上限**:`TermSession::data` 现在无界(全仓没有上限常量)。轮询设计下
`robocopy` / `tail -f` 能堆到 MB 级,而工具结果本身也有客户端上限(`get_client_log`
的注释已踩过这个坑,`McpServer.cpp:4243`)。需要:每次返回截到 `max_output_bytes`
(默认 64KB,带 `truncated:true`);给 `data` 一个硬上限(如 8MB),达到后停止收集
并追加标记;`delivered` 只前进不后退,丢弃的字节数要如实上报。
**v2 补充:busy 会话的最大存活时间。** `SweepIdleTerminals` 只回收 `!busy`(`11026`),
调用方超时后再也不轮询时,该主机的 `-32003` 会永久不消失。需要 `busySince` 兜底
(如 1 小时)强制清理,或让 `terminal_close` 能强杀 busy 会话。
**为什么不开新工具**:`terminal_poll` 之类会让工具数 +1,用参数形态区分(有无 `command`)
即可,且与 P0-1 天然一致。
**兼容性**:现有调用都传 `command`,走原路径。`command` 从必填改为「与 `session_id` 二选一」。
注意 `data` 在 `BeginTermCommand` 里被 `clear()`(`10925`),所以下一条带 `command` 的调用
必须先确认上一条输出已取完,否则会静默丢输出——建议上一条 `done` 但未取完时返回 `-32003`
并提示先轮询。
**验收**:跑一条 90 秒的命令,`timeout_ms=20000`,连续轮询 5 次后拿到完整输出与退出码,
会话未被销毁;`delivered` 单调递增、无重复无丢失;中途取消(`-32800`)后会话被销毁;
不再轮询时,该主机的终端槽在 busy 兜底时间后释放。
### P0-3 新增 `read_file`
```
read_file(id, path, offset?=0, limit?=2000, encoding?="auto", max_bytes?=262144)
```
返回:
```json
{ "path": "...", "size": 3792, "encoding": "utf-8", "eol": "crlf",
"lines_total": 72, "offset": 0, "lines_returned": 72, "truncated": false,
"text": "...", "sha256": "..." }
```
- `offset` 支持负数(`-200` = 最后 200 行),覆盖「看日志尾部」这个最高频场景
- `encoding: auto` 按 BOM → UTF-8 合法性 → GBK 回退探测;显式可传 `utf-8`/`gbk`/`latin1`
- 单次上限 256KB,超出按 `truncated: true` 截断并给 `lines_total`
**第一阶段实现(客户端零改动)**:复用 `download_file` 的 V2 通道把文件拉到
`<服务端数据目录>\mcp\tmp\<device_id>\`,读完即删。理由:本次 7 次 `download_file` 全部成功,
说明服务端作为 V2 接收端已可用;新增客户端命令的成本远高于收益。
**第二阶段**(可选):新增 `COMMAND_READ_FILE` 走内存,省掉落盘。
**v2 补充的四个前提**:
- **先看大小再下载**:`download_file` 是「整文件落到服务端磁盘」(默认 600s 超时),一个
2GB 日志会先占满主控磁盘。V2 的元数据到达后先判 `size > max_bytes`(默认 2MB)就直接
返回 `-32602`(附「改用 download_file」提示)并 `CancelIO`,不要开始传输。不新增错误码
——`-32011` 已被「目标写入失败」占用。
- **开关与平台门**:依赖 V2,必须 `McpFileTransfer=1` 且客户端 `SupportsFileV2`
(否则 `-32006`);只读模式下是否放行要明确(建议放行,它不写远端)。
- **临时目录清理**:用 RAII 覆盖成功/超时/取消/异常四条路径。`devId` 是 `uint64_t`,
拼路径没有注入风险;但并发调用共用文件传输槽(`BeginFileTransferPending`),会 `-32003`。
- **`sha256` 与 `lines_total` 的语义**:`sha256` 是**整个文件**的哈希(不是返回片段的);
`lines_total` 需要完整解码,`offset=-N` 也依赖它,所以第一步仍然是完整取回。
**为什么值得单开工具而不并入 `exec`**:本次 `.env` 事故就是「用 shell 改配置文件」的
典型翻车——PowerShell 的 `.Split($nl)` 绑到 `Split(char[])`,把 72 行拆成 144 行。
读侧同理:`type` 出来的 GBK 是乱码、`Get-Content` 会把行尾归一化。
字节级的读接口把编码、行尾、引号这三类坑一次性绕开。
**验收**:读一份 87 行、含 GBK 字符、CRLF 行尾的配置文件,`lines_total` 与
`Get-Content | Measure-Object -Line` 一致,`sha256` 与 `certutil -hashfile` 一致。
### P0-4 白名单补齐只读动词
**最小改动(推荐先做)**:在 `kDefaultCmdWhitelist` 补只读项
```
sc qc, sc enumdepend, sc sdshow
```
`sc qc` 是本次被拒的那条,属明确的漏项。
**v2 更正:`icacls` / `net user` / `net localgroup` 不能加。** 这三项都是「只读用法之外
还有写用法」,而 `IsCommandAllowed` 是**前缀匹配**(`McpServer.cpp:3862`),无法区分:
- `icacls X /grant everyone:F` 改 ACL
- `net user bob pwd /add` 建本地账号;`net localgroup administrators bob /add` 提权
- `whoami /priv` 已被现有 `whoami` 前缀覆盖,加了是冗余
要在 `exec_command` 里做这三类查询,只能等参数级过滤(白名单项 + 参数正则),那是另一个
改动面,不要混进本次。
**关于 `powershell`**:不建议直接加入白名单——那等于放开一切,且与 `exec_command`
「只读白名单」的定位矛盾。真正需要 PowerShell 的场景应通过 P0-3 的 `read_file` 和
P1-2 的 `http_probe` 覆盖掉。若后续确有需要,应另立 `kDefaultCmdWhitelistPS`,
对 `Get-*` 只读动词做 cmdlet 级白名单,并单独安全评审。
**验收**:`sc qc <svc>` 返回 `-32007` 消失;`powershell -Command ...` 仍被拒。
### P1-1 合并三个主机列表工具
`list_online_hosts` + `search_hosts` + `list_all_hosts` → `list_hosts`。
本次 `search_hosts` 用了 3 次,另两个各 0 次。三者的差异只在「是否含离线」,
用参数即可表达:
```
list_hosts(query?, online?=true, include_offline?=false, group?, os?, client_type?, limit?, offset?)
```
旧名保留为别名(同一 handler,`tools/list` 只暴露 `list_hosts`),避免破坏现有调用方。
### P1-2 新增 `http_probe`
本次 **25/118 条命令(21%)** 是手写 `Invoke-WebRequest http://127.0.0.1:8003/...`,
每条都要处理 `-UseBasicParsing`、`-TimeoutSec`、引号转义、JSON 解析。
```
http_probe(id, url, method?="GET", headers?, body?, timeout_ms?=10000, max_bytes?=65536)
```
**实现路径(v2 补充)**:没有客户端 HTTP 命令,这个工具只能**在 shell 里执行**:Windows 拼
`Invoke-WebRequest`(PTY 会话),Linux/macOS 用 `curl`。也就是说它仍然依赖 exec/terminal 的
通道、会占终端槽,并要分别维护两种平台的命令模板与输出解析(`-UseBasicParsing`、超时、
编码、JSON/非 JSON 两种返回)。客户端仍然零改动,但工作量不是「新增一个 handler」,
验收要覆盖两个平台。
**安全边界(必须硬编码,不可配置)**:
- 只允许 `http` / `https`
- **只接受 IP 字面量**(外加 `localhost` 特判)。校验在执行侧完成:请求是在**被管主机**上
发出的,服务端解析域名得到的是服务端自己的 DNS 结果,对目标主机没有意义;接受任意域名
等于校验形同虚设。允许 `127.0.0.0/8`、`::1`、`10/8`、`172.16/12`、`192.168/16`,其余拒绝
- 不跟随跨网段重定向;响应体上限 64KB
说明:被管主机本来就能跑任意命令,所以这不是严格意义上的 SSRF 跳板;限制私网段的价值在于
防止「用一条错误 URL 把主机当代理去打别处」,顺带避免误用。
**价值**:把「探本机业务健康」从「写一段 PowerShell」变成一次结构化调用,直接消掉 21% 的命令量。
### P1-3 `get_client_log` 的语义澄清
`get_client_log` 的描述(`McpServer.cpp:2265`)写的是「**YAMA 客户端的内存运行日志**
(客户端 ring buffer)」。本次需要的是**被管业务程序的日志**
(`C:\ProgramData\AssemblyManager\logs\assembly_manager.log`),两者完全不同。
建议不改名(改名破坏兼容),只做两件事:
1. 在 `get_client_log` 描述开头加一句「这不是被管业务程序的日志;读业务日志用 `read_file`」
2. 在 `read_file` 描述里点明「看日志尾部用 `offset=-N`」
### P2-1 合并 `host_list_*` 十个工具
十个 `host_list_*` 是「主机管理」各标签页的一一映射,本次零调用。
```
host_inspect(id, aspects[]) // processes|windows|network|software|browser_history|
// favorites|win32_services|driver_services|
// scheduled_tasks|hosts_file
```
旧名保留为别名。同时把与之重复的 `list_processes` / `list_windows` / `list_services` /
`list_network_connections` 一并折叠进来。
### P2-2 六对语义重复的工具
| 快捷版 | 主机管理版 | 建议 |
|---|---|---|
| `list_processes` | `host_list_processes` | 并入 `host_inspect` |
| `list_windows` | `host_list_windows` | 并入 `host_inspect` |
| `list_services` | `host_list_win32_services` | 并入 `host_inspect` |
| `list_network_connections` | `host_list_network_state` | 并入 `host_inspect` |
| `operate_window` | `host_control_window` | 保留一套,另一套做别名 |
| `control_service` | `host_control_service` | 保留一套,另一套做别名 |
对模型来说两套实现是纯噪音:同一个意图有两个工具名,选哪个要靠读两段长描述。
### P2-3 `tools/list` 体积
当前 **193,008 字节**(约 40k–60k tokens,实测口径见 §1.5 / 附录 B)。按上面合并估算:
| 改动 | 工具数变化 |
|---|---:|
| 三个主机列表 → `list_hosts` | −2 |
| `host_list_*` 十个 → `host_inspect` | −9 |
| 四个 `list_*` 折叠进 `host_inspect` | −4 |
| 两对控制类工具各留一 | −2 |
| **合计** | **63 → 46** |
**v2 更正**:v1 的「约降 27%」是按错误的 103KB 基线算的。按实测基线(193,008 B)看,
outputSchema 占 49,320 B 且合并后要保留,被删掉的主要是 17 个工具的 description +
inputSchema,乐观估计降 25–35KB(**约 −15%**)。实际值以改动后用附录 B 的方法重测为准。
**实测结果(2026-11-12,P2-1/2 落地后)**:开启全部开关时 `tools/list` 响应
**168,634 B / 49 个工具**,较基线降 24,374 B(**−12.6%**),未达到 15%。原因是清单
必须同时描述两种开关状态:`list_processes` / `list_windows` / `list_services` /
`operate_window` / `control_service` 在 McpMachine=0 时是唯一可用路径,因此以
`gate: "!machine"` 留在清单里(见 P2-4),所有状态下的实际列表都是 49 或 47 个,
到不了估算里的 46。若还要再降,只有两条路:删掉降级路径(关掉主机管理就失去列进程/
窗口/服务的能力)或压缩 description/outputSchema 正文——两者都不建议为凑 15% 去做。
### P2-4 别名/合并的同步项(v2 新增)
「旧名保留为别名、`tools/list` 只暴露新名」听起来只是一张别名表,但工具名在服务端还有
五处硬编码的消费点,漏一处就是静默降级:
| 位置 | 漏掉的后果 |
|---|---|
| `kToolPlatforms`(`McpServer.cpp:10251`) | `CheckToolPlatform` 查不到名字就**放行**(`10420`),别名会绕过平台门禁 |
| `IsBatchReadOnlyTool`(`McpInternal.cpp:594`) | 旧名走 `ids[]` 批量调用会被拒 |
| `McpMachine::Handles` / `CollectTargetReqs` | `host_list_*` 族走独立分派,改名后分派不到 |
| `kServerInstructions`(`McpServer.cpp:283` 起) | §4/§5 正文点名 `terminal_open`/`exec_command`/`host_list_processes`,模型会指向不存在的工具 |
| 文档与清单 | `mcp/tools.json` 需重新生成(`make_tools_json.py`),`check_platform_table.py` / `verify_tools.py` 回归,网站 MCP 页(v1.4.2 那套 11 组)同步 |
建议把「改名/合并」单独作为一次提交,别名在分派层保留一个版本,下个版本再删。
---
## 4. 明确不做(数据不支持)
| 不做 | 理由 |
|---|---|
| 改 `download_file` / `upload_file` / `get_screenshot` | 本次 0 失败、调用顺畅,没有证据支持改动 |
| 动 `remote_*` / `chat_*` | 本次零调用,无使用数据,改了也无从验证 |
| 直接放行 `powershell` | 等于白名单失效,须单独安全评审(见 P0-4) |
| 加 `secret_ref` 机制 | 属 Go 侧多租户需求;MFC 是单主控单用户,没有对应场景 |
| 新客户端命令 `COMMAND_READ_FILE` | 第一阶段用 `download_file` 复用即可,不值得为省落盘改客户端 |
| 砍掉写操作工具的权限门 | 本次只有 1 条写命令,但那是任务性质决定的,不是风险消失 |
---
## 5. 对 Go 侧最小工具集的影响
本次讨论同时确认了 Go 侧的最小工具集,两者共享同一批结论:
1. **P0-1 / P0-2 / P0-3 同时是 Go 侧的前置结论**:Go 侧 `hub` 已有 PTY 终端子连接
(`COMMAND_SHELL` → `TOKEN_TERMINAL_START`),但没有一次性执行的输出收集器,
也没有文件读写。MFC 侧这三项的实现路径可以直接复用。
2. **并发约束两边一致**:MFC 用 `-32003 Device busy` 保证每 host 单终端会话;
Go 侧 `hub.go` 注释写明 *at most one web terminal per device (MVP constraint shared
with the C++ server)*。Go 侧多用户场景下这个约束需要显式排队或租约,MFC 侧单用户则不必。
3. **命名对齐**:MFC 若落地 `read_file` / `http_probe`,Go 侧沿用同名同参数,
使同一句提示词在两个后端都能跑通。
4. **Go 侧不需要 MFC 的接口**:主机分享是客户端双宿(`COMMAND_SHARE(59)` +
`SHARE_TYPE_YAMA`,载荷 `ip:port[:shine[:transport]]`),Go 是与 MFC 同级的服务端,
不是下游消费者。详见 `common/host_share.h`。
---
## 6. 施工顺序与验收
| 序 | 项 | 改动面 | 客户端 | 预估收益(按本次数据) |
|---:|---|---|---|---|
| 1 | P0-4 白名单补 `sc qc`/`sc enumdepend`/`sc sdshow` | `McpServer.cpp:3817` 一行 | 零 | 消除 `-32007` 误拒 |
| 2 | P0-2 超时不销毁 + 轮询 | `WaitTermCommand` + 调用方 CancelIO + `delivered` 游标 + 输出上限 | 零 | 消除 2 次 `-32002`、9 组重试 |
| 3 | P0-1 免会话执行 | `BuildTerminalExec` 参数校验 + 默认会话 + `terminal_open` 复用 | 零 | −18 次调用(9.7%) |
| 4 | P0-3 `read_file` | 新增 handler,复用 V2 接收端 | 零 | 覆盖 44/118 条读命令 |
| 5 | P1-2 `http_probe` | 新增 handler(内部走 shell,Windows/POSIX 两套模板) | 零 | 覆盖 25/118 条命令 |
| 6 | P1-1 合并列表工具 | 别名 + 平台表 + `tools/list` 收敛 | 零 | −2 工具 |
| 7 | P1-3 描述澄清 | 两处 description | 零 | 减少误选 |
| 8 | P2-1/2/3/4 合并与收敛 | 别名表 + 清单生成 + instructions + 网站 | 零 | 63 → 46 工具 |
**顺序说明(v2)**:P0-2 排在 P0-1 之前——它会改动 `terminal_exec` 的会话形态(新增
`delivered`/`busySince` 状态),P0-1 的默认会话直接复用同一套状态,反过来做要改两遍。
**全部八项都不需要改客户端。** 这是本方案最重要的性质——所有收益都来自服务端。
**整体验收标准**:用同一套 ASM 工位任务重跑一遍,目标:
- MCP 调用总数从 186 降到 **110 以内**
- `terminal_open` / `terminal_close` 降到 **各 3 次以内**
- `timeout_ms` 手工覆盖次数从 41 降到 **10 以内**
- 零 `-32002`(会话被销毁);超时后能轮询续取
- `tools/list` 响应体积**较实测基线 193,008 B 下降 ≥15%**(≈ ≤164KB)。不要沿用
「80KB」:按本次合并范围做不到,见 P2-3。**实测 168,634 B(−12.6%)**,未达标,
原因见 P2-3 的实测结果段
---
## 附录 A:本次数据可复现的统计口径
- 调用记录:会话 jsonl 中 `function_call` 且 `name=DeferExecuteTool`,取
`arguments.toolName` 去掉 `mcp__YAMA__` 前缀
- 错误识别:结果文本里匹配 `MCP error (-?\d+):`,避免把输出正文里的 "Error" 误判
- 用途分类:对命令字符串做正则归类(服务状态/进程/注册表/读文件/HTTP/写/控制/列目录/跑脚本)
- 重复命令:对完整命令字符串精确去重
> 注意:不能用「结果里含 timeout 字样」判超时——本次有 29 条命令的**命令正文**里带
> `-TimeoutSec`,会被误判。只有匹配到 `MCP error` 前缀才算工具层失败。
## 附录 B:`tools/list` 体积测法(v2 新增)
一次只读请求即可,不会影响运行中的服务端:
```
POST http://127.0.0.1:6545/mcp # 明文后端;TLS 前端是 6544
Authorization: Bearer <token> # 取自 HKCU\SOFTWARE\YAMA\settings\McpToken,勿打印
{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}
```
2026-11-12 实测:响应 **193,008 字节**,tools 数组 136,692 字节,63 个工具;其中
description 31,874 / inputSchema 44,192 / outputSchema 49,320。
建议给 `tools/mcp_tools/verify_tools.py --live` 增加一行体积打印(当前只比对
name/description/schema 与顺序),让「清单体积」变成可回归的指标,而不是一次性手算。
+13 -5
View File
@@ -710,14 +710,22 @@ int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
Mprintf("** Screen preview thread failed: %s ***\n", e.what());
}
} else if (szBuffer[0] == CMD_HEARTBEAT_ACK) {
if (ulLength >= 1 + sizeof(HeartbeatACK)) {
HeartbeatACK* ack = (HeartbeatACK*)(szBuffer + 1);
// 必须同时认短包:完整结构是 1024 字节,但老服务端 / Go 服务端只回
// HeartbeatACK_OldSize(32)。长度不足就当「没收到」会让下面的 ACK 看门狗
// 每 60s 断开重连一次(表现为链路一直在抖、主连接端口不断变化)。
// Windows 端同样按 min(ulLength, 32) 兼容,见 KernelManager.cpp:2413。
if (ulLength >= 1 + HeartbeatACK_OldSize) {
HeartbeatACK ack = {}; // 短包时缺的字段保持 0(Authorization / ProcessingMs 等)
const size_t copyLen = (ulLength - 1 >= sizeof(HeartbeatACK))
? sizeof(HeartbeatACK)
: (size_t)(ulLength - 1);
memcpy(&ack, szBuffer + 1, copyLen);
uint64_t now = GetUnixMs();
g_lastHeartbeatAckMs.store(now, std::memory_order_relaxed); // 喂应用层 ACK 看门狗
int64_t total_rtt_ms = (int64_t)now - (int64_t)ack->Time;
int64_t total_rtt_ms = (int64_t)now - (int64_t)ack.Time;
int64_t rtt_ms = total_rtt_ms;
if (ack->ProcessingMs > 0 && (int64_t)ack->ProcessingMs < total_rtt_ms)
rtt_ms = total_rtt_ms - (int64_t)ack->ProcessingMs;
if (ack.ProcessingMs > 0 && (int64_t)ack.ProcessingMs < total_rtt_ms)
rtt_ms = total_rtt_ms - (int64_t)ack.ProcessingMs;
g_rttEstimator.update_from_sample((double)rtt_ms);
// 心跳节奏太密日志会刷屏;最多 60s 一行
static time_t lastAckLog = 0;
+13 -5
View File
@@ -813,13 +813,21 @@ int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
Mprintf("** [%p] V2 File recv error: %d ***\n", user, result);
}
} else if (szBuffer[0] == CMD_HEARTBEAT_ACK) {
if (ulLength >= 1 + sizeof(HeartbeatACK)) {
HeartbeatACK* ack = (HeartbeatACK*)(szBuffer + 1);
// 必须同时认短包:完整结构是 1024 字节,但老服务端 / Go 服务端只回
// HeartbeatACK_OldSize(32)。按 sizeof 卡长度的话 RTT 永远不更新(心跳里
// Ping 恒为 0),Windows 端按 min(ulLength, 32) 兼容,见 KernelManager.cpp:2413。
// macOS 没有 ACK 看门狗,不会因此断线重连,但 RTT 会被饿死。
if (ulLength >= 1 + HeartbeatACK_OldSize) {
HeartbeatACK ack = {}; // 短包时缺的字段保持 0(Authorization / ProcessingMs 等)
const size_t copyLen = (ulLength - 1 >= sizeof(HeartbeatACK))
? sizeof(HeartbeatACK)
: (size_t)(ulLength - 1);
memcpy(&ack, szBuffer + 1, copyLen);
uint64_t now = GetUnixMs();
int64_t total_rtt_ms = (int64_t)now - (int64_t)ack->Time;
int64_t total_rtt_ms = (int64_t)now - (int64_t)ack.Time;
int64_t rtt_ms = total_rtt_ms;
if (ack->ProcessingMs > 0 && (int64_t)ack->ProcessingMs < total_rtt_ms)
rtt_ms = total_rtt_ms - (int64_t)ack->ProcessingMs;
if (ack.ProcessingMs > 0 && (int64_t)ack.ProcessingMs < total_rtt_ms)
rtt_ms = total_rtt_ms - (int64_t)ack.ProcessingMs;
g_rttEstimator.update_from_sample((double)rtt_ms);
// Log at most once per minute
static uint64_t lastLogTime = 0;
+1595 -2499
View File
File diff suppressed because it is too large. Load diff
+9
View File
@@ -481,6 +481,8 @@ const ToolHints kToolHints[] = {
{ "list_online_hosts", true, false, true, false },
{ "search_hosts", true, false, true, false },
{ "list_all_hosts", true, false, true, false },
// P2-2:三合一后的正式名字(旧名保留为可调用别名)
{ "list_hosts", true, false, true, false },
{ "get_host_detail", true, false, true, false },
// get_activity_history 虽不含主机 id 之外的写操作,但要经主连接向目标主机发
// COMMAND_QUERY_ACTIVITY 取数据(McpServer.cpp:2249),属触达外部主机 → openWorld=true。
@@ -505,11 +507,14 @@ const ToolHints kToolHints[] = {
{ "list_registry", true, false, true, true },
{ "download_file", true, false, true, true }, // 只读主机(写的是主控本机目录)
{ "search_file", true, false, true, true },
{ "read_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 },
// P2-1:10 个 host_list_* 合并为 host_inspect(旧名为别名,行为一致)
{ "host_inspect", true, false, true, true },
{ "host_list_processes", true, false, true, true },
{ "host_list_windows", true, false, true, true },
{ "host_list_network_state", true, false, true, true },
@@ -521,6 +526,9 @@ const ToolHints kToolHints[] = {
{ "host_list_scheduled_tasks", true, false, true, true },
{ "host_get_hosts_file", true, false, true, true },
// --- 终端 ---
// 默认 GET 只读,但 method 可传 POST/PUT/DELETE 等(改的是被探测的服务,不是主机文件),
// 与 get_keylog 同理按「可写、可破坏」登记,避免客户端把它当纯读工具批量重试。
{ "http_probe", false, true, false, true },
{ "terminal_open", false, false, true, true },
{ "terminal_exec", false, true, false, true }, // 任意命令,后果由命令决定
{ "exec_command", false, true, false, true },
@@ -596,6 +604,7 @@ bool IsBatchReadOnlyTool(const std::string& t) {
"get_host_detail", "list_processes", "list_windows", "list_services",
"list_files", "list_registry", "get_client_log", "get_activity_history",
"list_network_connections",
"host_inspect", // P2-1:10 个 host_list_* 合并后的入口
"host_list_processes", "host_list_windows", "host_list_network_state",
"host_list_software", "host_list_browser_history", "host_list_favorites",
"host_list_win32_services", "host_list_driver_services",
+329 -130
View File
@@ -241,7 +241,7 @@ Json::Value MakeListOutputSchema(const char* arrayKey, const Json::Value& itemPr
}
Json::Value HostIdProp() {
return PropStr(u8"主机 id,取 list_online_hosts / search_hosts 返回的 id 字段");
return PropStr(u8"主机 id,取 list_hosts 返回的 id 字段");
}
// 所有读工具的公共分页参数
@@ -2068,6 +2068,171 @@ static std::string BuildHostGetHostsFile(const Json::Value& id, const Json::Valu
return BuildStructuredResult(id, sc, summary, &textPayload);
}
// ============================================================================
// P2-1:host_inspect —— 10 个 host_list_* / host_get_hosts_file 合并成一个工具
// ============================================================================
// 单个 aspect 直接走原 builder,输出与旧工具逐字节一致(旧工具名保留为别名,分派到
// 同一个入口);多个 aspect 串行取,每个 aspect 一个 managed 会话,结果收进
// results.<aspect>,某个 aspect 失败只记入 errors.<aspect>,不影响其它 aspect。
namespace {
typedef std::string (*InspectBuilder)(const Json::Value&, const Json::Value&, CMy2015RemoteDlg*);
std::string BuildInspectWin32Services(const Json::Value& id, const Json::Value& args,
CMy2015RemoteDlg* parent) {
return BuildHostListServices(id, args, parent, /*drivers=*/false);
}
std::string BuildInspectDriverServices(const Json::Value& id, const Json::Value& args,
CMy2015RemoteDlg* parent) {
return BuildHostListServices(id, args, parent, /*drivers=*/true);
}
struct InspectAspect {
const char* name;
const char* what; // 摘要里的中文名
InspectBuilder build;
};
// aspects 的枚举顺序即此处顺序;schema 与校验都从这里来,避免两处漂移。
const InspectAspect kInspectAspects[] = {
{ "processes", u8"进程", BuildHostListProcesses },
{ "windows", u8"窗口", BuildHostListWindows },
{ "network", u8"网络连接", BuildHostListNetworkState },
{ "software", u8"软件", BuildHostListSoftware },
{ "browser_history", u8"浏览记录", BuildHostListBrowserHistory },
{ "favorites", u8"收藏夹", BuildHostListFavorites },
{ "win32_services", u8"Win32 服务", BuildInspectWin32Services },
{ "driver_services", u8"驱动服务", BuildInspectDriverServices },
{ "scheduled_tasks", u8"计划任务", BuildHostListScheduledTasks },
{ "hosts_file", u8"hosts 文件", BuildHostGetHostsFile },
};
std::string ValidAspectList() {
std::string s;
for (const InspectAspect& a : kInspectAspects) {
if (!s.empty()) s += ", ";
s += a.name;
}
return s;
}
bool ReadInspectAspects(const Json::Value& id, const Json::Value& args,
std::vector<const InspectAspect*>& out, std::string& errJson) {
const Json::Value& v = args["aspects"];
if (!v.isArray() || v.size() == 0) {
errJson = BuildError(id, -32602,
"Invalid aspects: must be a non-empty array; valid: " + ValidAspectList());
return false;
}
for (Json::ArrayIndex i = 0; i < v.size(); ++i) {
if (!v[i].isString()) {
errJson = BuildError(id, -32602, "Invalid aspects: every entry must be a string");
return false;
}
const std::string s = v[i].asString();
const InspectAspect* hit = nullptr;
for (const InspectAspect& a : kInspectAspects) {
if (s == a.name) { hit = &a; break; }
}
if (!hit) {
errJson = BuildError(id, -32602,
"Invalid aspect '" + s + "'; valid: " + ValidAspectList());
return false;
}
bool dup = false;
for (const InspectAspect* p : out) {
if (p == hit) { dup = true; break; }
}
if (!dup) out.push_back(hit);
}
return true;
}
// 把一个 builder 的完整 JSON-RPC 响应拆成 structuredContent + 摘要文本 / 错误码。
struct InspectRun {
int code = 0; // 0 = 成功
Json::Value sc;
std::string text;
};
bool RunInspectAspect(const InspectAspect& a, const Json::Value& id, const Json::Value& args,
CMy2015RemoteDlg* parent, InspectRun& run) {
const std::string resp = a.build(id, args, parent);
Json::Value doc;
Json::Reader reader;
if (!reader.parse(resp, doc) || !doc.isObject()) {
run.code = kErrGeneric;
run.text = "internal error: unparsable tool result";
return false;
}
if (doc.isMember("error") && doc["error"].isObject()) {
run.code = doc["error"]["code"].asInt();
run.text = doc["error"]["message"].asString();
return false;
}
const Json::Value& result = doc["result"];
if (!result.isObject()) {
run.code = kErrGeneric;
run.text = "internal error: missing result";
return false;
}
run.sc = result["structuredContent"];
if (result["content"].isArray() && result["content"].size() > 0)
run.text = JsonStrField(result["content"][0], "text");
return true;
}
std::string BuildHostInspect(const Json::Value& id, const Json::Value& args,
CMy2015RemoteDlg* parent) {
std::vector<const InspectAspect*> aspects;
std::string errJson;
if (!ReadInspectAspects(id, args, aspects, errJson)) return errJson;
// 单 aspect:原样返回旧 builder 的响应——输出与旧工具(以及旧名别名)逐字节一致。
if (aspects.size() == 1) return aspects[0]->build(id, args, parent);
Json::Value results(Json::objectValue);
Json::Value errors(Json::objectValue);
std::string summary;
int okCount = 0, failCount = 0;
for (const InspectAspect* a : aspects) {
InspectRun run;
if (!summary.empty()) summary += u8";";
if (RunInspectAspect(*a, id, args, parent, run)) {
results[a->name] = run.sc;
okCount++;
summary += std::string(a->what) + ":" + (run.text.empty() ? std::string("ok") : run.text);
} else {
Json::Value e(Json::objectValue);
if (run.code) e["code"] = run.code;
e["message"] = run.text;
errors[a->name] = e;
failCount++;
summary += std::string(a->what) + u8":失败(" +
(run.code ? std::to_string(run.code) + " " : std::string()) + run.text + ")";
}
}
Json::Value sc(Json::objectValue);
sc["results"] = results;
if (failCount) sc["errors"] = errors;
Json::Value result(Json::objectValue);
result["structuredContent"] = sc;
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
item["text"] = summary;
content.append(item);
result["content"] = content;
result["isError"] = (okCount == 0);
return BuildResult(id, result);
}
} // namespace
// ============================================================================
// 主机管理:写工具(只读 + 可恢复操作)
// ============================================================================
@@ -2266,8 +2431,11 @@ static std::string BuildHostControlWindow(const Json::Value& id, const Json::Val
else if (action == "maximize") sw = SW_SHOWMAXIMIZED;
else if (action == "minimize") sw = SW_SHOWMINIMIZED;
else if (activate) sw = CMD_WINDOW_ACTIVATE_FLAG;
// close/show 在分派层已转给主连接实现(operate_window),不会走到这里;
// 错误信息仍按工具 schema 的完整枚举列出,免得调用方以为它们不存在。
else return BuildError(id, -32602,
"Invalid action: expected restore, hide, maximize, minimize or activate");
"Invalid action: expected restore, hide, maximize, minimize, "
"activate, close or show");
uint32_t hwnd = 0;
if (!ReadHwndArg(id, args, hwnd, errJson)) return errJson;
@@ -2403,10 +2571,13 @@ static std::string BuildHostControlService(const Json::Value& id, const Json::Va
std::string action = ToLowerAscii(OptStr(args, "action"));
bool dangerous = (action == "stop" || action == "restart");
// set_auto/set_manual 在分派层已转给主连接实现(control_service),不会走到这里;
// 错误信息仍按工具 schema 的完整枚举列出。
if (action != "start" && action != "stop" && action != "pause" &&
action != "continue" && action != "restart")
return BuildError(id, -32602,
"Invalid action: expected start, stop, pause, continue or restart");
"Invalid action: expected start, stop, pause, continue, restart, "
"set_auto or set_manual");
if (dangerous && !RequireDangerous(id, errJson)) return errJson;
std::string serviceName = Trim(GetStringArg(args, "name"));
@@ -2823,19 +2994,131 @@ Json::Value ReadInputSchemaBatch(Json::Value props) {
return schema;
}
// 只有 id/ids、没有分页的只读工具(host_get_hosts_file 用 max_bytes 控大小)
Json::Value IdOrIdsSchema(Json::Value props) {
AppendBatchIdsProp(props);
Json::Value schema = MakeSchema(props, {});
MakeIdOrIdsRequired(schema);
// ===== host_inspect(P2-1:10 个 host_list_* / host_get_hosts_file 合并)=====
// 过滤参数按 aspect 生效,其余 aspect 忽略;全部可选、AND 组合、子串匹配。
Json::Value BuildHostInspectInputSchema() {
Json::Value props(Json::objectValue);
props["id"] = HostIdProp();
Json::Value aspects(Json::objectValue);
aspects["type"] = "array";
aspects["minItems"] = 1;
Json::Value items(Json::objectValue);
items["type"] = "string";
Json::Value enums(Json::arrayValue);
for (const InspectAspect& a : kInspectAspects) enums.append(a.name);
items["enum"] = enums;
aspects["items"] = items;
aspects["description"] = u8"要取的方面(必填、可多选、自动去重):"
u8"processes=进程,windows=可见顶层窗口,network=网络连接(进程视角),"
u8"software=已安装软件,browser_history=IE 浏览历史,favorites=IE 收藏夹,"
u8"win32_services=Win32 服务,driver_services=驱动服务,"
u8"scheduled_tasks=计划任务,hosts_file=hosts 文件";
props["aspects"] = aspects;
props["pid"] = PropInt(u8"按 PID 过滤:processes / windows(所属进程)/ network");
props["name"] = PropStr(u8"按名称子串过滤:processes(映像名)/ software(软件名)/ "
u8"win32_services|driver_services(服务名或显示名)/ scheduled_tasks(任务名)");
props["arch"] = PropStrEnum(u8"按架构过滤:processes", { "x86", "x64" });
props["title"] = PropStr(u8"按标题子串过滤:windows(窗口标题)/ browser_history(网页标题)");
props["url"] = PropStr(u8"按 URL 子串过滤:browser_history / favorites");
props["publisher"] = PropStr(u8"按发布者子串过滤:software");
props["folder"] = PropStr(u8"按任务文件夹子串过滤(如 \\Microsoft):scheduled_tasks");
props["status"] = PropStr(u8"按状态子串过滤(如 Running / Ready):win32_services / driver_services / scheduled_tasks");
props["start_type"] = PropStr(u8"按启动类型子串过滤(如 Auto):win32_services / driver_services");
props["process"] = PropStr(u8"按进程名子串过滤:network");
props["protocol"] = PropStrEnum(u8"按协议过滤:network", { "tcp", "udp", "all" });
props["local_port"] = PropInt(u8"按本地端口精确过滤:network");
props["remote_port"] = PropInt(u8"按远端端口精确过滤:network");
props["state"] = PropStr(u8"按状态子串过滤(如 ESTABLISHED):network");
props["include_content"] = PropBool(u8"是否返回按行切分的内容,默认 true:hosts_file");
props["max_bytes"] = PropInt(u8"最多返回的原始字节数,默认 262144,上限 1048576:hosts_file");
AddPagingProps(props);
Json::Value schema = ReadInputSchemaBatch(props);
// aspects 是必填:ReadInputSchemaBatch 只留下 id/ids 的 anyOf,这里补回 required。
// 不写进 schema 的话,按 schema 校验的客户端会以为可以省略,运行时才吃到 -32602。
Json::Value req(Json::arrayValue);
req.append("aspects");
schema["required"] = req;
return schema;
}
// hosts_file 的输出 schema(原 host_get_hosts_file 的字段,一字不改)
Json::Value HostsFileOutputSchema() {
Json::Value outProps(Json::objectValue);
outProps["path"] = PropStr();
outProps["encoding"] = PropStr(u8"utf-8 / gbk(自动探测)");
outProps["bytes"] = PropInt(u8"文件原始字节数");
outProps["returnedBytes"] = PropInt();
outProps["truncated"] = PropBool();
outProps["lineCount"] = PropInt();
Json::Value lines(Json::objectValue);
lines["type"] = "array";
lines["items"] = PropStr();
outProps["lines"] = lines;
outProps["content"] = PropStr(u8"未截断时的完整文本");
Json::Value out(Json::objectValue);
out["type"] = "object";
out["properties"] = outProps;
return out;
}
Json::Value BuildHostInspectOutputSchema() {
Json::Value resultsProps(Json::objectValue);
resultsProps["processes"] = MakeListOutputSchema("processes", ProcessItemSchema());
Json::Value windows = MakeListOutputSchema("windows", WindowItemSchema());
windows["properties"]["truncated"] =
PropBool(u8"为 true 时表示客户端的可见窗口多于单次返回上限(96 条),列表不完整");
resultsProps["windows"] = windows;
resultsProps["network"] = MakeListOutputSchema("connections", NetStateItemSchema());
resultsProps["software"] = MakeListOutputSchema("software", SoftwareItemSchema());
resultsProps["browser_history"] = MakeListOutputSchema("history", HistoryItemSchema());
resultsProps["favorites"] = MakeListOutputSchema("favorites", FavoriteItemSchema());
resultsProps["win32_services"] = MakeListOutputSchema("services", ServiceItemSchema());
resultsProps["driver_services"] = MakeListOutputSchema("services", ServiceItemSchema());
resultsProps["scheduled_tasks"] = MakeListOutputSchema("tasks", TaskItemSchema());
resultsProps["hosts_file"] = HostsFileOutputSchema();
Json::Value results(Json::objectValue);
results["type"] = "object";
results["description"] = u8"按 aspect 名索引;每个值的形状与单 aspect 调用的顶层一致";
results["properties"] = resultsProps;
Json::Value errItem(Json::objectValue);
errItem["type"] = "object";
Json::Value errProps(Json::objectValue);
errProps["code"] = PropInt(u8"JSON-RPC 错误码,如 -32001 超时、-32005 平台不支持");
errProps["message"] = PropStr(u8"错误说明");
errItem["properties"] = errProps;
Json::Value errors(Json::objectValue);
errors["type"] = "object";
errors["description"] = u8"只有失败的 aspect 才会出现;不影响其它 aspect 的结果";
errors["additionalProperties"] = errItem;
Json::Value props(Json::objectValue);
props["results"] = results;
props["errors"] = errors;
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
// 单 aspect 时顶层直接是该 aspect 的列表结果(与旧工具逐字节一致),两种形状都合法。
schema["additionalProperties"] = true;
return schema;
}
} // namespace
bool Handles(const std::string& toolName) {
// host_inspect 之后的 10 个旧名(host_list_* / host_get_hosts_file)是 P2-1 合并后
// 保留的别名:不出现在 tools/list,但调用仍按旧行为处理。新增调用方请用 host_inspect。
static const char* kTools[] = {
"list_network_connections", "kill_network_connection",
"host_inspect",
"host_list_processes", "host_list_windows", "host_list_network_state",
"host_list_software", "host_list_browser_history", "host_list_favorites",
"host_list_win32_services", "host_list_driver_services",
@@ -2887,118 +3170,28 @@ void AppendTools(Json::Value& tools) {
ActionOutputSchema());
}
// ---- 主机管理:10 个只读标签页 ----
// ---- 主机管理:host_inspect(P2-1:原 10 个 host_list_* / host_get_hosts_file 合并)----
{
Json::Value props(Json::objectValue);
props["pid"] = PropInt(u8"按 PID 过滤");
props["name"] = PropStr(u8"按进程名子串过滤");
props["arch"] = PropStrEnum(u8"按架构过滤", { "x86", "x64" });
AddTool(tools, "host_list_processes",
u8"列出在线 Windows 主机的进程(主机管理「进程」标签页)。返回 PID、架构、窗口标题、路径、优先级、线程数、用户、工作集与文件大小。首选:与 list_processes 同源但字段更全,并支持服务端过滤(pid / name / arch),仅在它没有出现在 tools/list 里(McpMachine=0)时退回 list_processes。",
ReadInputSchemaBatch(props), MakeListOutputSchema("processes", ProcessItemSchema()));
}
{
Json::Value props(Json::objectValue);
props["pid"] = PropInt(u8"按所属进程 PID 过滤");
props["title"] = PropStr(u8"按窗口标题子串过滤");
Json::Value outSchema = MakeListOutputSchema("windows", WindowItemSchema());
// 客户端单个响应包最多装 96 条窗口;超出时这里给出 true,表示 windows
// 只是可见窗口的一个前缀,翻页也取不到剩下的部分。
outSchema["properties"]["truncated"] =
PropBool(u8"为 true 时表示客户端的可见窗口多于单次返回上限(96 条),列表不完整");
AddTool(tools, "host_list_windows",
u8"列出在线 Windows 主机上当前可见的顶层窗口(主机管理「窗口」标签页)。只包含可见窗口,故隐藏后窗口会从结果中消失;单次最多返回 96 条,可见窗口更多时 truncated=true 且列表不完整(不能据此断定某个窗口不存在)。hwnd 可用于 host_control_window 或 operate_window。首选:支持服务端过滤(pid / title),仅在它没有出现在 tools/list 里(McpMachine=0)时退回 list_windows。",
ReadInputSchemaBatch(props), outSchema);
}
{
Json::Value props(Json::objectValue);
props["pid"] = PropInt();
props["process"] = PropStr(u8"按进程名子串过滤");
props["protocol"] = PropStrEnum(u8"协议过滤", { "tcp", "udp" });
props["local_port"] = PropInt();
props["remote_port"] = PropInt();
props["state"] = PropStr(u8"按状态子串过滤");
AddTool(tools, "host_list_network_state",
u8"列出在线 Windows 主机的网络连接及其所属进程(主机管理「网络状态」标签页)。数据来源与「连接管理」不同(这里是进程视角、含 UDP 的无对端标记);仅支持 IPv4 展示。",
ReadInputSchemaBatch(props), MakeListOutputSchema("connections", NetStateItemSchema()));
}
{
Json::Value props(Json::objectValue);
props["name"] = PropStr(u8"按软件名子串过滤");
props["publisher"] = PropStr(u8"按发布者子串过滤");
AddTool(tools, "host_list_software",
u8"列出在线 Windows 主机已安装的软件(主机管理「软件」标签页,来自注册表 Uninstall 项)。只读;不提供卸载能力。",
ReadInputSchemaBatch(props), MakeListOutputSchema("software", SoftwareItemSchema()));
}
{
Json::Value props(Json::objectValue);
props["title"] = PropStr(u8"按标题子串过滤");
props["url"] = PropStr(u8"按 URL 子串过滤");
AddTool(tools, "host_list_browser_history",
u8"列出在线 Windows 主机的 IE 浏览历史(主机管理「浏览记录」标签页)。隐私数据,仅在显式开启主机管理时可见。",
ReadInputSchemaBatch(props), MakeListOutputSchema("history", HistoryItemSchema()));
}
{
Json::Value props(Json::objectValue);
props["name"] = PropStr(u8"按收藏名子串过滤");
props["url"] = PropStr(u8"按 URL 子串过滤");
AddTool(tools, "host_list_favorites",
u8"列出在线 Windows 主机的 IE 收藏夹(主机管理「收藏夹」标签页)。隐私数据,仅在显式开启主机管理时可见。",
ReadInputSchemaBatch(props), MakeListOutputSchema("favorites", FavoriteItemSchema()));
}
{
Json::Value props(Json::objectValue);
props["name"] = PropStr(u8"按服务名或显示名子串过滤");
props["status"] = PropStr(u8"按状态子串过滤,如 Running");
props["start_type"] = PropStr(u8"按启动类型子串过滤,如 Auto");
AddTool(tools, "host_list_win32_services",
u8"列出在线 Windows 主机的 Win32 服务(主机管理「服务」标签页之一)。返回显示名、描述、状态、启动类型、登录身份、服务名与可执行路径;服务名可用于 host_control_service。首选:支持服务端过滤(name / status),仅在它没有出现在 tools/list 里(McpMachine=0)时退回 list_services。",
ReadInputSchemaBatch(props), MakeListOutputSchema("services", ServiceItemSchema()));
}
{
Json::Value props(Json::objectValue);
props["name"] = PropStr(u8"按服务名或显示名子串过滤");
props["status"] = PropStr(u8"按状态子串过滤");
props["start_type"] = PropStr(u8"按启动类型子串过滤");
AddTool(tools, "host_list_driver_services",
u8"列出在线 Windows 主机的驱动服务(主机管理「服务」标签页之一)。字段同 host_list_win32_services。",
ReadInputSchemaBatch(props), MakeListOutputSchema("services", ServiceItemSchema()));
}
{
Json::Value props(Json::objectValue);
props["name"] = PropStr(u8"按任务名子串过滤");
props["folder"] = PropStr(u8"按任务文件夹子串过滤,如 \\Microsoft");
props["status"] = PropStr(u8"按状态子串过滤,如 Ready / Disabled");
AddTool(tools, "host_list_scheduled_tasks",
u8"列出在线 Windows 主机的计划任务(主机管理「计划任务」标签页)。返回任务名、完整路径、所在文件夹、可执行文件、状态与上次/下次运行时间。任务名 + folder 可用于 host_control_task。",
ReadInputSchemaBatch(props), MakeListOutputSchema("tasks", TaskItemSchema()));
}
{
Json::Value props(Json::objectValue);
props["id"] = HostIdProp();
props["include_content"] = PropBool(u8"是否返回按行切分的内容,默认 true");
props["max_bytes"] = PropInt(u8"最多返回的原始字节数,默认 262144,上限 1048576");
Json::Value outProps(Json::objectValue);
outProps["path"] = PropStr();
outProps["encoding"] = PropStr(u8"utf-8 / gbk(自动探测)");
outProps["bytes"] = PropInt(u8"文件原始字节数");
outProps["returnedBytes"] = PropInt();
outProps["truncated"] = PropBool();
outProps["lineCount"] = PropInt();
Json::Value lines(Json::objectValue);
lines["type"] = "array";
lines["items"] = PropStr();
outProps["lines"] = lines;
outProps["content"] = PropStr(u8"未截断时的完整文本");
Json::Value out(Json::objectValue);
out["type"] = "object";
out["properties"] = outProps;
AddTool(tools, "host_get_hosts_file",
u8"读取在线 Windows 主机的 hosts 文件(主机管理「HOSTS」标签页),按行返回并自动识别 UTF-8/GBK。只读;不提供写入能力。",
IdOrIdsSchema(props), out);
AddTool(tools, "host_inspect",
u8"一次取回在线 Windows 主机的多类主机管理信息(原 10 个 host_list_* 工具合并)。aspects 必填、可多选:"
u8"processes(进程:PID/架构/窗口标题/路径/优先级/线程数/用户/工作集与文件大小)| "
u8"windows(当前可见顶层窗口;只含可见窗口,单次最多 96 条,超出时 truncated=true 且列表不完整,"
u8"不能据此断定某窗口不存在;hwnd 可交给 host_control_window / operate_window)| "
u8"network(网络连接,进程视角、含 UDP;与 list_network_connections 的「连接管理」数据源不同)| "
u8"software(已安装软件,来自注册表 Uninstall 项;不提供卸载)| "
u8"browser_history(IE 浏览历史,隐私数据)| favorites(IE 收藏夹,隐私数据)| "
u8"win32_services(Win32 服务;服务名可用于 host_control_service)| "
u8"driver_services(驱动服务;字段同 win32_services)| "
u8"scheduled_tasks(计划任务;任务名 + folder 可用于 host_control_task)| "
u8"hosts_file(按行返回并自动识别 UTF-8/GBK)。"
u8"注意:win32_services / driver_services 要求客户端以管理员权限运行——非提权客户端"
u8"拿不到 SCM 句柄后直接不回应,调用会在约 12 秒后超时(同等场景 list_services 会明确报 access denied)。"
u8"过滤参数按 aspect 生效、其余忽略(见各参数说明),在服务端完成且先于分页:"
u8"total 为命中数、totalAll 为该项全部条目数。"
u8"单个 aspect 时顶层就是该项的列表结果(与合并前的旧工具一致);多个 aspect 时汇总在 "
u8"results.<aspect>,某个 aspect 失败只记入 errors.<aspect>、不影响其它 aspect,全部失败才 isError=true。"
u8"每多选一个 aspect 就多一次子连接,耗时线性增长,不需要的不要选。只读。",
BuildHostInspectInputSchema(), BuildHostInspectOutputSchema());
}
// ---- 主机管理:4 个写工具(只读 + 可恢复操作) ----
@@ -3018,38 +3211,43 @@ void AppendTools(Json::Value& tools) {
{
Json::Value props(Json::objectValue);
props["id"] = HostIdProp();
props["action"] = PropStrEnum(u8"restore/hide/maximize/minimize/activate",
{ "restore", "hide", "maximize", "minimize", "activate" });
props["action"] = PropStrEnum(u8"restore/hide/maximize/minimize/activate,"
u8"以及 close/show(转主连接实现,需 McpManage=1)",
{ "restore", "hide", "maximize", "minimize", "activate",
"close", "show" });
Json::Value hwnd(Json::objectValue);
Json::Value types(Json::arrayValue);
types.append("integer");
types.append("string");
hwnd["type"] = types;
hwnd["description"] = u8"窗口句柄,取 host_list_windows 的 hwnd;整数或 0x 前缀字符串";
hwnd["description"] = u8"窗口句柄,取 host_inspect(aspects=[\"windows\"])或 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(最小化)/activate(激活到前台)。hwnd 取 host_list_windows 或 list_windows 返回的 hwnd。动作后重新枚举可见窗口复核:hide 后 hwnd 应消失,其余动作后仍应存在;activate 会额外复核 GetForegroundWindow,目标未成为前台则 ok=false、reason=not_foreground。activate 需要新客户端(窗口信息能力),旧客户端返回 -32005,可退回 restore。不提供关闭窗口——需要 close / show 时改用 operate_window。dry_run=true 只核实 hwnd 并返回窗口信息。",
u8"对在线 Windows 主机的窗口执行操作:restore(还原)/hide(隐藏)/maximize(最大化)/minimize(最小化)/activate(激活到前台)/close(关闭)/show(显示)。hwnd 取 host_inspect 的 windows 项或 list_windows 返回的 hwnd。restore 等五个动作走主机管理链路,动作后重新枚举可见窗口复核:hide 后 hwnd 应消失,其余动作后仍应存在;activate 会额外复核 GetForegroundWindow,目标未成为前台则 ok=false、reason=not_foreground,且需要新客户端(窗口信息能力),旧客户端返回 -32005,可退回 restore。close/show 没有主机管理实现,转由主连接版 operate_window 处理(因此动作后不复核,ok 只表示已下发;McpManage=0 时返回 -32006)——它们只在 McpMachine=0 时才以 operate_window 之名出现在 tools/list。dry_run=true 只核实 hwnd 并返回窗口信息,不下发动作。",
MakeSchema(props, { "id", "action", "hwnd" }),
ActionOutputSchema());
}
{
Json::Value props(Json::objectValue);
props["id"] = HostIdProp();
props["action"] = PropStrEnum(u8"start/stop/pause/continue/restart",
{ "start", "stop", "pause", "continue", "restart" });
props["name"] = PropStr(u8"服务名(ServiceName,不是显示名),取 host_list_*_services 的 name");
props["action"] = PropStrEnum(u8"start/stop/pause/continue/restart,"
u8"以及 set_auto/set_manual(转主连接实现,需 McpManage=1)",
{ "start", "stop", "pause", "continue", "restart",
"set_auto", "set_manual" });
props["name"] = PropStr(u8"服务名(ServiceName,不是显示名),取 host_inspect 的 win32_services / driver_services 项的 name;与 service_name 二选一");
props["service_name"] = PropStr(u8"name 的旧参数名别名(与 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。不提供删除服务。dry_run=true 只核实服务并返回当前状态,不下发命令(是否已是目标状态由你按 state 判断)。",
MakeSchema(props, { "id", "action", "name" }),
u8"控制在线 Windows 主机的服务:start/stop/pause/continue/restart/set_auto/set_manual。start 等五个动作走主机管理链路:客户端对每次控制都会自动回一份刷新后的服务列表,工具据此复核状态并如实返回 ok;stop 与 restart 归入危险操作,需要同时开启 McpMachineDangerous;restart 先 stop 再 start。set_auto/set_manual 没有主机管理实现,转由主连接版 control_service 处理(ok 只表示已下发、需另查状态;McpManage=0 时返回 -32006)——它们只在 McpMachine=0 时才以 control_service 之名出现在 tools/list。不提供删除服务。dry_run=true 只核实服务并返回当前状态,不下发命令(是否已是目标状态由你按 state 判断);set_auto/set_manual 不支持 dry_run(返回 -32602)。",
MakeSchema(props, { "id", "action" }),
ActionOutputSchema());
}
{
Json::Value props(Json::objectValue);
props["id"] = HostIdProp();
props["action"] = PropStrEnum(u8"run=立即运行,stop=停止正在运行的任务", { "run", "stop" });
props["name"] = PropStr(u8"任务名,取 host_list_scheduled_tasks 的 name");
props["name"] = PropStr(u8"任务名,取 host_inspect 的 scheduled_tasks 项的 name");
props["folder"] = PropStr(u8"可选:任务所在文件夹;同名任务存在多个时必填");
props["dry_run"] = PropBool(u8"true 时只校验任务存在(含同名歧义检查)并返回当前状态,不下发 run/stop,默认 false");
AddTool(tools, "host_control_task",
@@ -3077,7 +3275,8 @@ std::string Call(const Json::Value& id, const std::string& toolName,
if (toolName == "kill_network_connection")
return BuildKillNetworkConnection(id, args, parent);
// ---- 主机管理:只读 ----
// ---- 主机管理:只读(host_inspect 及合并后的旧名别名) ----
if (toolName == "host_inspect") return BuildHostInspect(id, args, parent);
if (toolName == "host_list_processes") return BuildHostListProcesses(id, args, parent);
if (toolName == "host_list_windows") return BuildHostListWindows(id, args, parent);
if (toolName == "host_list_network_state") return BuildHostListNetworkState(id, args, parent);
File diff suppressed because it is too large. Load diff
+43 -5
View File
@@ -227,6 +227,11 @@ public:
// 终端子连接是否已被 MCP 接管(MessageHandle 顶部据此把 shell 输出路由到 OnTerminalData)。
bool IsTerminalContext(context* subCtx);
// 工具线程:写命令前确认 subCtx 仍是该会话在用的子连接。等待提示符期间 shell 可能已退出,
// 子连接被 OfflineProc 归还连接池后可能已被新连接复用,此时再写就是往别人的连接里灌命令。
// sessionId 非空时还要求会话是持久的且 token 一致。
bool IsTermSubCtxLive(uint64_t device_id, const std::string& sessionId, context* subCtx);
// 追加 shell 输出并做哨兵检测(命中置 done 并唤醒等待者)。
void OnTerminalData(context* subCtx, const BYTE* data, ULONG len);
@@ -241,6 +246,7 @@ public:
// 工具线程:等待输出收集完成(哨兵命中 / 进程退出 / 超时)。
// 成功 true:out=截断到哨兵前的原始字节、exitCode=0/1(进程退出无哨兵时 -1)、closed=是否进程退出。
// 失败时也尽量照实回填 closed:为 true 表示子连接已断开或去向未知,调用方不得再对它 CancelIO。
bool WaitTerminalDone(uint64_t device_id, std::vector<BYTE>& out, int& exitCode, bool& closed, int timeoutMs);
// 工具线程:写命令前等 shell 启动完成(收到第一屏输出,通常是提示符)。
@@ -258,6 +264,15 @@ public:
// 登记持久终端挂起(复用单设备单终端约束;sessionId 由调用方生成)。
bool BeginTermOpen(uint64_t device_id, const std::string& sessionId);
// terminal_exec 不带 session_id 时:复用该主机已有的持久会话;没有就登记一个挂起会话。
// 返回:0=ok(reused=true 复用已有会话;false=本次新建,调用方需发 COMMAND_SHELL 并
// WaitTerminalReady);2=已有会话但尚未就绪(并发 open,调用方报 -32003)。
int OpenOrReuseTermSession(uint64_t device_id, std::string& sessionId, bool& reused);
// terminal_open 撞上已有会话时复用它(不再报 -32003):0=ok(输出 token 与 isPty);
// 2=已有会话但尚未就绪(有 open 在并发建立中)。
int ReuseTermSession(uint64_t device_id, std::string& sessionId, bool& isPty);
// 复位单条命令字段并置 busy;输出 subCtx/isPty。
// 返回:0=ok;1=会话不存在;2=sessionId 不匹配;3=未就绪;4=忙(另一条命令在飞);
// 5=shell 已退出。1/2 之外的原因由 DescribeTermDestroyed 提供可读文案。
@@ -273,9 +288,22 @@ public:
// 否则返回空串。sessionId 不匹配时也返回空串(那是「id 写错」而不是「已销毁」)。
std::string DescribeTermDestroyed(uint64_t device_id, const std::string& sessionId);
// 等待本条命令完成(done || closed || 超时)。done=保持会话;closed/超时=清理会话+路由。
bool WaitTermCommand(uint64_t device_id, std::vector<BYTE>& out, int& exitCode,
bool& closed, int timeoutMs);
// 等待本条命令结束或超时,并交付 [delivered, ...) 的增量输出。
// pollMode=true 表示本次调用没有携带新命令(只轮询),此时会话空闲 = 调用方用错,返回 7。
// 返回:0=命令结束(done=true;closed=true 表示 shell 退出;本次被 maxOutputBytes 截断时
// 会话保留到轮询取完尾巴再清理,否则当场清理)
// 1=等待超时,命令仍在运行(done=false;会话保持 busy,可再次轮询)
// 2=请求被取消,会话已销毁(与旧语义一致:取消方不会再轮询)
// 3=会话不存在/未就绪/等待期间被销毁(细节看 DescribeTermDestroyed)
// 4=sessionId 不匹配
// 7=轮询时没有在跑的命令(会话空闲)
// 每次最多交付 maxOutputBytes 原始字节(按换行边界回退);truncated=本次是否仍有剩余。
// droppedBytes=该命令因 data 硬上限被丢弃的字节数(累计,如实上报)。
int WaitTermCommand(uint64_t device_id, const std::string& sessionId,
std::vector<BYTE>& out, bool& done, int& exitCode, bool& closed,
bool& truncated, size_t& droppedBytes,
bool& isPty, std::string& nonce,
int maxOutputBytes, int timeoutMs, bool pollMode);
// 关闭持久终端(校验 sessionId;CancelIO + 清理路由/会话)。
// 返回:0=已关闭;1=会话不存在(幂等);2=sessionId 不匹配(调用方报错)。
@@ -371,9 +399,10 @@ public:
bool IsC2CTransferPending(uint64_t src_id, uint64_t dst_id);
// 登记文件传输会话(false = 该 host 已有文件会话或一次性挂起请求)。
// maxFileBytes 仅 read_file 使用:首包文件尺寸超过它就拒收(0=不限)。
bool BeginFileTransferPending(uint64_t device_id, const std::string& tool,
const std::string& localDir, const std::string& remotePath,
bool overwrite);
bool overwrite, uint64_t maxFileBytes = 0);
// 登记上传会话(false = 该 host 已有文件会话或一次性挂起请求)。upload 走主连接、
// 工具线程同步驱动 FileBatchTransferWorkerV2。会话同时用于单设备单传输互斥与
@@ -828,6 +857,12 @@ private:
bool busy = false; // 一条命令在飞(terminal_exec 复位→WaitTermCommand 返回)
time_t lastActiveAt = 0; // idle 回收用(秒)
std::chrono::steady_clock::time_point startedAt = std::chrono::steady_clock::now(); // P11
// ===== 超时轮询(P0-2)=====
size_t delivered = 0; // 已交付给调用方的 data 前缀长度(超时/轮询增量回传)
size_t droppedBytes = 0; // 因 data 硬上限被丢弃的最旧字节数(如实上报)
std::chrono::steady_clock::time_point busySince{}; // busy 起点(长时间在飞的强制回收兜底)
int waiters = 0; // 阻塞在 WaitTermCommand 里的线程数;terminal_close 据此
// 判断 closed 之后是否还有人负责收尾(没有就自己清)
};
std::mutex m_TermMutex;
std::condition_variable m_TermCv;
@@ -893,7 +928,10 @@ private:
uint32_t filesDone = 0; // 已完成的文件数(含跳过的)
bool done = false; // 全部完成或出错
int error = 0; // 0=ok;8=哈希不匹配;1001=路径逃逸;1002=超时;1003=流式子连接断线;
// 1004=停滞(看门狗);1005=远端路径不存在;1006=拒绝访问;1007=其他下载失败
// 1004=停滞(看门狗);1005=远端路径不存在;1006=拒绝访问;1007=其他下载失败;
// 1008=read_file 拒绝:文件大于 maxFileBytes;1009=read_file 拒绝:路径是目录或命中多个文件
// read_file 专用:只收单个普通文件,首包文件尺寸超过该值直接拒收(0=不限,download_file 用)
uint64_t maxFileBytes = 0;
DWORD errorDetail = 0; // error=1005/1006/1007 时的 win32 码(原样带进文案,便于分支/排查)
std::map<uint32_t, FileTransferEntry> fileEntries; // fileIndex → {path,size,sha256}
std::set<uint32_t> skipIndexes; // overwrite=false 跳过的 fileIndex
+35
View File
@@ -0,0 +1,35 @@
package main
import (
"encoding/binary"
"testing"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/protocol"
)
// The Linux and Android clients only accept a heartbeat ACK when
// `ulLength >= 1 + sizeof(HeartbeatACK)` == 1025 bytes and silently ignore a
// shorter packet, so the 60s ACK watchdog never gets fed and the client
// reconnects forever. A 33-byte reply here did exactly that on the Go server
// (linux/main.cpp:2107 "Heartbeat ACK timeout: 60007 ms ... reconnecting",
// once a minute, with the terminal session dying on every reconnect).
func TestBuildHeartbeatACKIsFullSize(t *testing.T) {
const hbTime = uint64(0x1122334455667788)
resp := buildHeartbeatACK(hbTime, 2)
if want := 1 + 1024; len(resp) != want {
t.Fatalf("ACK length = %d, want %d (shorter packets are ignored by the client)", len(resp), want)
}
if resp[0] != protocol.CommandHeartbeat {
t.Fatalf("cmd byte = %d, want %d", resp[0], protocol.CommandHeartbeat)
}
if got := binary.LittleEndian.Uint64(resp[1+protocol.HeartbeatACKOffTime:]); got != hbTime {
t.Fatalf("echoed Time = %#x, want %#x", got, hbTime)
}
if got := resp[1+protocol.HeartbeatACKOffAuthorized]; got != 2 {
t.Fatalf("Authorized = %d, want 2", got)
}
if got := binary.LittleEndian.Uint32(resp[1+protocol.HeartbeatACKOffProcessing:]); got != 0 {
t.Fatalf("ProcessingMs = %d, want 0 (unknown => plain now-Time RTT)", got)
}
}
+42 -22
View File
@@ -71,9 +71,15 @@ func (h *MyHandler) OnDisconnect(ctx *connection.Context) {
// device-offline event, instead of frames/output continuing to
// stream from orphaned sub-conn ctxs until they time out on
// their own. Both calls no-op if there's no active session.
h.hub.CloseScreen(info.ClientID)
h.hub.CloseTerminalSession(info.ClientID)
h.hub.Unregister(info.ClientID)
//
// Use the *Pinned variants: this runs concurrently with a re-login
// on a fresh connection, and the plain versions would tear down the
// sessions Register just carried over (and Unregister by ID alone
// would delete the device that just re-registered, hiding a live
// client until its next reconnect).
h.hub.CloseScreenPinned(info.ClientID, ctx)
h.hub.CloseTerminalSessionPinned(info.ClientID, ctx)
h.hub.UnregisterPinned(info.ClientID, ctx)
}
}
@@ -322,6 +328,16 @@ func (h *MyHandler) handleTerminalStart(ctx *connection.Context, isPTY bool) {
} else {
h.log.Warn("orphan terminal sub-conn: device=%s conn=%d isPTY=%v",
devID, ctx.ID, isPTY)
// Genuine device, but no pending session: the term_open that
// spawned this shell was issued on a main conn that has since
// been replaced (Register deliberately does not carry
// terminalPending over, so the browser can retry). Tell the
// viewer instead of leaving the pane on "connecting" until it
// is closed by hand — the browser treats term_closed as the
// session being over and lets the user reopen it.
if mc != nil && mc.GetPeerIP() == ctx.GetPeerIP() {
h.hub.PublishTerminalClosed(devID, "reconnected")
}
}
ctx.Close()
return
@@ -696,10 +712,9 @@ func (h *MyHandler) handleAuth(ctx *connection.Context, data []byte) {
// - offset 548: Passcode (44 bytes)
// - offset 592: PwdHmac (8 bytes, uint64)
//
// HeartbeatACK structure:
// - offset 0: Time (8 bytes, uint64)
// - offset 8: Authorized (1 byte, char)
// - offset 9: Reserved (23 bytes)
// The reply layout is HeartbeatACK (common/commands.h, 1024 bytes), rendered
// by buildHeartbeatACK from the offsets in protocol/commands.go — see the
// HeartbeatACKSize comment there for why the full size is mandatory.
func (h *MyHandler) handleHeartbeat(ctx *connection.Context, data []byte) {
// Parse Time from heartbeat request (offset 1, 8 bytes)
@@ -768,27 +783,32 @@ func (h *MyHandler) handleHeartbeat(ctx *connection.Context, data []byte) {
}
}
// Build HeartbeatACK response: CMD_HEARTBEAT_ACK(1) + HeartbeatACK(32)
resp := make([]byte, 33)
resp[0] = protocol.CommandHeartbeat // CMD_HEARTBEAT_ACK = 216
// Time at offset 1 (8 bytes, little-endian)
resp[1] = byte(hbTime)
resp[2] = byte(hbTime >> 8)
resp[3] = byte(hbTime >> 16)
resp[4] = byte(hbTime >> 24)
resp[5] = byte(hbTime >> 32)
resp[6] = byte(hbTime >> 40)
resp[7] = byte(hbTime >> 48)
resp[8] = byte(hbTime >> 56)
// Authorized at offset 9 (1 byte)
resp[9] = authorized
// Reserved[23] at offset 10 is already zero
resp := buildHeartbeatACK(hbTime, authorized)
if err := h.srv.Send(ctx, resp); err != nil {
h.log.Error("Failed to send heartbeat ACK to client %d: %v", ctx.ID, err)
}
}
// buildHeartbeatACK renders the CMD_HEARTBEAT_ACK reply: CMD_HEARTBEAT_ACK(1)
// + HeartbeatACK(1024). The packet MUST be the full struct size: clients
// deployed before 2026-11 only accept `ulLength >= 1 + sizeof(HeartbeatACK)`
// and silently ignore a shorter ACK, so a 33-byte reply left their 60s ACK
// watchdog unfed and made every such client reconnect forever. Current
// clients accept both sizes. The C++ server sends the same 1+1024 bytes
// (server/2015Remote/2015RemoteDlg.cpp).
//
// IsTrail / Authorization / ProcessingMs stay zero: clients sync the first two
// from CMD_MASTERSETTING, and ProcessingMs == 0 means "unknown", so the client
// computes RTT as plain now-Time (its behaviour before that field existed).
func buildHeartbeatACK(hbTime uint64, authorized byte) []byte {
resp := make([]byte, 1+protocol.HeartbeatACKSize)
resp[0] = protocol.CommandHeartbeat // CMD_HEARTBEAT_ACK = 216
binary.LittleEndian.PutUint64(resp[1+protocol.HeartbeatACKOffTime:], hbTime)
resp[1+protocol.HeartbeatACKOffAuthorized] = authorized
return resp
}
// parsePorts parses a semicolon-separated port string and returns port numbers
func parsePorts(portStr string) ([]int, error) {
var ports []int
+90 -11
View File
@@ -471,6 +471,32 @@ func (h *Hub) Register(d *Device, conn *connection.Context) {
}
d.conn = conn
h.mu.Lock()
// A reconnecting client logs in with a *fresh* Device struct, so every
// sub-conn-scoped field would come back zeroed even though the sub-conns
// themselves (screen / shell) ride their own TCP connections and normally
// survive a main-conn reconnect. Dropping them silently breaks live views:
// - terminal: SendToTerminal returns ErrDeviceOffline for every keystroke
// (handleTermInput ignores the error) while output keeps streaming the
// other way — the browser looks connected but typing does nothing, and
// CloseTerminalSession can no longer tear the shell down (orphan shells
// + leaked sockets);
// - screen: the cached resolution / last IDR are lost, so a viewer that
// joins before the next IDR has nothing to decode.
// The carried bindings may themselves be dead if the whole network path
// went away; the sub-conn read timeout then reaps them through
// UnbindScreenConn / UnbindTerminalConn, which clears the same fields.
// Carry the session state over. UnbindScreenConn / UnbindTerminalConn still
// clear it when a sub-conn really is gone, and a genuine offline closes
// both sessions via the *Pinned disconnect helpers, which no-op if a
// re-login has already taken ownership of this ID.
if prev, ok := h.devices[d.ID]; ok {
d.screenConn = prev.screenConn
d.screenWidth, d.screenHeight = prev.screenWidth, prev.screenHeight
d.lastKeyframe = prev.lastKeyframe
d.cursorSeen, d.lastCursorIndex = prev.cursorSeen, prev.lastCursorIndex
d.lastCursorX, d.lastCursorY, d.cursorPubAt = prev.lastCursorX, prev.lastCursorY, prev.cursorPubAt
d.terminalConn, d.terminalIsPTY = prev.terminalConn, prev.terminalIsPTY
}
h.devices[d.ID] = d
info := deviceToInfo(d)
h.mu.Unlock()
@@ -482,19 +508,34 @@ func (h *Hub) Register(d *Device, conn *connection.Context) {
// Unregister removes a device by ID. No-op if not present.
// Subscribers are notified after the device is removed (only if it existed).
func (h *Hub) Unregister(id string) {
h.unregister(id, nil)
}
// UnregisterPinned is Unregister restricted to a device still pinned to main.
// The disconnect path MUST use this: the old main conn's OnDisconnect runs
// concurrently with a re-login, and deleting by ID alone would remove the
// device that just re-registered, leaving a live client invisible in the
// online list until it reconnects again.
func (h *Hub) UnregisterPinned(id string, main *connection.Context) bool {
return h.unregister(id, main)
}
func (h *Hub) unregister(id string, main *connection.Context) bool {
if id == "" {
return
return false
}
h.mu.Lock()
_, existed := h.devices[id]
d, existed := h.devices[id]
if !existed || (main != nil && d.conn != main) {
h.mu.Unlock()
return false
}
delete(h.devices, id)
h.mu.Unlock()
if !existed {
return
}
for _, s := range h.snapshotSubscribers() {
s.OnDeviceOffline(id)
}
return true
}
// ListDevices returns a fresh snapshot slice. The caller may mutate it freely;
@@ -594,11 +635,25 @@ func (h *Hub) PublishCursor(deviceID string, index byte, x, y int) {
// The actual sub-conn teardown is delegated to retireScreenConn, which is
// shared with BindScreenConn's replacement path.
func (h *Hub) CloseScreen(deviceID string) {
h.closeScreenPinned(deviceID, nil)
}
// CloseScreenPinned is CloseScreen restricted to a device that is still
// pinned to main. The main-conn teardown path uses it so a client that has
// already logged in again on a fresh connection is not stripped of the
// screen session Register just carried over to it. The ownership check and
// the detach happen under one hub lock, so a concurrent Register cannot slip
// in between.
func (h *Hub) CloseScreenPinned(deviceID string, main *connection.Context) bool {
return h.closeScreenPinned(deviceID, main)
}
func (h *Hub) closeScreenPinned(deviceID string, main *connection.Context) bool {
h.mu.Lock()
d, ok := h.devices[deviceID]
if !ok {
if !ok || (main != nil && d.conn != main) {
h.mu.Unlock()
return
return false
}
sc := d.screenConn
d.screenConn = nil
@@ -607,6 +662,7 @@ func (h *Hub) CloseScreen(deviceID string) {
d.lastKeyframe = nil
h.mu.Unlock()
h.retireScreenConn(sc)
return true
}
// PublishResolution announces a new (or first-ever) screen geometry for a
@@ -853,11 +909,22 @@ func (h *Hub) TerminalIsPTY(id string) bool {
// send COMMAND_BYE, then close after a short grace period so the client's
// IOCPClient reconnect logic doesn't fire.
func (h *Hub) CloseTerminalSession(deviceID string) {
h.closeTerminalPinned(deviceID, nil)
}
// CloseTerminalSessionPinned is CloseTerminalSession restricted to a device
// still pinned to main; see CloseScreenPinned for why the disconnect path
// needs the ownership check.
func (h *Hub) CloseTerminalSessionPinned(deviceID string, main *connection.Context) bool {
return h.closeTerminalPinned(deviceID, main)
}
func (h *Hub) closeTerminalPinned(deviceID string, main *connection.Context) bool {
h.mu.Lock()
d, ok := h.devices[deviceID]
if !ok {
if !ok || (main != nil && d.conn != main) {
h.mu.Unlock()
return
return false
}
tc := d.terminalConn
// hadSession guards against firing spurious OnTerminalClosed events
@@ -872,7 +939,7 @@ func (h *Hub) CloseTerminalSession(deviceID string) {
h.mu.Unlock()
if !hadSession {
return
return true
}
for _, s := range h.snapshotSubscribers() {
@@ -880,7 +947,7 @@ func (h *Hub) CloseTerminalSession(deviceID string) {
}
if tc == nil {
return
return true
}
h.terminalIndexMu.Lock()
delete(h.terminalIndex, tc)
@@ -896,6 +963,18 @@ func (h *Hub) CloseTerminalSession(deviceID string) {
time.Sleep(500 * time.Millisecond)
c.Close()
}(tc)
return true
}
// PublishTerminalClosed tells terminal viewers the session is over without
// touching hub session state. Used when the device opens a shell sub-conn that
// cannot be bound because the terminal request it answers no longer exists
// (the main conn reconnected in between); otherwise the browser pane would
// wait on term_ready forever.
func (h *Hub) PublishTerminalClosed(deviceID, reason string) {
for _, s := range h.snapshotSubscribers() {
s.OnTerminalClosed(deviceID, reason)
}
}
// PublishTerminalData fans out one chunk of shell output to subscribers.
+190
View File
@@ -0,0 +1,190 @@
package hub
import (
"bytes"
"testing"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/connection"
)
// A reconnecting client logs in with a fresh Device struct. Its screen / shell
// sub-conns ride their own TCP connections and survive the main-conn reconnect,
// so Register must carry the session state over — otherwise a web terminal goes
// dead on every reconnect: SendToTerminal returns ErrDeviceOffline for every
// keystroke (handleTermInput drops the error silently) while shell output keeps
// streaming, so the browser looks connected but typing does nothing, and the
// shell can no longer be torn down (orphan shells + leaked sockets).
func TestRegisterKeepsTerminalSession(t *testing.T) {
h := New()
var sent []*connection.Context
h.SetSender(func(ctx *connection.Context, data []byte) error {
sent = append(sent, ctx)
return nil
})
mainConn := &connection.Context{RemoteAddr: "10.0.0.1:1000"}
h.Register(&Device{ID: "dev", PeerIP: "10.0.0.1"}, mainConn)
if err := h.OpenTerminalSession("dev"); err != nil {
t.Fatalf("OpenTerminalSession: %v", err)
}
term := &connection.Context{RemoteAddr: "10.0.0.1:1001"}
if !h.BindTerminalConn("dev", term, true) {
t.Fatal("BindTerminalConn rejected the pending session")
}
// Main conn drops and the client logs in again (fresh Device struct).
reconnected := &connection.Context{RemoteAddr: "10.0.0.1:1002"}
h.Register(&Device{ID: "dev", PeerIP: "10.0.0.1"}, reconnected)
if got := h.MainConn("dev"); got != reconnected {
t.Fatalf("MainConn = %p, want the reconnected ctx %p", got, reconnected)
}
sent = nil
if err := h.SendToTerminal("dev", []byte("ls\r")); err != nil {
t.Fatalf("SendToTerminal after re-register: %v (terminal binding was dropped)", err)
}
if len(sent) != 1 || sent[0] != term {
t.Fatalf("keystroke went to %v, want the bound shell sub-conn", sent)
}
if !h.TerminalIsPTY("dev") {
t.Fatal("terminalIsPTY lost across re-register (resize would be silently ignored)")
}
if got := h.TerminalDeviceID(term); got != "dev" {
t.Fatalf("TerminalDeviceID(shell) = %q, want dev (output would be parsed as commands)", got)
}
}
// Same failure mode for the screen path: losing the cached geometry and last
// IDR leaves a viewer that joins right after the reconnect with nothing to
// decode until the device happens to emit the next IDR.
func TestRegisterKeepsScreenCache(t *testing.T) {
h := New()
h.Register(&Device{ID: "dev", PeerIP: "10.0.0.1"},
&connection.Context{RemoteAddr: "10.0.0.1:1000"})
screen := &connection.Context{RemoteAddr: "10.0.0.1:1001"}
if !h.BindScreenConn("dev", screen) {
t.Fatal("BindScreenConn failed")
}
h.PublishResolution("dev", 1920, 1080)
keyframe := []byte{0xde, 0xad, 0xbe, 0xef}
h.PublishScreenFrame("dev", keyframe, true)
h.Register(&Device{ID: "dev", PeerIP: "10.0.0.1"},
&connection.Context{RemoteAddr: "10.0.0.1:1002"})
st := h.ScreenState("dev")
if !st.Active {
t.Fatal("screen session marked inactive after re-register")
}
if st.Width != 1920 || st.Height != 1080 {
t.Fatalf("cached geometry = %dx%d, want 1920x1080", st.Width, st.Height)
}
if !bytes.Equal(st.Keyframe, keyframe) {
t.Fatalf("cached IDR = %x, want %x (late joiners would wait for the next IDR)", st.Keyframe, keyframe)
}
}
// Once a sub-conn really goes away, its unbind must still clear the session so
// a later re-register cannot resurrect a stale binding.
func TestRegisterDoesNotReviveClosedSessions(t *testing.T) {
h := New()
h.SetSender(func(ctx *connection.Context, data []byte) error { return nil })
h.Register(&Device{ID: "dev", PeerIP: "10.0.0.1"},
&connection.Context{RemoteAddr: "10.0.0.1:1000"})
if err := h.OpenTerminalSession("dev"); err != nil {
t.Fatalf("OpenTerminalSession: %v", err)
}
term := &connection.Context{RemoteAddr: "10.0.0.1:1001"}
if !h.BindTerminalConn("dev", term, true) {
t.Fatal("BindTerminalConn rejected the pending session")
}
h.UnbindTerminalConn(term) // shell sub-conn dropped
h.UnbindScreenConn(&connection.Context{RemoteAddr: "10.0.0.1:1003"}) // no-op, not bound
h.Register(&Device{ID: "dev", PeerIP: "10.0.0.1"},
&connection.Context{RemoteAddr: "10.0.0.1:1002"})
if err := h.SendToTerminal("dev", []byte("ls\r")); err != ErrDeviceOffline {
t.Fatalf("SendToTerminal = %v, want ErrDeviceOffline (no session)", err)
}
}
// The old main conn's OnDisconnect runs concurrently with a re-login. Its
// cleanup must be scoped to the connection it is about, otherwise the stale
// callback strips the sessions Register just carried over — and deleting by
// ID alone hides a live client until its next reconnect.
func TestStaleDisconnectCannotTearDownNewRegistration(t *testing.T) {
h := New()
h.SetSender(func(ctx *connection.Context, data []byte) error { return nil })
oldConn := &connection.Context{RemoteAddr: "10.0.0.1:1000"}
h.Register(&Device{ID: "dev", PeerIP: "10.0.0.1"}, oldConn)
if err := h.OpenTerminalSession("dev"); err != nil {
t.Fatalf("OpenTerminalSession: %v", err)
}
term := &connection.Context{RemoteAddr: "10.0.0.1:1001"}
if !h.BindTerminalConn("dev", term, true) {
t.Fatal("BindTerminalConn failed")
}
if !h.BindScreenConn("dev", &connection.Context{RemoteAddr: "10.0.0.1:1003"}) {
t.Fatal("BindScreenConn failed")
}
// Re-login lands first; the old conn's teardown runs afterwards.
newConn := &connection.Context{RemoteAddr: "10.0.0.1:1002"}
h.Register(&Device{ID: "dev", PeerIP: "10.0.0.1"}, newConn)
if h.CloseScreenPinned("dev", oldConn) {
t.Fatal("stale disconnect closed the screen session of the new registration")
}
if h.CloseTerminalSessionPinned("dev", oldConn) {
t.Fatal("stale disconnect closed the terminal session of the new registration")
}
if h.UnregisterPinned("dev", oldConn) {
t.Fatal("stale disconnect removed the re-registered device")
}
if got := h.MainConn("dev"); got != newConn {
t.Fatalf("MainConn = %p, want the new conn %p", got, newConn)
}
if !h.ScreenState("dev").Active {
t.Fatal("screen session lost to the stale disconnect")
}
if err := h.SendToTerminal("dev", []byte("ls\r")); err != nil {
t.Fatalf("SendToTerminal after stale disconnect: %v", err)
}
// The real owner can still clean up.
if !h.UnregisterPinned("dev", newConn) {
t.Fatal("UnregisterPinned rejected the owning main conn")
}
if h.MainConn("dev") != nil {
t.Fatal("device still registered after the owner's disconnect")
}
}
// Only a *bound* session rides across a reconnect: a terminal request that
// never produced a shell sub-conn is re-issued by the browser instead of
// pinning the device "busy" forever.
func TestRegisterDoesNotCarryPendingTerminal(t *testing.T) {
h := New()
h.SetSender(func(ctx *connection.Context, data []byte) error { return nil })
h.Register(&Device{ID: "dev", PeerIP: "10.0.0.1"},
&connection.Context{RemoteAddr: "10.0.0.1:1000"})
if err := h.OpenTerminalSession("dev"); err != nil {
t.Fatalf("OpenTerminalSession: %v", err)
}
if !h.IsTerminalPending("dev") {
t.Fatal("session should be pending after OpenTerminalSession")
}
h.Register(&Device{ID: "dev", PeerIP: "10.0.0.1"},
&connection.Context{RemoteAddr: "10.0.0.1:1002"})
if h.IsTerminalPending("dev") {
t.Fatal("pending request carried across re-register; device would stay 'busy' forever")
}
if err := h.OpenTerminalSession("dev"); err != nil {
t.Fatalf("retry after re-register: %v, want nil", err)
}
}
+20
View File
@@ -134,6 +134,26 @@ const (
CmdSockDllLoader byte = 210 // SOCKET_DLLLOADER - shellcode/memory-DLL loader requests the full DLL payload
)
// HeartbeatACK (CMD_HEARTBEAT_ACK) response layout — mirrors the HeartbeatACK
// struct in common/commands.h, where sizeof(HeartbeatACK) == 1024.
//
// Size matters: clients deployed before 2026-11 gate the ACK on
// `ulLength >= 1 + sizeof(HeartbeatACK)` (1025 bytes) and silently drop
// anything shorter. That never feeds their application-level ACK watchdog,
// so they reconnect every 60s forever — a 33-byte reply here did exactly
// that on the Go server. Current clients accept both sizes (they clamp to
// min(ulLength-1, sizeof)), and the C++ server always sends 1+1024
// (2015RemoteDlg.cpp), so the wire is 1+1024 for everyone. Windows was the
// only client tolerant of the short form from the start (KernelManager.cpp
// copies min(ulLength, 32)).
const (
HeartbeatACKSize = 1024
HeartbeatACKOffTime = 0 // uint64 LE — the request's Time, echoed back
HeartbeatACKOffAuthorized = 8 // byte — 0/1/2 (2 = authorized by admin)
HeartbeatACKOffIsTrail = 9 // byte — trial master
HeartbeatACKOffProcessing = 212 // uint32 LE — server-side processing time (ms)
)
// Sub-connection authentication (matches common/commands.h ConnAuth* structs).
// Each newly-opened sub-conn first sends a 512-byte ConnAuthPacket, then waits
// for a 256-byte ConnAuthAck before any further command is meaningful.
+68 -33
View File
@@ -11,27 +11,41 @@ import json
import sys
if len(sys.argv) < 3:
sys.exit("用法: python make_tools_json.py <tools_raw.json> <mcp/tools.json>")
sys.exit("用法: python make_tools_json.py <tools_raw.json> <mcp/tools.json> [tools_raw_machine_off.json]")
SRC = sys.argv[1]
DST = sys.argv[2]
# 可选:McpMachine=0 状态下的抓取。开启态的抓取里没有降级工具(P2-2),
# 而它们仍是真实工具,必须进清单——所以清单 = 两份抓取的并集。
OFF_SRC = sys.argv[3] if len(sys.argv) > 3 else None
# 只在 McpMachine=0 时出现的降级工具(gate = "!machine")。改动这个集合要同步更新
# McpServer.cpp 里 showDegradedLists / showMainControls 两段。
# P2-2:operate_window / control_service 与 host_inspect / host_control_* 之间同样按
# McpMachine 二选一暴露(动作并集,两套名字都可调用)。
MACHINE_OFF_FALLBACKS = {"list_processes", "list_windows", "list_services",
"operate_window", "control_service"}
# gate: 该工具要求哪个服务端开关为开(null = 无条件出现)
# write: 需要 !McpReadonly
# manage: 额外需要 McpManage(仅 McpMachine 族的两处用到)
GATE = {
# ---- McpServer.cpp:BuildToolsListResult 无条件段 ----
"list_online_hosts": (None, False, False),
"search_hosts": (None, False, False),
"list_all_hosts": (None, False, False),
# P1-1:list_online_hosts / search_hosts / list_all_hosts 三合一(旧名为别名,不出现在 tools/list)
"list_hosts": (None, False, False),
"get_host_detail": (None, False, False),
"list_processes": (None, False, False),
"list_windows": (None, False, False),
# ---- McpMachine=0 时的降级路径(P2-2)----
# 开启主机管理后它们由 host_inspect 的 processes / windows / win32_services 项取代,
# 所以只在开关关闭时进 tools/list(名字仍可作为别名调用)。
# 同理,operate_window / control_service(见下方单开关段)在开启后被
# host_control_window / host_control_service 取代。
"list_processes": ("!machine", False, False),
"list_windows": ("!machine", False, False),
"list_services": ("!machine", False, False),
"get_activity_history": (None, False, False),
"get_screenshot": (None, False, False),
"get_foreground_window": (None, False, False),
"list_files": (None, False, False),
"list_services": (None, False, False),
"get_client_log": (None, False, False),
"get_audit_log": (None, False, False),
"get_server_status": (None, False, False),
@@ -52,6 +66,8 @@ GATE = {
"terminal_open": ("terminal", True, False),
"terminal_exec": ("terminal", True, False),
"terminal_close": ("terminal", True, False),
# http_probe 在主机上跑 shell(Windows PowerShell / Linux curl),与终端族同门控
"http_probe": ("terminal", True, False),
# ---- remote_control ----
"remote_open": ("remote_control", True, False),
@@ -64,13 +80,17 @@ GATE = {
# ---- file_transfer ----
"download_file": ("file_transfer", True, False),
# read_file 只读远端(不写),因此不受 readonly 约束
"read_file": ("file_transfer", False, False),
"upload_file": ("file_transfer", True, False),
"copy_files_c2c": ("file_transfer", True, False),
# ---- manage(McpServer 侧的危险操作)----
"kill_process": ("manage", True, False),
"operate_window": ("manage", True, False),
"control_service": ("manage", True, False),
# P2-2:主机管理开启时由 host_control_window / host_control_service 承担
# (后两者也接受 close/show、set_auto/set_manual),所以只在 McpMachine=0 时暴露。
"operate_window": ("!machine", True, True),
"control_service": ("!machine", True, True),
"power_action": ("manage", True, False),
"uninstall_host": ("manage", True, False),
@@ -81,16 +101,8 @@ GATE = {
# ---- McpMachine 族:总开关 McpMachine ----
"list_network_connections": ("machine", False, False),
"host_list_processes": ("machine", False, False),
"host_list_windows": ("machine", False, False),
"host_list_network_state": ("machine", False, False),
"host_list_software": ("machine", False, False),
"host_list_browser_history": ("machine", False, False),
"host_list_favorites": ("machine", False, False),
"host_list_win32_services": ("machine", False, False),
"host_list_driver_services": ("machine", False, False),
"host_list_scheduled_tasks": ("machine", False, False),
"host_get_hosts_file": ("machine", False, False),
# P2-1:10 个 host_list_* / host_get_hosts_file 合并(旧名为别名,不出现在 tools/list)
"host_inspect": ("machine", False, False),
"kill_network_connection": ("machine", True, True), # writable && IsManageEnabled()
"host_control_process": ("machine", True, False), # writable
"host_control_window": ("machine", True, False),
@@ -138,9 +150,7 @@ _APKONLY = ["apk"]
PLATFORMS = {
# 服务端本地数据,与客户端平台无关
"list_online_hosts": _APK,
"search_hosts": _APK,
"list_all_hosts": _APK,
"list_hosts": _APK,
"get_host_detail": _APK,
"get_audit_log": _APK,
"get_server_status": _APK,
@@ -168,11 +178,15 @@ PLATFORMS = {
"terminal_close": _WLA,
"exec_command": _WLA,
# http_probe 走终端通道:macOS 终端未开放;Android 的 toybox 不保证有 curl/base64
"http_probe": _WL,
# macOS 客户端有 COMMAND_KILLPROCESS 分支,但服务端同样拦着(McpServer.cpp:6870)
"kill_process": _WL,
# 需要 CLIENT_CAP_V2;三个桌面平台的 DefaultCaps() 都含 V2
"download_file": _TRIO,
"read_file": _TRIO,
"upload_file": _TRIO,
# 远程控制:Windows / Linux 全功能;Android 只支持整屏目标,输入翻译成触摸与全局动作
@@ -211,16 +225,8 @@ PLATFORMS = {
# McpMachine 族(COMMAND_MACHINE_MANAGE 仅 Windows 实现)
"list_network_connections": _WIN,
"kill_network_connection": _WIN,
"host_list_processes": _WIN,
"host_list_windows": _WIN,
"host_list_network_state": _WIN,
"host_list_software": _WIN,
"host_list_browser_history": _WIN,
"host_list_favorites": _WIN,
"host_list_win32_services": _WIN,
"host_list_driver_services": _WIN,
"host_list_scheduled_tasks": _WIN,
"host_get_hosts_file": _WIN,
# P2-1:10 个 host_list_* / host_get_hosts_file 合并为 host_inspect(仅 Windows)
"host_inspect": _WIN,
"host_control_process": _WIN,
"host_control_window": _WIN,
"host_control_service": _WIN,
@@ -250,7 +256,33 @@ ROLES = {
}
raw = json.load(open(SRC, encoding="utf-8"))
tools_in = raw["result"]["tools"]
tools_on = raw["result"]["tools"]
# 并集:开启态抓取 + 关闭态抓取里独有的降级工具。关闭态工具的描述/schema 也必须来自
# 活服务端,不能沿用旧清单,否则清单会和二进制悄悄漂移。
if OFF_SRC:
tools_off = json.load(open(OFF_SRC, encoding="utf-8"))["result"]["tools"]
on_names = {t["name"] for t in tools_on}
off_names = {t["name"] for t in tools_off}
off_only = [t for t in tools_off if t["name"] not in on_names]
bad = [t["name"] for t in off_only if GATE.get(t["name"], (None,))[0] != "!machine"]
if bad:
print(f"!! 关闭态抓取里有未声明为 !machine 的工具: {bad}", file=sys.stderr)
sys.exit(1)
absent = sorted(MACHINE_OFF_FALLBACKS - off_names)
if absent:
print(f"!! 关闭态抓取里缺少降级工具: {absent}", file=sys.stderr)
sys.exit(1)
leaked = sorted(n for n in MACHINE_OFF_FALLBACKS if n in on_names)
if leaked:
print(f"!! 开启态抓取里出现了降级工具(应已隐藏): {leaked}", file=sys.stderr)
sys.exit(1)
tools_on = tools_on + off_only
elif MACHINE_OFF_FALLBACKS & {t["name"] for t in tools_on}:
print("!! 未提供关闭态抓取,但开启态里有降级工具——清单会丢工具", file=sys.stderr)
sys.exit(1)
tools_in = tools_on
missing = [t["name"] for t in tools_in if t["name"] not in GATE]
if missing:
@@ -312,6 +344,9 @@ doc = {
"由 tools/mcp_tools/dump_tools.py 抓取、make_tools_json.py 生成,勿手工编辑。",
"gate: 该工具出现的开关条件(null = 无条件);write: 需 !McpReadonly;",
"manage: 额外需 McpManage。这三项从 C++ 注册点的 if 条件解析而来,运行时不可见。",
"gate 为 \"!machine\" 表示该降级工具只在 McpMachine=0 时出现(开启主机管理后",
"由 host_inspect 的对应 aspect 取代,名字仍可作为别名调用);清单是开启态与",
"关闭态两份抓取的并集。",
"platforms: 该工具涉及的任一主机都必须落在此集合内(win/lnx/mac/apk),依据各平台",
"客户端对相应 COMMAND_ 的处理实现。apk 上 COMMAND_SYSTEM 与 COMMAND_SHELL 均为空实现。",
"roles: 仅多主机工具才有。按参数名细分平台,表达 platforms 说不清的方向性能力",
+32 -8
View File
@@ -10,7 +10,8 @@
port 省略时自动探测 6545(明文后端)/ 6544(TLS 前端)
比对内容:name / description / inputSchema / outputSchema,逐字段深度比较,
外加工具顺序。gate / write / manage / impl 是 tools.json 独有的元信息,不参与比对。
外加工具顺序。gate / write / manage / impl 是 tools.json 独有的元信息,不参与比对;
例外是 gate == "!machine" 的降级工具——它们只在 McpMachine=0 时出现,不进本次比对。
"""
import http.client
import json
@@ -69,7 +70,21 @@ def fetch_live(token, port=None):
conn.close()
if resp.status == 200:
print(f"连接 127.0.0.1:{p} ({'TLS' if tls else 'plain'})")
return json.loads(raw.decode("utf-8"))["result"]["tools"]
obj = json.loads(raw.decode("utf-8"))
tools = obj["result"]["tools"]
stats = {
"response_bytes": len(raw),
"tools_array_bytes": len(
json.dumps(tools, ensure_ascii=False, separators=(",", ":")).encode("utf-8")),
"description_bytes": sum(len(t.get("description", "").encode("utf-8")) for t in tools),
"input_schema_bytes": sum(
len(json.dumps(t.get("inputSchema", {}), ensure_ascii=False, separators=(",", ":")).encode("utf-8"))
for t in tools),
"output_schema_bytes": sum(
len(json.dumps(t.get("outputSchema", {}), ensure_ascii=False, separators=(",", ":")).encode("utf-8"))
for t in tools),
}
return tools, stats
last = f"{p}: HTTP {resp.status} {raw[:200].decode('utf-8', 'replace')}"
except Exception as e:
last = f"{p}: {e}"
@@ -95,21 +110,30 @@ def main():
port = int(args[3]) if len(args) > 3 else None
if not token:
sys.exit("未找到 McpToken(参数 / YAMA_MCP_TOKEN / 注册表 均无)")
tools_live = fetch_live(token, port)
tools_live, live_stats = fetch_live(token, port)
print(f"活服务: 127.0.0.1:{port if port else 'auto'}")
print(f"体积: 响应 {live_stats['response_bytes']} B / tools 数组 {live_stats['tools_array_bytes']} B"
f"(description {live_stats['description_bytes']} / inputSchema {live_stats['input_schema_bytes']}"
f" / outputSchema {live_stats['output_schema_bytes']})")
else:
sys.exit(__doc__)
doc = json.load(open(path, encoding="utf-8"))
tools_json = doc["tools"]
# gate == "!machine" 的工具只在 McpMachine=0 时出现,而黄金样本/活服务都是开关
# 全开的抓取,按约定它们不该在这里出现(tools.json 是两份抓取的并集)。
off_gated = {t["name"] for t in tools_json if t.get("gate") == "!machine"}
tools_cmp = [t for t in tools_json if t["name"] not in off_gated]
print(f"tools.json: {path} ({len(tools_json)} 个工具)")
if off_gated:
print(f" 其中 {len(off_gated)} 个 !machine 降级工具不计入本次比对: {sorted(off_gated)}")
print(f"服务端: {len(tools_live)} 个工具")
if len(tools_json) != len(tools_live):
print(f"!! 数量不一致: {len(tools_json)} vs {len(tools_live)}")
if len(tools_cmp) != len(tools_live):
print(f"!! 数量不一致: {len(tools_cmp)} vs {len(tools_live)}")
live_by_name = {t["name"]: t for t in tools_live}
json_by_name = {t["name"]: t for t in tools_json}
json_by_name = {t["name"]: t for t in tools_cmp}
only_live = sorted(set(live_by_name) - set(json_by_name))
only_json = sorted(set(json_by_name) - set(live_by_name))
@@ -139,7 +163,7 @@ def main():
# 顺序一致性:tools/list 的数组顺序会影响模型的选择倾向
order_live = [t["name"] for t in tools_live]
order_json = [t["name"] for t in tools_json]
order_json = [t["name"] for t in tools_cmp]
if order_live != order_json:
print("!! 工具顺序不一致")
for i, (x, y) in enumerate(zip(order_live, order_json)):
@@ -151,7 +175,7 @@ def main():
print("工具顺序: 一致")
if diffs == 0 and not only_live and not only_json:
print(f"\nPASS: {len(tools_json)} 个工具完全一致")
print(f"\nPASS: {len(tools_cmp)} 个工具完全一致")
return 0
print(f"\nFAIL: {diffs} 处差异")
return 1