Files
SimpleRemoter/tools/mcp_smoke.ps1
T
yuanyuanxianganddeepseek-flash abe7e99a77 Feature: Harden the MCP transport and add non-destructive host tools
Cap MCP request bodies at 2 MB, set a 15 s idle read timeout and a 60 s
write timeout, and give httplib an explicit 32-thread pool: long tools
such as chat_wait hold a worker for up to 55 s, and the default pool of
8 to 15 left other callers queued.

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

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

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

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

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

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

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

Co-Authored-By: deepseek-flash
2026-10-25 13:59:17 +01:00

205 lines
9.5 KiB
PowerShell
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<#
服务端 MCP 只读冒烟测试。
只调用「不会改变任何状态」的工具(列表/详情类),断言结构化字段齐全、
分页字段正确、鉴权与请求体上限生效。可在发布前对着任一台在线主机跑一遍,
确认 MCP 链路与改动前相比没有回归。
用法:
$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)。
不指定就跳过:客户端递归用无界 wsprintf 拼 MAX_PATH 缓冲,
深目录会栈溢出(Debug 客户端弹 Run-Time Check Failure #2)。
退出码: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 = ''
)
$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
}
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)
$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)
# ===== 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)
$all = Rpc '' $null 'list_all_hosts' @{ limit = 5 }
Check 'list_all_hosts 带分页字段' (HasPaging $all.result.structuredContent)
$found = Rpc '' $null 'search_hosts' @{ query = ''; limit = 5 }
Check 'search_hosts 正常返回' ($found.error -eq $null -and (HasPaging $found.result.structuredContent))
$audit = Rpc '' $null 'get_audit_log' @{ limit = 5 }
Check 'get_audit_log 正常返回' ($audit.error -eq $null)
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))
$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)
$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:客户端递归用无界 wsprintf 拼 MAX_PATH 缓冲,深目录会栈溢出
# (Debug 客户端弹 Run-Time Check Failure #2 并挂住搜索线程)。所以默认不跑,
# 需要时用 -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)
}
} else {
Write-Host " 未指定 -SearchPath,跳过 search_file 测试(深目录会触发客户端已知的 MAX_PATH 栈溢出)。" -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)
}
# ===== 汇总 =====
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