P10-B adds delete_path, move_path and create_folder, and the switch they need. Reusing McpFileTransfer would have been wrong: uploading overwrites a file, deleting destroys a tree, and an operator who wants one may well not want the other. McpFileWrite is therefore a separate key, off by default, wired the way every other switch is - read from settings.ini at startup, reported as get_server_status.switches.file_write, and exposed with its own checkbox in the MCP settings dialog. The tools additionally require readonly to be off: a read-only server has no business modifying a host. No client change was needed: COMMAND_DELETE_FILE, COMMAND_DELETE_DIRECTORY, COMMAND_CREATE_FOLDER and COMMAND_RENAME_FILE already existed in the Windows file manager. The chain reuses the file-manager sub-connection and adds a phase - the main connection asks for the drive list, the sub-connection's first packet hands it to OnDriveList which sends the write command, and the client's TOKEN_*_FINISH ack moves the pending request from phase 0 to 1, where the tool sends COMMAND_LIST_FILES for the parent so the ack and the confirmation share one timeout. Only the IO thread touches the sub-connection; the tool thread just waits on the shared condvar, which keeps the sub-connection's lifetime out of its reach. The confirmation exists because the client answers unconditionally: it ignores the return values of DeleteFile, MoveFile and MakeSureDirectoryPathExists and there is no error token. ok therefore only means "the command arrived", and verified is the real answer - true when the parent listing shows the expected post-state, false when it shows the opposite, null when the listing itself did not come back (timeout or disconnect), since reporting that as false would be a lie. Linux, macOS and Android hosts are refused outright: those clients decode these paths as GBK while the server speaks UTF-8 to them for list_files, so a non-ASCII path would corrupt rather than fail. Paths are validated as UTF-8, converted to GBK exactly once, and reject %VAR%, relative paths, drive and share roots, and - for delete_path and for move_path's source - the Windows, Program Files, ProgramData, $Recycle.Bin and System Volume Information trees. create_folder gets no system-directory ban, because writing there is the same permission upload_file already has. Two defects surfaced while exercising this against a real client: create_folder's wire path has to end with a backslash, because MakeSureDirectoryPathExists treats a non-terminated last component as a file name and only creates the intermediate levels; and ResolveFileOpVerified(LookupInListing(...), isDir, ...) read isDir before the lookup ever set it - argument evaluation order is unspecified and MSVC evaluates right to left - so every create_folder reported verified=false even when the directory existed. Verified on a Debug x64 build against a Windows client over MCP: nested create_folder, upload, rename, delete, delete a tree, the failure shapes (delete with recursive=false on a directory, create_folder onto an existing file name, delete of a non-existent target) and every refusal (drive root, C:\Windows\Temp, C:\Users, %TEMP%, relative, empty, over-long, from==to, offline host, non-numeric id), with a Chinese-named directory created, renamed and deleted end to end; no file-manager window appeared in the server process during any of it. The smoke test gained section [4c], opt-in through -FileWriteDir, which asserts verified and never ok and walks a sandbox through the same path; two runs passed 69 checks with the sandbox removed afterwards. Bin/settings.ini was restored byte-exact and the Release instance was left alone. Co-Authored-By: deepseek-flash
553 lines
32 KiB
PowerShell
553 lines
32 KiB
PowerShell
<#
|
||
服务端 MCP 冒烟测试。
|
||
|
||
默认只调用「不会改变任何状态」的工具(列表/详情类),断言结构化字段齐全、
|
||
分页字段正确、鉴权与请求体上限生效。可在发布前对着任一台在线主机跑一遍,
|
||
确认 MCP 链路与改动前相比没有回归。
|
||
|
||
唯一会写目标机的部分是 [4c] 文件写入,且必须显式给 -FileWriteDir 才会跑:
|
||
它在那个目录下建一个 mcp_smoke_xxxx 沙箱,走完 create/upload/rename/delete
|
||
后整棵删掉,不碰沙箱以外的任何东西。
|
||
|
||
用法:
|
||
$env:YAMA_MCP_TOKEN = '<token>' # 与 service 的 McpToken 一致
|
||
powershell -ExecutionPolicy Bypass -File tools\mcp_smoke.ps1
|
||
powershell -ExecutionPolicy Bypass -File tools\mcp_smoke.ps1 -Base http://127.0.0.1:6545/mcp
|
||
|
||
参数:
|
||
-Base MCP 端点,默认 http://127.0.0.1:6544/mcp(Release 实例)
|
||
-Token 覆盖 env YAMA_MCP_TOKEN
|
||
-HostId 指定在线主机 id;缺省取 list_online_hosts 的第一台
|
||
-SkipHost 只测服务端本机工具,不触达远程主机(无在线主机时用)
|
||
-SearchPath 可选,跑 search_file 测试的搜索根目录(如 C:\Windows\Fonts)。
|
||
不指定就跳过:没有安全的默认根目录,从盘符根扫描很慢,且路径超过
|
||
MAX_PATH 的条目会被客户端静默跳过(8f718d9 起不再栈溢出),通常先撞
|
||
10000 条上限,测出来的是「部分结果」而不是功能是否可用。
|
||
-AuditLog 可选,服务端审计日志路径(如 Bin\logs\mcp_audit.log)。给了才断言
|
||
-32006 拒绝会写一条 CALL_DENIED。
|
||
-FileWriteDir 可选,跑 delete_path / move_path / create_folder 的目标机目录
|
||
(必须已存在且可写,如 C:\Users\Public 或 C:\Temp)。脚本只在其下
|
||
新建 mcp_smoke_xxxx 沙箱并在结束时删掉它。不指定就跳过这一节。
|
||
注意 upload_file 的 local_path 指的是服务端本机路径,所以这一节要求
|
||
冒烟脚本与服务端在同一台机器上(默认的 127.0.0.1 即如此)。
|
||
|
||
退出码:0 全部通过;1 有失败项。token 不会被打印。
|
||
#>
|
||
param(
|
||
[string]$Base = 'http://127.0.0.1:6544/mcp',
|
||
[string]$Token = $env:YAMA_MCP_TOKEN,
|
||
[string]$HostId = '',
|
||
[switch]$SkipHost,
|
||
[string]$SearchPath = '',
|
||
[string]$AuditLog = '',
|
||
[string]$FileWriteDir = ''
|
||
)
|
||
|
||
$ErrorActionPreference = 'Stop'
|
||
$script:pass = 0
|
||
$script:fail = 0
|
||
$script:failures = @()
|
||
|
||
function Check([string]$name, [bool]$ok, [string]$detail = '') {
|
||
if ($ok) {
|
||
$script:pass++
|
||
Write-Host (" [PASS] " + $name) -ForegroundColor Green
|
||
} else {
|
||
$script:fail++
|
||
$script:failures += $name + $(if ($detail) { " -- $detail" } else { "" })
|
||
Write-Host (" [FAIL] " + $name + $(if ($detail) { " -- " + $detail } else { "" })) -ForegroundColor Red
|
||
}
|
||
}
|
||
|
||
function Send-Raw([string]$json, [string]$auth) {
|
||
# 返回 @{ Status = <int>; Body = <string> };非 2xx 不抛异常。
|
||
$bytes = [System.Text.Encoding]::UTF8.GetBytes($json)
|
||
$headers = @{}
|
||
if ($auth) { $headers['Authorization'] = 'Bearer ' + $auth }
|
||
try {
|
||
$resp = Invoke-WebRequest -Uri $Base -Method Post -Body $bytes `
|
||
-ContentType 'application/json' -Headers $headers -TimeoutSec 180 -UseBasicParsing
|
||
return @{ Status = [int]$resp.StatusCode; Body = $resp.Content }
|
||
} catch {
|
||
$r = $_.Exception.Response
|
||
if ($r) { return @{ Status = [int]$r.StatusCode; Body = '' } }
|
||
return @{ Status = 0; Body = $_.Exception.Message }
|
||
}
|
||
}
|
||
|
||
function Rpc([string]$method, $params, [string]$toolName, $toolArgs) {
|
||
# tools/call 用 toolName+args,其余方法用 method+params。
|
||
if ($toolName) {
|
||
$payload = @{ jsonrpc = '2.0'; id = 1; method = 'tools/call';
|
||
params = @{ name = $toolName; arguments = $toolArgs } }
|
||
} else {
|
||
$payload = @{ jsonrpc = '2.0'; id = 1; method = $method; params = $params }
|
||
}
|
||
$json = $payload | ConvertTo-Json -Depth 12 -Compress
|
||
$raw = Send-Raw $json $Token
|
||
if ($raw.Status -ne 200) { throw "HTTP $($raw.Status) calling $method$toolName" }
|
||
return ($raw.Body | ConvertFrom-Json)
|
||
}
|
||
|
||
function HasPaging($obj) {
|
||
if ($null -eq $obj) { return $false }
|
||
foreach ($k in @('total', 'totalAll', 'offset', 'limit', 'hasMore')) {
|
||
if (-not ($obj.PSObject.Properties.Name -contains $k)) { return $false }
|
||
}
|
||
return $true
|
||
}
|
||
|
||
# 结果外露(docs/Mcp_Design.md §14):content 末尾必须有一个可解析的 JSON 文本块,
|
||
# 内容与 structuredContent 对应。只读 content 的客户端(WorkBuddy)靠它拿到 id。
|
||
function HasJsonText($rpc) {
|
||
if ($null -eq $rpc -or $null -eq $rpc.result) { return $false }
|
||
$c = @($rpc.result.content)
|
||
if ($c.Count -lt 2) { return $false }
|
||
$last = $c[$c.Count - 1]
|
||
if ($last.type -ne 'text' -or [string]::IsNullOrEmpty($last.text)) { return $false }
|
||
try { $null = $last.text | ConvertFrom-Json } catch { return $false }
|
||
return $true
|
||
}
|
||
|
||
Write-Host "MCP smoke test -> $Base"
|
||
if (-not $Token) {
|
||
Write-Host "缺少 token:请设置环境变量 YAMA_MCP_TOKEN 或传 -Token。" -ForegroundColor Red
|
||
exit 1
|
||
}
|
||
|
||
# ===== 1. 传输层 =====
|
||
Write-Host "`n[1] 传输层"
|
||
$bad = Send-Raw '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}' 'wrong-token-for-smoke-test'
|
||
Check '未授权 token 返回 401' ($bad.Status -eq 401) ("status=" + $bad.Status)
|
||
|
||
$big = '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"list_online_hosts","arguments":{"pad":"' +
|
||
('x' * (2 * 1024 * 1024 + 1024)) + '"}}}'
|
||
$o = Send-Raw $big $Token
|
||
Check '请求体超过 2 MB 返回 413' ($o.Status -eq 413) ("status=" + $o.Status)
|
||
|
||
# ===== 2. 协议层 =====
|
||
Write-Host "`n[2] 协议层"
|
||
$init = Rpc 'initialize' @{ protocolVersion = '2025-06-18'; capabilities = @{}; clientInfo = @{ name = 'smoke'; version = '1' } } $null $null
|
||
Check 'initialize 返回 serverInfo' ($null -ne $init.result.serverInfo)
|
||
# initialize.instructions 是模型唯一的「隐性知识」入口(主机 id 形态、开关、错误码、编排)。
|
||
Check 'initialize 带非空 instructions' (([string]$init.result.instructions).Length -gt 100)
|
||
|
||
$tl = Rpc 'tools/list' @{} $null $null
|
||
$tools = @($tl.result.tools)
|
||
Check 'tools/list 至少 40 个工具' ($tools.Count -ge 40) ("count=" + $tools.Count)
|
||
$annotated = @($tools | Where-Object {
|
||
$a = $_.annotations
|
||
$a -and ($a.PSObject.Properties.Name -contains 'readOnlyHint') -and
|
||
($a.PSObject.Properties.Name -contains 'destructiveHint') -and
|
||
($a.PSObject.Properties.Name -contains 'idempotentHint') -and
|
||
($a.PSObject.Properties.Name -contains 'openWorldHint')
|
||
})
|
||
Check '每个工具都带 annotations 四元组' ($annotated.Count -eq $tools.Count) ("annotated=" + $annotated.Count + "/" + $tools.Count)
|
||
$ro = @($tools | Where-Object { $_.annotations.readOnlyHint -eq $true })
|
||
Check '存在只读工具且无只读工具被标为破坏性' ($ro.Count -gt 0 -and
|
||
(@($ro | Where-Object { $_.annotations.destructiveHint -eq $true }).Count -eq 0)) ("readOnly=" + $ro.Count)
|
||
|
||
# ===== 2b. 协议层错误码 =====
|
||
Write-Host "`n[2b] 协议层错误码"
|
||
$um = Rpc 'bogus/method' @{} $null $null
|
||
Check '未知 method 返回 -32601' ([int]$um.error.code -eq -32601) ([string]$um.error.code)
|
||
$ut = Rpc '' $null 'no_such_tool' @{}
|
||
Check '未知工具返回 -32602' ([int]$ut.error.code -eq -32602) ([string]$ut.error.code)
|
||
$mi = Rpc '' $null 'get_host_detail' @{}
|
||
Check '缺少必填参数返回 -32602' ([int]$mi.error.code -eq -32602) ([string]$mi.error.message)
|
||
|
||
# ===== 2c. 批量入口上限 =====
|
||
$ids51 = (1..51 | ForEach-Object { '"99999999999999' + $_ + '"' }) -join ','
|
||
# Rpc 会把 ids 数组重新序列化,这里直接发原始请求体,避免 51 个 id 走两层转换
|
||
$raw51 = '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"list_processes","arguments":{"ids":[' +
|
||
$ids51 + ']}}}'
|
||
$r51 = Send-Raw $raw51 $Token
|
||
$j51 = $r51.Body | ConvertFrom-Json
|
||
Check '批量 51 个 id 返回 -32602' ([int]$j51.error.code -eq -32602) ([string]$j51.error.message)
|
||
|
||
# ===== 3. 服务端本机只读工具 =====
|
||
Write-Host "`n[3] 服务端本机工具"
|
||
$online = Rpc '' $null 'list_online_hosts' @{ limit = 100 }
|
||
$sc = $online.result.structuredContent
|
||
Check 'list_online_hosts 带分页字段' (HasPaging $sc)
|
||
Check 'list_online_hosts 每条都有 id/online' (@($sc.hosts | Where-Object { -not $_.id -or $_.online -ne $true }).Count -eq 0)
|
||
|
||
$noMatch = Rpc '' $null 'list_online_hosts' @{ group = 'zzz-no-such-group' }
|
||
Check 'list_online_hosts 过滤未命中返回 0 条' ($noMatch.error -eq $null -and [int]$noMatch.result.structuredContent.total -eq 0)
|
||
Check 'list_online_hosts 过滤后 totalAll 仍是全部在线数' ([int]$noMatch.result.structuredContent.totalAll -eq [int]$sc.totalAll)
|
||
|
||
$all = Rpc '' $null 'list_all_hosts' @{ limit = 5 }
|
||
Check 'list_all_hosts 带分页字段' (HasPaging $all.result.structuredContent)
|
||
Check 'list_all_hosts 的 content 附带结构化 JSON' (HasJsonText $all)
|
||
$allJson = $null
|
||
if (HasJsonText $all) { $allJson = $all.result.content[-1].text | ConvertFrom-Json }
|
||
Check 'content 的 JSON 里能取到主机 id(串联下一跳)' ($null -eq $allJson -or
|
||
@($allJson.hosts).Count -eq 0 -or [string]$allJson.hosts[0].id -ne '')
|
||
|
||
$found = Rpc '' $null 'search_hosts' @{ query = ''; limit = 5 }
|
||
Check 'search_hosts 正常返回' ($found.error -eq $null -and (HasPaging $found.result.structuredContent))
|
||
Check 'search_hosts 的 content 附带结构化 JSON' (HasJsonText $found)
|
||
|
||
$audit = Rpc '' $null 'get_audit_log' @{ limit = 5 }
|
||
Check 'get_audit_log 正常返回' ($audit.error -eq $null)
|
||
Check 'get_audit_log 带分页字段' (HasPaging $audit.result.structuredContent)
|
||
Check 'get_audit_log 条数不超过 limit' (@($audit.result.structuredContent.entries).Count -le 5)
|
||
$auditFiltered = Rpc '' $null 'get_audit_log' @{ type = 'zzz-no-such-type'; limit = 5 }
|
||
Check 'get_audit_log 过滤未命中返回 0 条' ($auditFiltered.error -eq $null -and @($auditFiltered.result.structuredContent.entries).Count -eq 0)
|
||
|
||
$status = Rpc '' $null 'get_server_status' @{}
|
||
$st = $status.result.structuredContent.status
|
||
Check 'get_server_status 正常返回' ($status.error -eq $null -and $null -ne $st)
|
||
$basePort = 6544
|
||
if ($Base -match ':(\d+)(/|$)') { $basePort = [int]$Matches[1] }
|
||
Check 'get_server_status 版本/端口/开关齐全' `
|
||
([string]$st.version -ne '' -and [int]$st.port -eq $basePort -and $null -ne $st.switches -and $null -ne $st.sessions)
|
||
Check 'get_server_status 不含 token' (($st | ConvertTo-Json -Depth 6) -notmatch '(?i)token')
|
||
Check 'get_server_status 的 content 附带结构化 JSON' (HasJsonText $status)
|
||
|
||
if (-not $HostId) {
|
||
$first = @($sc.hosts)[0]
|
||
if ($first) { $HostId = [string]$first.id }
|
||
}
|
||
if (-not $HostId) {
|
||
Write-Host "`n 没有在线主机,跳过主机类工具。" -ForegroundColor Yellow
|
||
$SkipHost = $true
|
||
}
|
||
|
||
# ===== 4. 主机只读工具 =====
|
||
if (-not $SkipHost) {
|
||
Write-Host "`n[4] 主机工具 (id=$HostId)"
|
||
|
||
$det = Rpc '' $null 'get_host_detail' @{ id = $HostId }
|
||
$h = $det.result.structuredContent.host
|
||
Check 'get_host_detail id 回显正确' (([string]$h.id) -eq $HostId)
|
||
Check 'get_host_detail 含 os/version/online' ($h.os -and $h.version -and ($null -ne $h.online))
|
||
|
||
# capabilities:这台主机本身能做什么(服务端开关在 get_server_status.switches)。
|
||
# 逐项都要能对上真实门控,所以除了「齐全」还要断言 platform 与 registry 的一致性。
|
||
$caps = $h.capabilities
|
||
Check 'get_host_detail 带 capabilities.platform' ($null -ne $caps -and [string]$caps.platform -ne '')
|
||
$capFlags = @('screenPreview', 'remoteControl', 'fileTransferV2', 'c2cPaths', 'registry')
|
||
$missing = @($capFlags | Where-Object {
|
||
$null -eq $caps -or $null -eq $caps.$_ -or $caps.$_.GetType() -ne [bool]
|
||
})
|
||
Check 'capabilities 五个布尔位齐全' ($missing.Count -eq 0) ("missing=" + ($missing -join ','))
|
||
$isWin = @('DLL', 'EXE', 'MEXE', 'SC', 'MDLL') -contains [string]$caps.platform
|
||
Check 'capabilities.registry 与平台一致(仅 Windows)' ($caps.registry -eq $isWin) `
|
||
("platform=" + $caps.platform + " registry=" + $caps.registry)
|
||
if (@('MAC', 'APK') -contains [string]$caps.platform) {
|
||
Check 'capabilities.remoteControl 对 MAC/APK 为 false' ($caps.remoteControl -eq $false) `
|
||
("platform=" + $caps.platform)
|
||
}
|
||
|
||
$procs = Rpc '' $null 'list_processes' @{ id = $HostId; limit = 3 }
|
||
$ps = $procs.result.structuredContent
|
||
Check 'list_processes 分页字段' (HasPaging $ps)
|
||
Check 'list_processes 条数不超过 limit' (@($ps.processes).Count -le 3)
|
||
Check 'list_processes 总数为正' ([int]$ps.total -gt 0)
|
||
|
||
# 服务端过滤(P10-A §5.3):过滤在分页之前生效——total 是命中数,totalAll 仍是全量。
|
||
$firstProc = @($ps.processes)[0]
|
||
if ($firstProc -and [string]$firstProc.name) {
|
||
$pname = [string]$firstProc.name
|
||
$byName = Rpc '' $null 'list_processes' @{ id = $HostId; name = $pname; limit = 100 }
|
||
$bn = $byName.result.structuredContent
|
||
# totalAll 是「过滤前的总数」,两次调用之间目标机的进程本来就会增减(实测差过 1),
|
||
# 所以留一点余量:要断言的是「过滤没有把 totalAll 一起缩掉」,不是快照完全相等。
|
||
$drift = [Math]::Abs([int]$bn.totalAll - [int]$ps.totalAll)
|
||
Check 'list_processes name 过滤命中且 totalAll 不变' `
|
||
($byName.error -eq $null -and $drift -le 10 -and
|
||
[int]$bn.total -gt 0 -and [int]$bn.total -le [int]$bn.totalAll) `
|
||
("total=" + $bn.total + " totalAll=" + $bn.totalAll + " baseAll=" + $ps.totalAll + " drift=" + $drift)
|
||
$lower = $pname.ToLowerInvariant()
|
||
Check 'list_processes name 过滤结果都含该名字' `
|
||
(@($bn.processes | Where-Object { -not ([string]$_.name).ToLowerInvariant().Contains($lower) }).Count -eq 0)
|
||
}
|
||
if ($firstProc -and $null -ne $firstProc.pid) {
|
||
$ppid = [int]$firstProc.pid
|
||
$byPid = Rpc '' $null 'list_processes' @{ id = $HostId; pid = $ppid; limit = 100 }
|
||
$bp = $byPid.result.structuredContent
|
||
Check 'list_processes pid 过滤只返回该进程' `
|
||
($byPid.error -eq $null -and [int]$bp.total -ge 1 -and
|
||
@($bp.processes | Where-Object { [int]$_.pid -ne $ppid }).Count -eq 0) `
|
||
("pid=" + $ppid + " total=" + $bp.total)
|
||
}
|
||
|
||
$wins = Rpc '' $null 'list_windows' @{ id = $HostId; limit = 3 }
|
||
Check 'list_windows 正常返回' ($wins.error -eq $null -and (HasPaging $wins.result.structuredContent))
|
||
|
||
$drv = Rpc '' $null 'list_files' @{ id = $HostId }
|
||
$ds = $drv.result.structuredContent
|
||
Check 'list_files 无 path 时返回驱动器列表' (@($ds.drives).Count -gt 0 -and (HasPaging $ds))
|
||
|
||
$drive = ''
|
||
if (@($ds.drives).Count -gt 0) { $drive = [string](@($ds.drives)[0].drive) }
|
||
if ($drive) {
|
||
$dir = Rpc '' $null 'list_files' @{ id = $HostId; path = $drive; limit = 5 }
|
||
Check ("list_files 目录列举 (" + $drive + ")") ($dir.error -eq $null -and (HasPaging $dir.result.structuredContent))
|
||
|
||
# search_file:没有安全的默认搜索根。从盘符根扫描很慢,客户端会静默跳过超过
|
||
# MAX_PATH 的路径(8f718d9 起不再栈溢出),通常先撞 10000 条上限。所以默认不跑,
|
||
# 需要时用 -SearchPath 指定一个中浅层目录(如 C:\Windows\Fonts)。
|
||
if ($SearchPath) {
|
||
$search = Rpc '' $null 'search_file' @{ id = $HostId; path = $SearchPath; pattern = '*.exe'; limit = 3; timeout_ms = 5000 }
|
||
$ss = $search.result.structuredContent
|
||
if ($search.error) {
|
||
Check 'search_file 正常返回' $false $search.error.message
|
||
} else {
|
||
Check 'search_file 带 finished/truncated 字段' (($null -ne $ss.finished) -and ($null -ne $ss.truncated))
|
||
Check 'search_file 命中项字段完整' (@($ss.files | Where-Object { -not $_.path -or $null -eq $_.size }).Count -eq 0)
|
||
|
||
# C4:结果侧过滤(大小 / 修改时间 / 精简字段),全部在服务端做
|
||
$base0 = [int]$ss.totalAll
|
||
$big = Rpc '' $null 'search_file' @{ id = $HostId; path = $SearchPath; pattern = '*.exe';
|
||
limit = 3; timeout_ms = 5000; min_size = 1073741824 }
|
||
$bs = $big.result.structuredContent
|
||
Check 'search_file min_size 过滤后 totalAll 不变' `
|
||
($big.error -eq $null -and [int]$bs.totalAll -eq $base0 -and [int]$bs.total -le $base0)
|
||
$slim = Rpc '' $null 'search_file' @{ id = $HostId; path = $SearchPath; pattern = '*.exe';
|
||
limit = 3; timeout_ms = 5000; name_only = $true }
|
||
$sl = @($slim.result.structuredContent.files)
|
||
Check 'search_file name_only 只返回 path/name' `
|
||
($slim.error -eq $null -and @($sl | Where-Object { $_.size -or $_.modified -or $_.dir }).Count -eq 0)
|
||
$bad = Rpc '' $null 'search_file' @{ id = $HostId; path = $SearchPath; pattern = '*.exe';
|
||
modified_after = '2026/01/01' }
|
||
Check 'search_file 非法 modified_after 返回 -32602' `
|
||
($bad.error -and [int]$bad.error.code -eq -32602)
|
||
}
|
||
} else {
|
||
Write-Host " 未指定 -SearchPath,跳过 search_file 测试(默认根目录扫得慢且结果不全)。" -ForegroundColor Yellow
|
||
}
|
||
}
|
||
|
||
# 批量入口:一台真实主机 + 一台不存在的主机,验证 results 汇总
|
||
$batch = Rpc '' $null 'list_processes' @{ ids = @($HostId, '999999999999999'); limit = 1 }
|
||
$bs = $batch.result.structuredContent
|
||
Check '批量 results 覆盖全部 id' (@($bs.results).Count -eq 2 -and [int]$bs.succeeded -eq 1 -and [int]$bs.failed -eq 1)
|
||
|
||
# get_keylog.offlineRecord(P10-A):客户端就绪包里带「离线记录」标志,老客户端只发 1 字节,
|
||
# 此时服务端按设计省略该字段——缺省与布尔都算通过,但要把是哪种情况说出来。
|
||
if (@($tools | Where-Object { $_.name -eq 'get_keylog' }).Count -gt 0) {
|
||
$kl = Rpc '' $null 'get_keylog' @{ id = $HostId; duration_ms = 1000; max_bytes = 4096 }
|
||
if ($kl.error) {
|
||
Check 'get_keylog 正常返回' $false ([string]$kl.error.message)
|
||
} else {
|
||
$ks = $kl.result.structuredContent
|
||
$hasFlag = $ks.PSObject.Properties.Name -contains 'offlineRecord'
|
||
Check 'get_keylog.offlineRecord 为布尔(老客户端可缺省)' `
|
||
((-not $hasFlag) -or $ks.offlineRecord.GetType() -eq [bool]) `
|
||
("offlineRecord=" + $ks.offlineRecord)
|
||
if (-not $hasFlag) {
|
||
Write-Host " 主机未上报离线记录标志(老客户端),offlineRecord 缺省属预期。" -ForegroundColor Yellow
|
||
}
|
||
}
|
||
} else {
|
||
Write-Host " get_keylog 未开启(McpKeylog),跳过键盘记录读取。" -ForegroundColor Yellow
|
||
}
|
||
}
|
||
|
||
# ===== 4b. 结构化失败(新客户端:TOKEN_*_ERROR → -32009/-32010) =====
|
||
# 老客户端没有这些回报包,对应工具会退化成「成功 + 空列表」或超时——
|
||
# 所以这三条只对「新客户端」成立;失败时先确认目标机客户端是否已升级。
|
||
if (-not $SkipHost -and $drive) {
|
||
Write-Host "`n[4b] 结构化失败"
|
||
$ghostDir = $drive.TrimEnd('\') + '\mcp_smoke_no_such_dir_xyz'
|
||
$lf = Rpc '' $null 'list_files' @{ id = $HostId; path = $ghostDir }
|
||
Check 'list_files 不存在路径返回 -32009' `
|
||
($lf.error -and [int]$lf.error.code -eq -32009) ([string]$lf.error.message)
|
||
|
||
$lr = Rpc '' $null 'list_registry' @{ id = $HostId; path = 'HKEY_LOCAL_MACHINE\SOFTWARE\MCPSmokeNoSuchKey_xyz' }
|
||
Check 'list_registry 不存在键返回 -32009' `
|
||
($lr.error -and [int]$lr.error.code -eq -32009) ([string]$lr.error.message)
|
||
|
||
if (@($tools | Where-Object { $_.name -eq 'download_file' }).Count -gt 0) {
|
||
$dlDir = Join-Path $env:TEMP 'mcp_smoke_dl'
|
||
$dl = Rpc '' $null 'download_file' @{ id = $HostId; remote_path = ($ghostDir + '\a.txt'); local_dir = $dlDir }
|
||
Check 'download_file 不存在路径返回 -32009' `
|
||
($dl.error -and [int]$dl.error.code -eq -32009) ([string]$dl.error.message)
|
||
Remove-Item -LiteralPath $dlDir -Recurse -Force -ErrorAction SilentlyContinue
|
||
} else {
|
||
Write-Host " download_file 未开启(McpFileTransfer),跳过下载负例。" -ForegroundColor Yellow
|
||
}
|
||
|
||
# copy_files_c2c:只测「不需要两台在线主机」的拒绝分支,避免冒烟改变远端文件。
|
||
# 同主机 → -32602(参数被拒);目标不在线 → -32002(主机找不到)。
|
||
if (@($tools | Where-Object { $_.name -eq 'copy_files_c2c' }).Count -gt 0) {
|
||
$c2cSame = Rpc '' $null 'copy_files_c2c' @{
|
||
src_id = $HostId; dst_id = $HostId
|
||
paths = @($ghostDir + '\a.txt'); dst_dir = (Join-Path $env:TEMP 'mcp_smoke_c2c')
|
||
}
|
||
Check 'copy_files_c2c 同主机返回 -32602' `
|
||
($c2cSame.error -and [int]$c2cSame.error.code -eq -32602) ([string]$c2cSame.error.message)
|
||
|
||
$c2cOff = Rpc '' $null 'copy_files_c2c' @{
|
||
src_id = $HostId; dst_id = '1'
|
||
paths = @($ghostDir + '\a.txt'); dst_dir = (Join-Path $env:TEMP 'mcp_smoke_c2c')
|
||
}
|
||
Check 'copy_files_c2c 目标离线返回 -32002' `
|
||
($c2cOff.error -and [int]$c2cOff.error.code -eq -32002) ([string]$c2cOff.error.message)
|
||
} else {
|
||
Write-Host " copy_files_c2c 未开启(McpFileTransfer/McpReadonly),跳过 C2C 负例。" -ForegroundColor Yellow
|
||
}
|
||
}
|
||
|
||
# ===== 4c. 文件写入(P10-B:delete_path / move_path / create_folder) =====
|
||
# 客户端对删除文件/删除目录/建目录/改名四条命令都是「做完就无条件回完成包」,ok 只证明命令送达;真正的结论在
|
||
# verified(true=复核看到状态变了,false=复核看到没变,null=复核没做成)。所以这一节只断言
|
||
# verified,不看 ok。顺带覆盖两处只有真机才暴露的坑:建目录要在路径末尾补反斜杠,
|
||
# 以及复核要读 LookupInListing 的 isDir 出参。
|
||
function Detail($r) {
|
||
if ($null -ne $r -and $null -ne $r.error) { return [string]$r.error.message }
|
||
$c = @($r.result.content)
|
||
if ($c.Count -gt 0) { return [string]$c[0].text }
|
||
return ''
|
||
}
|
||
function ErrCode($r) {
|
||
if ($null -eq $r -or $null -eq $r.error) { return 0 }
|
||
return [int]$r.error.code
|
||
}
|
||
function OkVerified($r) {
|
||
if ($null -eq $r -or $null -ne $r.error) { return $false }
|
||
$s = $r.result.structuredContent
|
||
return (($s.ok -eq $true) -and ($s.verified -eq $true))
|
||
}
|
||
function ListingNames([string]$path) {
|
||
$r = Rpc '' $null 'list_files' @{ id = $HostId; path = $path; limit = 100 }
|
||
if ($r.error) { return @() }
|
||
return @($r.result.structuredContent.files | ForEach-Object { [string]$_.name })
|
||
}
|
||
|
||
$writeTools = @($tools | Where-Object { $_.name -in @('delete_path', 'move_path', 'create_folder') })
|
||
if ($writeTools.Count -lt 3) {
|
||
Write-Host "`n[4c] 文件写入:工具未出现(McpFileWrite 关或 McpReadonly 开),跳过。" -ForegroundColor Yellow
|
||
} elseif ($SkipHost -or -not $HostId) {
|
||
Write-Host "`n[4c] 文件写入:没有在线主机,跳过。" -ForegroundColor Yellow
|
||
} elseif (-not $FileWriteDir) {
|
||
Write-Host "`n[4c] 文件写入:未给 -FileWriteDir,跳过(这一节会在目标机上建/删文件)。" -ForegroundColor Yellow
|
||
} else {
|
||
Write-Host "`n[4c] 文件写入 (根=$FileWriteDir)"
|
||
$sandbox = $FileWriteDir.TrimEnd('\') + '\mcp_smoke_' + (Get-Random -Minimum 10000 -Maximum 99999)
|
||
$uploadedName = ''
|
||
try {
|
||
# 一次建两层:既测「中间层一并创建」,也测路径末尾的反斜杠(少了它,客户端
|
||
# MakeSureDirectoryPathExists 会把最后一级当成文件名,只建中间层)。
|
||
$deep = $sandbox + '\sub\deep'
|
||
$mk = Rpc '' $null 'create_folder' @{ id = $HostId; path = $deep }
|
||
Check 'create_folder 建嵌套目录 verified=true' (OkVerified $mk) (Detail $mk)
|
||
$names = ListingNames $sandbox
|
||
Check 'create_folder 后父目录里能看到它' ($names -contains 'sub') ("names=" + ($names -join ','))
|
||
|
||
# upload_file 的返回值只有摘要,用列表复核它到底落没落盘
|
||
$localFile = Join-Path $env:TEMP ('mcp_smoke_upload_' + (Get-Random -Minimum 1000 -Maximum 9999) + '.txt')
|
||
Set-Content -LiteralPath $localFile -Value 'mcp smoke' -Encoding ascii
|
||
$uploadedName = [System.IO.Path]::GetFileName($localFile)
|
||
$uploadOk = $false
|
||
if (@($tools | Where-Object { $_.name -eq 'upload_file' }).Count -gt 0) {
|
||
$up = Rpc '' $null 'upload_file' @{ id = $HostId; local_path = $localFile; remote_dir = $sandbox }
|
||
$uploadOk = ($null -eq $up.error)
|
||
Check 'upload_file 正常返回' $uploadOk (Detail $up)
|
||
} else {
|
||
Write-Host " upload_file 未开启,跳过上传/改名/删文件三连。" -ForegroundColor Yellow
|
||
}
|
||
if ($uploadOk) {
|
||
Check 'upload_file 后沙箱里能看到该文件' ((ListingNames $sandbox) -contains $uploadedName)
|
||
|
||
$renamed = $uploadedName -replace '\.txt$', '_renamed.txt'
|
||
$mv = Rpc '' $null 'move_path' @{ id = $HostId; from = ($sandbox + '\' + $uploadedName); to = ($sandbox + '\' + $renamed) }
|
||
Check 'move_path 改名 verified=true' (OkVerified $mv) (Detail $mv)
|
||
$names = ListingNames $sandbox
|
||
Check 'move_path 后新名字出现、旧名字消失' `
|
||
(($names -contains $renamed) -and -not ($names -contains $uploadedName)) ("names=" + ($names -join ','))
|
||
$uploadedName = $renamed
|
||
|
||
$rm = Rpc '' $null 'delete_path' @{ id = $HostId; path = ($sandbox + '\' + $renamed) }
|
||
Check 'delete_path 删文件 verified=true' (OkVerified $rm) (Detail $rm)
|
||
Check 'delete_path 后文件不在列表里' (-not ((ListingNames $sandbox) -contains $renamed))
|
||
} elseif (@($tools | Where-Object { $_.name -eq 'upload_file' }).Count -gt 0) {
|
||
# 上传失败时改名/删文件没有对象,跳过而不是再报两条失败(upload_file 那条已经记了)
|
||
Write-Host " 上一步 upload_file 失败,跳过改名/删文件。" -ForegroundColor Yellow
|
||
}
|
||
Remove-Item -LiteralPath $localFile -Force -ErrorAction SilentlyContinue
|
||
|
||
# 非 ASCII 路径:服务端按 UTF-8 校验、只转一次 GBK,客户端再用 A 接口落盘
|
||
$cnDir = $sandbox + '\中文目录'
|
||
$cn = Rpc '' $null 'create_folder' @{ id = $HostId; path = $cnDir }
|
||
Check 'create_folder 中文路径 verified=true' (OkVerified $cn) (Detail $cn)
|
||
$cnRm = Rpc '' $null 'delete_path' @{ id = $HostId; path = $cnDir; recursive = $true }
|
||
Check 'delete_path 中文路径 verified=true' (OkVerified $cnRm) (Detail $cnRm)
|
||
|
||
# recursive=false 落在目录上:客户端 DeleteFile 失败且不回错误包 → 复核必须说 false
|
||
$mk2 = Rpc '' $null 'create_folder' @{ id = $HostId; path = ($sandbox + '\asdir') }
|
||
if (OkVerified $mk2) {
|
||
$bad = Rpc '' $null 'delete_path' @{ id = $HostId; path = ($sandbox + '\asdir') }
|
||
Check 'delete_path 对目录用 recursive=false 时 verified=false' `
|
||
(($null -eq $bad.error) -and ($bad.result.structuredContent.ok -eq $true) -and
|
||
($bad.result.structuredContent.verified -eq $false)) (Detail $bad)
|
||
}
|
||
|
||
# 越界与参数拒绝:全部发生在服务端,不该触达目标机
|
||
$fwDrive = if ($drive) { $drive } else { $FileWriteDir.Substring(0, 2) }
|
||
$fwRoot = $fwDrive.TrimEnd('\')
|
||
$longPath = $sandbox + '\' + ('a' * 220)
|
||
$cases = @(
|
||
@{ name = '盘符根'; tool = 'delete_path'; args = @{ id = $HostId; path = $fwRoot }; code = -32602 }
|
||
@{ name = '系统目录'; tool = 'delete_path'; args = @{ id = $HostId; path = ($fwRoot + '\Windows\Temp') }; code = -32602 }
|
||
@{ name = '含 %VAR%'; tool = 'delete_path'; args = @{ id = $HostId; path = '%TEMP%\mcp_smoke_x' }; code = -32602 }
|
||
@{ name = '相对路径'; tool = 'create_folder'; args = @{ id = $HostId; path = 'mcp_smoke_x' }; code = -32602 }
|
||
@{ name = '超长路径'; tool = 'create_folder'; args = @{ id = $HostId; path = $longPath }; code = -32602 }
|
||
@{ name = 'from 与 to 相同'; tool = 'move_path'; args = @{ id = $HostId; from = $deep; to = $deep.ToUpperInvariant() }; code = -32602 }
|
||
@{ name = '主机不在线'; tool = 'create_folder'; args = @{ id = '1'; path = ($sandbox + '\x') }; code = -32002 }
|
||
)
|
||
foreach ($c in $cases) {
|
||
$r = Rpc '' $null $c.tool $c.args
|
||
Check ('参数被拒:' + $c.name + ' 返回 ' + $c.code) ((ErrCode $r) -eq $c.code) (Detail $r)
|
||
}
|
||
|
||
# 收尾:整棵删掉沙箱,并用父目录列表复核
|
||
$rmAll = Rpc '' $null 'delete_path' @{ id = $HostId; path = $sandbox; recursive = $true }
|
||
Check 'delete_path 递归删沙箱 verified=true' (OkVerified $rmAll) (Detail $rmAll)
|
||
$fwParent = $FileWriteDir.TrimEnd('\')
|
||
Check '沙箱已不在父目录里' (-not ((ListingNames $fwParent) -contains [System.IO.Path]::GetFileName($sandbox)))
|
||
} finally {
|
||
# 中途失败时也要尽量不把沙箱留在目标机上(尽力而为,不再断言)
|
||
$null = Rpc '' $null 'delete_path' @{ id = $HostId; path = $sandbox; recursive = $true }
|
||
}
|
||
}
|
||
|
||
# ===== 5. 策略拒绝(-32006) =====
|
||
# 只在某个开关确实关闭时才有意义,所以先读 get_server_status 的 switches 再挑一个关着的功能。
|
||
# 全部开启时跳过(不算失败)——这条不是每次都能测,但测到时能证明拒绝路径与审计都还在。
|
||
Write-Host "`n[5] 策略拒绝"
|
||
$gateMap = @(
|
||
@{ swName = 'keylog'; tool = 'get_keylog'; args = @{} }
|
||
@{ swName = 'chat'; tool = 'chat_open'; args = @{} }
|
||
@{ swName = 'terminal'; tool = 'terminal_open'; args = @{} }
|
||
@{ swName = 'remote_control'; tool = 'get_screenshot'; args = @{} }
|
||
)
|
||
$offGate = $null
|
||
foreach ($g in $gateMap) {
|
||
if ($null -ne $st.switches -and $st.switches.PSObject.Properties.Name -contains $g.swName -and
|
||
$st.switches.($g.swName) -eq $false) { $offGate = $g; break }
|
||
}
|
||
if ($offGate) {
|
||
$args5 = @{}
|
||
if ($HostId) { $args5['id'] = $HostId }
|
||
foreach ($k in $offGate.args.Keys) { $args5[$k] = $offGate.args[$k] }
|
||
$refused = Rpc '' $null $offGate.tool $args5
|
||
Check ("关闭 " + $offGate.swName + " 后 " + $offGate.tool + " 返回 -32006") ([int]$refused.error.code -eq -32006) ([string]$refused.error.message)
|
||
if ($AuditLog) {
|
||
$tail = Get-Content -LiteralPath $AuditLog -Tail 20 -ErrorAction SilentlyContinue
|
||
Check '拒绝记录进审计日志(CALL_DENIED)' (@($tail | Where-Object { $_ -match 'CALL_DENIED' }).Count -gt 0)
|
||
}
|
||
} else {
|
||
Write-Host " 所有功能开关都开着,跳过 -32006 检查(关掉任一开关再跑一次可覆盖)。" -ForegroundColor Yellow
|
||
}
|
||
|
||
# ===== 汇总 =====
|
||
Write-Host ("`n通过 " + $script:pass + " 项,失败 " + $script:fail + " 项。") -ForegroundColor $(if ($script:fail -eq 0) { 'Green' } else { 'Red' })
|
||
if ($script:fail -gt 0) {
|
||
$script:failures | ForEach-Object { Write-Host (" - " + $_) -ForegroundColor Red }
|
||
exit 1
|
||
}
|
||
exit 0
|