P11 closes the plan's last batch, entirely on the server side: no client change is required for any of it. Long-running tools now expose a cancellation flag that every wait loop checks in 500 ms slices. A cancelled tool returns through the cleanup branch it already had (late first packets still get absorbed, sub connections still get closed, pending entries still get deleted), so there is no second cleanup path to keep in sync, and the host is released within a second. Three sources set the flag: notifications/cancelled (matched on the exact JSON-RPC id, with a fallback to the display form so a request_id copied out of the session list round-trips), mcp_cancel_session (by request_id, host id or session id), and a failed SSE write when the client has gone away. The dispatcher rewrites a cancel-induced failure to -32800 so callers do not mistake it for a host fault. tools/call requests carrying _meta.progressToken are answered as text/event-stream on the same POST: the tool runs on its own thread and both the notifications/progress events and the final JSON-RPC response go out through one chunked provider. Requests without a token are unchanged. download_file reports files done vs. expected, upload_file reports bytes sent vs. total. Two new local-only tools, mcp_list_sessions and mcp_cancel_session, list and cancel in-flight sessions (calls, pending one-shots, terminal, remote control, file transfer, chat). They are deliberately not gated by the feature switches or readonly mode, since that is the only way out of a stuck request. The -32003 busy message now names the occupier: "Device busy: ... (tool=download_file, elapsed=12s)". power_action gains wait/wait_ms to verify the result against the main connection's presence (went_offline, came_back, elapsed_ms); not seeing the transition is reported as ok, not as a failure. kill_process, operate_window and the four host_control_* tools accept dry_run, which validates the target against one fresh snapshot and returns what would be affected without sending anything. Validation rejections now use -32012; -32008 stays as documented historical alias. One implementation note worth recording: the per-thread call context uses FLS, not thread_local. Any static thread_local in this server crashes the process about a second after start, because some threads come from shellcode/MemoryModule images that never ran PE TLS initialisation. Verified against a real Debug server and a real Windows client over MCP: the smoke test now passes 104 checks with 0 failures, including cancellation releasing the host in under a second, the cancelled request returning -32800, notifications/cancelled returning 202, 63 progress events with exact byte counts for a 64 MB upload, and a cleanly terminated SSE stream. Not exercised in this pass: power_action's wait=true path (it would take the test host down) and the -32006 readonly/switch-off section (every switch was on during the run). Co-Authored-By: deepseek-flash
909 lines
53 KiB
PowerShell
909 lines
53 KiB
PowerShell
<#
|
||
服务端 MCP 冒烟测试。
|
||
|
||
默认只调用「不会改变任何状态」的工具(列表/详情类),断言结构化字段齐全、
|
||
分页字段正确、鉴权与请求体上限生效。可在发布前对着任一台在线主机跑一遍,
|
||
确认 MCP 链路与改动前相比没有回归。
|
||
|
||
唯一会写目标机的部分是 [4c] 文件写入,且必须显式给 -FileWriteDir 才会跑:
|
||
它在那个目录下建一个 mcp_smoke_xxxx 沙箱,走完 create/upload/rename/delete
|
||
后整棵删掉,不碰沙箱以外的任何东西。
|
||
|
||
[6] 是 P11 的验收:-32012(校验拒绝,历史别名 -32008 不再出现)、dry_run
|
||
只校验不下发、mcp_list_sessions / mcp_cancel_session 与 notifications/cancelled
|
||
的取消路径(取消后 1s 内释放主机、被取消的请求回 -32800)、以及 SSE 进度通知。
|
||
其中「真实取消」会起一条能在目标机跑够 ~25s 的无副作用命令(Windows 上是
|
||
ping -n 25 127.0.0.1,没有 exec_command 时退回 get_keylog 20s),1s 后取消;
|
||
命令本身会在目标机上自己跑完,不影响结果。SSE 进度一节同样要求 -FileWriteDir,
|
||
会往那个目录上传一个 4 MB 临时文件并在结束时删掉。
|
||
|
||
用法:
|
||
$env:YAMA_MCP_TOKEN = '<token>' # 与 service 的 McpToken 一致
|
||
powershell -ExecutionPolicy Bypass -File tools\mcp_smoke.ps1
|
||
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'
|
||
# Start-RpcAsync 用 HttpClient 发并发请求;Windows PowerShell 5.1 默认没加载这个程序集,
|
||
# 而类型字面量在执行该语句时就要能解析,所以放在脚本开头加载。
|
||
try { Add-Type -AssemblyName System.Net.Http -ErrorAction Stop } catch { }
|
||
$script:pass = 0
|
||
$script:fail = 0
|
||
$script:failures = @()
|
||
|
||
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
|
||
}
|
||
|
||
# 工具是否出现在 tools/list 里:不可见多半是开关关着(正常配置),相关断言跳过而不是报失败。
|
||
function HasTool([string]$name) {
|
||
return (@($tools | Where-Object { $_.name -eq $name }).Count -gt 0)
|
||
}
|
||
|
||
# 并发发起一个 tools/call:取消测试要在请求还在飞的时候去查表、去取消,
|
||
# 单线程的 Invoke-WebRequest 做不到。返回句柄交给 Receive-RpcAsync 收尾。
|
||
#
|
||
# 用 HttpClient.SendAsync(真异步,立即返回 Task)。别用 HttpWebRequest + BeginGetResponse:
|
||
# 实测 EndGetResponse 之前 BeginGetResponse 自己就会阻塞到响应头到达(服务端在工具跑完
|
||
# 才写响应头),于是「异步」调用其实是同步的,被测的长调用根本没在飞。
|
||
$script:HttpClient = $null
|
||
function Get-SmokeHttpClient() {
|
||
if (-not $script:HttpClient) {
|
||
$c = New-Object System.Net.Http.HttpClient
|
||
$c.Timeout = [TimeSpan]::FromSeconds(180)
|
||
$script:HttpClient = $c
|
||
}
|
||
return $script:HttpClient
|
||
}
|
||
function Start-RpcAsync([string]$json) {
|
||
$req = New-Object System.Net.Http.HttpRequestMessage([System.Net.Http.HttpMethod]::Post, $Base)
|
||
$req.Content = New-Object System.Net.Http.StringContent($json, [System.Text.Encoding]::UTF8, 'application/json')
|
||
$req.Headers.Add('Authorization', 'Bearer ' + $Token)
|
||
$req.Headers.Add('Accept', 'application/json, text/event-stream')
|
||
return @{ Request = $req; Task = (Get-SmokeHttpClient).SendAsync($req) }
|
||
}
|
||
|
||
function Receive-RpcAsync($handle) {
|
||
$resp = $null
|
||
try {
|
||
$resp = $handle.Task.GetAwaiter().GetResult() # 非 2xx 不抛异常(没调 EnsureSuccessStatusCode)
|
||
return $resp.Content.ReadAsStringAsync().GetAwaiter().GetResult()
|
||
} catch {
|
||
return ''
|
||
} finally {
|
||
if ($resp) { $resp.Dispose() }
|
||
$handle.Request.Dispose()
|
||
}
|
||
}
|
||
|
||
# 带 Accept: text/event-stream 的请求:带 _meta.progressToken 的 tools/call 会以
|
||
# chunked SSE 回应,Invoke-WebRequest 读完整条流后一次性返回正文。
|
||
function Send-Sse([string]$json, [string]$auth) {
|
||
$bytes = [System.Text.Encoding]::UTF8.GetBytes($json)
|
||
$headers = @{ Authorization = 'Bearer ' + $auth; Accept = 'application/json, text/event-stream' }
|
||
$resp = Invoke-WebRequest -Uri $Base -Method Post -Body $bytes -ContentType 'application/json' `
|
||
-Headers $headers -TimeoutSec 300 -UseBasicParsing
|
||
return @{ Status = [int]$resp.StatusCode; Body = [string]$resp.Content
|
||
ContentType = [string]$resp.Headers['Content-Type'] }
|
||
}
|
||
|
||
# 结果外露(docs/Mcp_Design.md §14):content 末尾必须有一个可解析的 JSON 文本块,
|
||
# 内容与 structuredContent 对应。只读 content 的客户端(WorkBuddy)靠它拿到 id。
|
||
function HasJsonText($rpc) {
|
||
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)
|
||
|
||
# P11:在飞会话的观测 / 取消入口必须一直可见——它是卡住请求的唯一出路,
|
||
# 因此不受功能开关与只读模式限制(只读时也在列表里)。
|
||
foreach ($n in @('mcp_list_sessions', 'mcp_cancel_session')) {
|
||
Check ('tools/list 含 ' + $n) (@($tools | Where-Object { $_.name -eq $n }).Count -eq 1)
|
||
}
|
||
|
||
# ===== 2b. 协议层错误码 =====
|
||
Write-Host "`n[2b] 协议层错误码"
|
||
$um = Rpc 'bogus/method' @{} $null $null
|
||
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)
|
||
|
||
# 6b 的 dry_run 断言要拿一个真能操作的进程:pid 0 是内核伪进程([System Process]),
|
||
# kill_process 按约定拒绝非零以外的 PID,host_control_process 也认不出它。
|
||
$sample = Rpc '' $null 'list_processes' @{ id = $HostId; limit = 50 }
|
||
if ($null -eq $sample.error) {
|
||
$realProc = @($sample.result.structuredContent.processes | Where-Object { [int]$_.pid -gt 4 })[0]
|
||
if ($realProc) { $ppid = [int]$realProc.pid }
|
||
}
|
||
}
|
||
|
||
$wins = Rpc '' $null 'list_windows' @{ id = $HostId; limit = 3 }
|
||
Check 'list_windows 正常返回' ($wins.error -eq $null -and (HasPaging $wins.result.structuredContent))
|
||
|
||
$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 }
|
||
}
|
||
}
|
||
|
||
# ===== 4d. 键鼠锁定(P10-C:remote_block_input)参数校验 =====
|
||
# 这里刻意不真的锁定对端:冒烟测试常常跑在操作者自己的电脑上(客户端与服务端同机),
|
||
# 真锁会把正在用电脑的人挡在外面。锁定 / 到期自动解除 / remote_close 强制解除只能人工旁观
|
||
# 目标机来验证(见 docs/Mcp_Next_Plan.md §3.1),本节只覆盖服务端就能判定的拒绝分支。
|
||
$blockTool = @($tools | Where-Object { $_.name -eq 'remote_block_input' }).Count -gt 0
|
||
if (-not $blockTool) {
|
||
Write-Host "`n[4d] 键鼠锁定:remote_block_input 未出现(McpRemoteControl=0 或 McpReadonly=1),跳过。" -ForegroundColor Yellow
|
||
} elseif ($SkipHost -or -not $HostId) {
|
||
Write-Host "`n[4d] 键鼠锁定:没有在线主机,跳过。" -ForegroundColor Yellow
|
||
} else {
|
||
Write-Host "`n[4d] 键鼠锁定(参数校验)"
|
||
$blockCases = @(
|
||
@{ name = '缺 block'; args = @{ id = $HostId; session_id = 'mcp_smoke_no_such' }; code = -32602 }
|
||
@{ name = 'block 非布尔'; args = @{ id = $HostId; session_id = 'mcp_smoke_no_such'; block = 'maybe' }; code = -32602 }
|
||
@{ name = 'max_block_ms 越界'; args = @{ id = $HostId; session_id = 'mcp_smoke_no_such'; block = $true; max_block_ms = 500 }; code = -32602 }
|
||
@{ name = '会话不存在'; args = @{ id = $HostId; session_id = 'mcp_smoke_no_such'; block = $true }; code = -32002 }
|
||
@{ name = '主机不在线'; args = @{ id = '1'; session_id = 'mcp_smoke_no_such'; block = $true }; code = -32002 }
|
||
)
|
||
foreach ($c in $blockCases) {
|
||
$r = Rpc '' $null 'remote_block_input' $c.args
|
||
Check ('键鼠锁定:' + $c.name + ' 返回 ' + $c.code) ((ErrCode $r) -eq $c.code) (Detail $r)
|
||
}
|
||
}
|
||
|
||
# ===== 5. 策略拒绝(-32006) =====
|
||
# 只在某个开关确实关闭时才有意义,所以先读 get_server_status 的 switches 再挑一个关着的功能。
|
||
# 全部开启时跳过(不算失败)——这条不是每次都能测,但测到时能证明拒绝路径与审计都还在。
|
||
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
|
||
}
|
||
|
||
# ===== 6. P11:校验码 / dry_run / 在飞会话观测与取消 / SSE 进度 =====
|
||
# 每条都对应 P11 的一条验收:
|
||
# 6a -32012(校验拒绝)取代历史别名 -32008;
|
||
# 6b dry_run 统一「只校验目标、不下发动作」;
|
||
# 6c mcp_list_sessions 快照 + mcp_cancel_session 与 notifications/cancelled 的取消,
|
||
# 以及「取消后主机 1s 内释放」(用 get_server_status.sessions.pending 复核);
|
||
# 6d 带 _meta.progressToken 的 tools/call 走 text/event-stream,长任务的进度通知计数 > 0。
|
||
Write-Host "`n[6] P11 校验码、dry_run 与中断"
|
||
|
||
# 取消测试要同时挂着长请求、还要再发短请求,需要比 .NET 默认(每主机 2 条)更多的连接。
|
||
[System.Net.ServicePointManager]::DefaultConnectionLimit = 16
|
||
$p11Host = (-not $SkipHost) -and [bool]$HostId
|
||
$isWindowsHost = ($null -eq $caps) -or (@('DLL', 'EXE', 'MEXE', 'SC', 'MDLL') -contains [string]$caps.platform)
|
||
|
||
# 6a. -32012:命令里的 shell 元字符属于「参数被校验拒绝」,不是白名单拒绝(-32007)
|
||
if ($p11Host -and (HasTool 'exec_command')) {
|
||
$badCmd = Rpc '' $null 'exec_command' @{ id = $HostId; command = 'dir & whoami' }
|
||
Check 'exec_command 含 shell 元字符返回 -32012' ((ErrCode $badCmd) -eq -32012) (Detail $badCmd)
|
||
Check '校验拒绝不再使用历史别名 -32008' ((ErrCode $badCmd) -ne -32008) (Detail $badCmd)
|
||
} else {
|
||
Write-Host " exec_command 不可用,跳过 -32012 检查。" -ForegroundColor Yellow
|
||
}
|
||
|
||
# 6b. dry_run:只取一次快照校验目标存在,结构化结果带 dry_run=true,
|
||
# 且不能出现「动作后才有」的字段(remaining / changed)——那意味着动作真的下发了。
|
||
if ($p11Host -and (HasTool 'kill_process')) {
|
||
$drBad = Rpc '' $null 'kill_process' @{ id = $HostId; pids = @(4); dry_run = 'yes' }
|
||
Check 'kill_process dry_run 非布尔返回 -32602' ((ErrCode $drBad) -eq -32602) (Detail $drBad)
|
||
if ($null -ne $ppid) {
|
||
$dr = Rpc '' $null 'kill_process' @{ id = $HostId; pids = @($ppid); dry_run = $true }
|
||
$drs = $dr.result.structuredContent
|
||
Check 'kill_process dry_run=true 只校验(targets/missing,无 remaining)' `
|
||
(($null -eq $dr.error) -and ($drs.dry_run -eq $true) -and
|
||
(@($drs.targets).Count -ge 1) -and
|
||
($drs.PSObject.Properties.Name -contains 'missing') -and
|
||
-not ($drs.PSObject.Properties.Name -contains 'remaining')) (Detail $dr)
|
||
}
|
||
} else {
|
||
Write-Host " kill_process 不可用,跳过该 dry_run 检查。" -ForegroundColor Yellow
|
||
}
|
||
|
||
$win0 = $null
|
||
if ($null -ne $wins -and $null -ne $wins.result) { $win0 = @($wins.result.structuredContent.windows)[0] }
|
||
if ($p11Host -and (HasTool 'operate_window') -and $win0 -and $null -ne $win0.hwnd) {
|
||
$owBad = Rpc '' $null 'operate_window' @{ id = $HostId; hwnd = $win0.hwnd; action = 'restore'; dry_run = 'yes' }
|
||
Check 'operate_window dry_run 非布尔返回 -32602' ((ErrCode $owBad) -eq -32602) (Detail $owBad)
|
||
$ow = Rpc '' $null 'operate_window' @{ id = $HostId; hwnd = $win0.hwnd; action = 'restore'; dry_run = $true }
|
||
$ows = $ow.result.structuredContent
|
||
Check 'operate_window dry_run=true 只校验(window 有值、无 changed)' `
|
||
(($null -eq $ow.error) -and ($ows.dry_run -eq $true) -and ($null -ne $ows.window) -and
|
||
-not ($ows.PSObject.Properties.Name -contains 'changed')) (Detail $ow)
|
||
} else {
|
||
Write-Host " operate_window 不可用(或没有可见窗口),跳过该 dry_run 检查。" -ForegroundColor Yellow
|
||
}
|
||
|
||
if ($p11Host -and (HasTool 'host_control_process') -and $null -ne $ppid) {
|
||
$hc = Rpc '' $null 'host_control_process' @{ id = $HostId; action = 'freeze'; pid = $ppid; dry_run = $true }
|
||
$hcs = $hc.result.structuredContent
|
||
Check 'host_control_process dry_run=true 只校验(state/detail,无 changed)' `
|
||
(($null -eq $hc.error) -and ($hcs.dry_run -eq $true) -and ([string]$hcs.target -ne '') -and
|
||
-not ($hcs.PSObject.Properties.Name -contains 'changed')) (Detail $hc)
|
||
} else {
|
||
Write-Host " host_control_process 不可用,跳过该 dry_run 检查。" -ForegroundColor Yellow
|
||
}
|
||
|
||
# 6c. 观测与取消。参数拒绝 / 空命中先测(不依赖主机),真实取消再单独跑。
|
||
$ls0 = Rpc '' $null 'mcp_list_sessions' @{}
|
||
Check 'mcp_list_sessions 返回 sessions/count' `
|
||
(($null -eq $ls0.error) -and ($null -ne $ls0.result.structuredContent.sessions) -and
|
||
([int]$ls0.result.structuredContent.count -eq @($ls0.result.structuredContent.sessions).Count)) (Detail $ls0)
|
||
$lsBad = Rpc '' $null 'mcp_list_sessions' @{ kind = 'zzz-no-such-kind' }
|
||
Check 'mcp_list_sessions 非法 kind 返回 -32602' ((ErrCode $lsBad) -eq -32602) (Detail $lsBad)
|
||
$cnBad = Rpc '' $null 'mcp_cancel_session' @{}
|
||
Check 'mcp_cancel_session 缺参数返回 -32602' ((ErrCode $cnBad) -eq -32602) (Detail $cnBad)
|
||
$cnNone = Rpc '' $null 'mcp_cancel_session' @{ request_id = 'zzz-no-such-request' }
|
||
Check 'mcp_cancel_session 未命中返回 cancelled=0' `
|
||
(($null -eq $cnNone.error) -and ([int]$cnNone.result.structuredContent.cancelled -eq 0)) (Detail $cnNone)
|
||
|
||
# 真实取消:起一个确定会跑够 20s+ 的无副作用调用,等它进了在飞表再取消。
|
||
# Windows 主机用 exec_command 跑 ping(白名单内、不需要管理员),其他平台退回 get_keylog。
|
||
$longCall = $null
|
||
if ($p11Host) {
|
||
if ((HasTool 'exec_command') -and $isWindowsHost) {
|
||
$longCall = @{ tool = 'exec_command'
|
||
args = @{ id = $HostId; command = 'ping -n 25 127.0.0.1'; timeout_ms = 60000 } }
|
||
} elseif (HasTool 'get_keylog') {
|
||
$longCall = @{ tool = 'get_keylog'; args = @{ id = $HostId; duration_ms = 20000; max_bytes = 4096 } }
|
||
}
|
||
}
|
||
|
||
function Wait-Session([string]$rid, [int]$tries = 40) {
|
||
# 轮询 mcp_list_sessions 直到出现这次调用(或超时),返回快照项。
|
||
for ($i = 0; $i -lt $tries; $i++) {
|
||
Start-Sleep -Milliseconds 100
|
||
$snap = Rpc '' $null 'mcp_list_sessions' @{ kind = 'call' }
|
||
if ($null -eq $snap.error) {
|
||
$hit = @($snap.result.structuredContent.sessions | Where-Object { [string]$_.request_id -eq $rid })[0]
|
||
if ($hit) { return $hit }
|
||
}
|
||
}
|
||
return $null
|
||
}
|
||
|
||
if (-not $longCall) {
|
||
Write-Host " 没有能跑长的工具(exec_command/get_keylog),跳过取消与 SSE 进度检查。" -ForegroundColor Yellow
|
||
} else {
|
||
$rid = 'p11-cancel-' + (Get-Random -Minimum 1000 -Maximum 9999)
|
||
$payload = @{ jsonrpc = '2.0'; id = $rid; method = 'tools/call'
|
||
params = @{ name = $longCall.tool; arguments = $longCall.args } } |
|
||
ConvertTo-Json -Depth 8 -Compress
|
||
$h = Start-RpcAsync $payload
|
||
$seen = Wait-Session $rid
|
||
Check '在飞调用出现在 mcp_list_sessions 里' ($null -ne $seen) ("request_id=" + $rid)
|
||
if (-not $seen) {
|
||
$null = Receive-RpcAsync $h
|
||
Check '取消测试的前置条件(长调用进入在飞表)' $false '长任务没有进入在飞表,取消路径未验证'
|
||
} else {
|
||
Check '会话快照字段齐全(host_id/kind/tool/elapsed_ms)' `
|
||
((([string]$seen.host_id) -eq $HostId) -and ([string]$seen.kind -eq 'call') -and
|
||
([string]$seen.tool -eq $longCall.tool) -and ($null -ne $seen.elapsed_ms)) `
|
||
("host_id=" + $seen.host_id + " kind=" + $seen.kind + " tool=" + $seen.tool)
|
||
|
||
# -32003 的正文要点名占用者(P11 之前只有一句通用话)。它来自「同一主机的一次性
|
||
# 待响应请求单飞行」:exec_command 走的是终端子连接,与 list_processes 这类请求
|
||
# 并不互斥,所以占用者要用「并发打同一台主机」来制造,而不是拿长调用去当占用者。
|
||
if (HasTool 'list_processes') {
|
||
$raceHandles = @()
|
||
for ($i = 0; $i -lt 8; $i++) {
|
||
$raceHandles += Start-RpcAsync (@{ jsonrpc = '2.0'; id = ('race-' + $i); method = 'tools/call'
|
||
params = @{ name = 'list_processes'
|
||
arguments = @{ id = $HostId; limit = 5 } } } |
|
||
ConvertTo-Json -Depth 8 -Compress)
|
||
}
|
||
$raceErrs = @()
|
||
foreach ($rh in $raceHandles) {
|
||
$rb = [string](Receive-RpcAsync $rh)
|
||
$rj = $null
|
||
try { $rj = $rb | ConvertFrom-Json } catch { continue }
|
||
if ($null -ne $rj.error) { $raceErrs += $rj }
|
||
}
|
||
$busy = @($raceErrs | Where-Object { [int]$_.error.code -eq -32003 })[0]
|
||
Check '并发请求同一主机时被拒的返回 -32003 且点名占用者' `
|
||
(($null -ne $busy) -and ([string]$busy.error.message).Contains('tool=')) `
|
||
(($raceErrs | ForEach-Object { [string]$_.error.message }) -join ' | ')
|
||
}
|
||
|
||
$cn = Rpc '' $null 'mcp_cancel_session' @{ request_id = $rid }
|
||
$cns = $cn.result.structuredContent
|
||
Check 'mcp_cancel_session 按 request_id 取消' `
|
||
(($null -eq $cn.error) -and ([int]$cns.cancelled -eq 1)) (Detail $cn)
|
||
Check '取消后主机 1s 内释放' `
|
||
(($cns.released -eq $true) -and ([int]$cns.waited_ms -le 1000)) `
|
||
("released=" + $cns.released + " waited_ms=" + $cns.waited_ms)
|
||
|
||
$body = [string](Receive-RpcAsync $h)
|
||
$jr = $null
|
||
try { $jr = $body | ConvertFrom-Json } catch { }
|
||
if ($body.Length -gt 160) { $body = $body.Substring(0, 160) }
|
||
Check '被取消的请求回 -32800' (($null -ne $jr) -and ($null -ne $jr.error) -and
|
||
([int]$jr.error.code -eq -32800)) $body
|
||
|
||
# 交叉核对:get_server_status 的 sessions.pending 应回到 0,主机能再次正常调用
|
||
$st2 = (Rpc '' $null 'get_server_status' @{}).result.structuredContent.status
|
||
Check '取消后 get_server_status 无挂起(sessions.pending=0)' `
|
||
([int]$st2.sessions.pending -eq 0) ("pending=" + $st2.sessions.pending)
|
||
if (HasTool 'list_processes') {
|
||
$again = Rpc '' $null 'list_processes' @{ id = $HostId; limit = 1 }
|
||
Check '取消后主机可再次正常调用' ($null -eq $again.error) (Detail $again)
|
||
}
|
||
|
||
# notifications/cancelled:与 mcp_cancel_session 等价的通知路径(202 无响应体)
|
||
$rid2 = 'p11-notify-' + (Get-Random -Minimum 1000 -Maximum 9999)
|
||
$payload2 = @{ jsonrpc = '2.0'; id = $rid2; method = 'tools/call'
|
||
params = @{ name = $longCall.tool; arguments = $longCall.args } } |
|
||
ConvertTo-Json -Depth 8 -Compress
|
||
$h2 = Start-RpcAsync $payload2
|
||
$seen2 = Wait-Session $rid2
|
||
if (-not $seen2) {
|
||
$null = Receive-RpcAsync $h2
|
||
Check '第二个长调用进入在飞表(通知取消前置)' $false '长任务没有进入在飞表'
|
||
} else {
|
||
$note = '{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":"' +
|
||
$rid2 + '","reason":"smoke"}}'
|
||
$nr = Send-Raw $note $Token
|
||
Check 'notifications/cancelled 返回 202' ($nr.Status -eq 202) ("status=" + $nr.Status)
|
||
$body2 = [string](Receive-RpcAsync $h2)
|
||
$jr2 = $null
|
||
try { $jr2 = $body2 | ConvertFrom-Json } catch { }
|
||
if ($body2.Length -gt 160) { $body2 = $body2.Substring(0, 160) }
|
||
Check '通知取消后请求回 -32800' (($null -ne $jr2) -and ($null -ne $jr2.error) -and
|
||
([int]$jr2.error.code -eq -32800)) $body2
|
||
# 通知路径没有「等释放」的返回值,只能自己轮询(≤2s)
|
||
$freed = $false
|
||
for ($i = 0; $i -lt 20 -and -not $freed; $i++) {
|
||
$snap3 = Rpc '' $null 'mcp_list_sessions' @{ kind = 'call' }
|
||
if (@($snap3.result.structuredContent.sessions |
|
||
Where-Object { [string]$_.request_id -eq $rid2 }).Count -eq 0) { $freed = $true }
|
||
else { Start-Sleep -Milliseconds 100 }
|
||
}
|
||
Check '通知取消后 2s 内从在飞表消失' $freed
|
||
}
|
||
}
|
||
}
|
||
|
||
# 6d. SSE:带 _meta.progressToken 的 tools/call 以 text/event-stream 回应。
|
||
# 先用一个立即返回的工具验证传输与收尾(进度天然为 0 条),再用一次真实上传验证进度。
|
||
$probe = '{"jsonrpc":"2.0","id":7001,"method":"tools/call","params":{"name":"get_server_status","arguments":{},"_meta":{"progressToken":"smoke-probe"}}}'
|
||
$sse = Send-Sse $probe $Token
|
||
Check 'SSE:Content-Type 是 text/event-stream' ($sse.ContentType -like 'text/event-stream*') $sse.ContentType
|
||
$sseProbeLast = $null
|
||
foreach ($line in ($sse.Body -split "`n")) {
|
||
if ($line.StartsWith('data: ')) { try { $sseProbeLast = ($line.Substring(6) | ConvertFrom-Json) } catch { } }
|
||
}
|
||
Check 'SSE:流末尾是完整 JSON-RPC 响应' `
|
||
(($null -ne $sseProbeLast) -and ([string]$sseProbeLast.id -eq '7001') -and
|
||
($null -ne $sseProbeLast.result) -and ($null -eq $sseProbeLast.error))
|
||
|
||
if (-not $p11Host -or -not $FileWriteDir -or -not (HasTool 'upload_file') -or -not (HasTool 'delete_path')) {
|
||
Write-Host " 未给 -FileWriteDir 或文件写入工具不可见,跳过 SSE 进度检查(进度 > 0 需一次真实长任务)。" -ForegroundColor Yellow
|
||
} else {
|
||
# 4 MB 分 64 KB 一片:即使局域网很快也能产生多个进度回调(首个回调不受 1s 节流限制)。
|
||
$progLocal = Join-Path $env:TEMP ('mcp_smoke_prog_' + (Get-Random -Minimum 1000 -Maximum 9999) + '.bin')
|
||
$fs = [System.IO.File]::Create($progLocal)
|
||
$chunk = New-Object byte[] (64 * 1024)
|
||
for ($i = 0; $i -lt 64; $i++) { $fs.Write($chunk, 0, $chunk.Length) }
|
||
$fs.Close()
|
||
$progName = [System.IO.Path]::GetFileName($progLocal)
|
||
# 注意:PowerShell 变量名大小写不敏感,别用 $tok —— 会覆盖掉 bearer token $Token。
|
||
$progToken = 'smoke-progress-' + (Get-Random -Minimum 1000 -Maximum 9999)
|
||
$sseBody = @{ jsonrpc = '2.0'; id = 7002; method = 'tools/call'
|
||
params = @{ name = 'upload_file'
|
||
arguments = @{ id = $HostId; local_path = $progLocal; remote_dir = $FileWriteDir }
|
||
_meta = @{ progressToken = $progToken } } } |
|
||
ConvertTo-Json -Depth 10 -Compress
|
||
try {
|
||
$up = Send-Sse $sseBody $Token
|
||
$progCount = ([regex]::Matches($up.Body, [regex]::Escape('notifications/progress'))).Count
|
||
Check 'SSE:长任务收到 notifications/progress(计数 > 0)' ($progCount -gt 0) ("count=" + $progCount)
|
||
Check 'SSE:进度通知回显 progressToken 且带 progress' `
|
||
(($up.Body -match ('"progressToken":"' + [regex]::Escape($progToken) + '"')) -and
|
||
($up.Body -match '"progress":'))
|
||
$upLast = $null
|
||
foreach ($line in ($up.Body -split "`n")) {
|
||
if ($line.StartsWith('data: ')) { try { $upLast = ($line.Substring(6) | ConvertFrom-Json) } catch { } }
|
||
}
|
||
Check 'SSE:流末尾是 upload_file 的最终响应(未取消)' `
|
||
(($null -ne $upLast) -and ([string]$upLast.id -eq '7002') -and
|
||
($null -ne $upLast.result) -and ($null -eq $upLast.error))
|
||
Check 'SSE 进度测试上传的文件已落盘' ((ListingNames $FileWriteDir) -contains $progName)
|
||
} finally {
|
||
$null = Rpc '' $null 'delete_path' @{ id = $HostId; path = ($FileWriteDir.TrimEnd('\') + '\' + $progName) }
|
||
Remove-Item -LiteralPath $progLocal -Force -ErrorAction SilentlyContinue
|
||
}
|
||
}
|
||
|
||
# ===== 汇总 =====
|
||
Write-Host ("`n通过 " + $script:pass + " 项,失败 " + $script:fail + " 项。") -ForegroundColor $(if ($script:fail -eq 0) { 'Green' } else { 'Red' })
|
||
if ($script:fail -gt 0) {
|
||
$script:failures | ForEach-Object { Write-Host (" - " + $_) -ForegroundColor Red }
|
||
exit 1
|
||
}
|
||
exit 0
|