Skip to main content
Glama
mcp-ht-better-hyperv

mcp-ht-better-hyperv

by HuanTian3365

mcp-ht-better-hyperv

简体中文 | English

一个把 Windows Hyper-V 的日常运维能力提供给任意 MCP 客户端的 server。

npm license node

项目介绍

一个独立的 MCP server,把 Windows Hyper-V 的日常运维能力交给任意支持 MCP 的客户端。通过 stdio 或 Streamable HTTP 提供 12 个 hyperv_* 工具:

  • 列出虚拟机、电源状态、代次、CPU/内存、客机心跳与是否已保存凭证

  • 截取客机当前屏幕,存成 PNG,并把图片本身返回给客户端

  • 开关机与重启(干净关机 / 断电)

  • 在宿主机上提权执行 PowerShell

  • 在客机内以管理员身份执行 PowerShell(PowerShell Direct)

  • 用合成鼠标/键盘操作客机桌面,并能把一串动作编成一次调用

⚠️ 风险声明(部署前必读) 本 server 面向“在本机管理本机 Hyper-V”的单一操作者,能力等价于把宿主机与客机的管理员权限交给调用它的模型。

  • 运行条件:Windows + 已启用 Hyper-V + 运行账户在本地 Administrators 组内;首次提权会弹出 UAC(ConsentPromptBehaviorAdmin 为静默模式时除外)。

  • hyperv_host_exec 在宿主机上以管理员权限执行任意 PowerShell;hyperv_exec 在客机内是完整管理员令牌,不受客机 UAC 约束。

  • hyperv_mouse / hyperv_keyboard / hyperv_sequence 能操作客机桌面;非 ASCII 输入会走剪贴板注入,改写并还原宿主机剪贴板(只备份还原文本)。

  • hyperv_vm_screenshot 会把客机画面交给 MCP 客户端,并默认落盘到数据目录的 screenshots\。

  • 只在本机或可信网络运行,不要暴露到公网;HTTP 传输不提供 TLS,跨机器使用请放在 HTTPS 反向代理或 VPN 之后。

  • 客机凭证以明文保存在数据目录的 config.json;HYPERV_KEEP_SCRIPTS=true 会把含明文凭据的临时脚本留在系统临时目录。

完整清单与漏洞报告方式见 SECURITY.md。

Related MCP server: vmrun-mcp

环境要求

  • Windows 10/11 Pro、Enterprise/Education 或 Windows Server,且已启用 Hyper-V

  • Windows PowerShell 5.1(优先)或 PowerShell 7(回退)

  • Node.js >= 20

  • 运行 server 的账户在本地 Administrators 组内

  • 需要交互桌面才能弹出/完成 UAC;若 ConsentPromptBehaviorAdmin=0,提权静默

安装

# 免安装直接跑(stdio,由客户端负责拉起)
npx @huantian/mcp-ht-better-hyperv

# 或全局安装,之后直接用命令名
npm i -g @huantian/mcp-ht-better-hyperv
mcp-ht-better-hyperv

从源码仓库运行时才需要在仓库目录 npm install,然后用 node src/index.js。

启动

stdio(默认):

npx @huantian/mcp-ht-better-hyperv

HTTP:

$env:MCP_HTTP_AUTH_TOKEN = "请换成一个长随机串"
npx @huantian/mcp-ht-better-hyperv --transport http --host 127.0.0.1 --port 8787

端点 http://127.0.0.1:8787/mcp,健康检查 GET /healthz。--port 0 会选空闲端口并把实际地址打印到 stderr。

stdio 模式下 stdout 只输出 MCP JSON-RPC,所有日志写 stderr 与数据目录的日志文件。

客户端配置

最小 stdio 配置:

{
  "mcpServers": {
    "hyperv": {
      "command": "npx",
      "args": ["-y", "@huantian/mcp-ht-better-hyperv"]
    }
  }
}

Claude Desktop、Claude Code、Cursor、VS Code、Codex 与通用 HTTP 的完整配置见 docs/client-setup.md,环境变量表也在那里。

工具

工具

作用

需要客机 OS

hyperv_vm_list

列出虚拟机:名称、电源状态、代次、CPU/内存、心跳、是否已存凭证

否

hyperv_vm_screenshot

截取当前屏幕,存成 PNG,返回路径 + image 内容块

否

hyperv_vm_start

启动并等待 Running

否

hyperv_vm_stop

停止并等待 Off;mode=shutdown(默认)或 turnoff

否

hyperv_vm_restart

停止 → 等待 Off → 启动 → 等待 Running

否

hyperv_host_exec

在宿主机上以管理员权限执行 PowerShell

否

hyperv_exec

在客机内以管理员权限执行 PowerShell

是

hyperv_mouse

移动、单击/双击/右键、拖拽、滚轮(仅基本会话)

是

hyperv_keyboard

ASCII 文本、键名按键、组合键;非 ASCII 自动走剪贴板

是(非 ASCII 还要凭证)

hyperv_sequence

一次调用执行一串点击/输入/等待/等画面变化/截图,失败即停

是

hyperv_credential_set

保存客机管理员用户名/密码(允许空密码)

否

hyperv_credential_clear

删除某台 VM 的凭证

否

截图

hyperv_vm_screenshot(vm, region?, savePath?) 从 Hyper-V 合成显卡取一帧,支持 region={x1,y1,x2,y2} 裁剪;越界返回 INVALID_ARGUMENT,不会自动裁边。默认保存到 <数据目录>/screenshots/,同时作为 image 内容块返回。

可能得到全黑图片,这不是故障:增强会话连接期间、没有任何基本会话连接时、或客机息屏时,Hyper-V 的帧缓冲就是空的。

鼠标与键盘

hyperv_mouse(vm, action, x?, y?, ...) 支持 move / click / drag / scroll;hyperv_keyboard(vm, text?, key?, combo?, submit?) 支持键名与组合键。

只对基本会话有效:增强会话(RDP / HvSocket)期间合成事件到不了客机,工具会明确报错。坐标是客机当前分辨率的像素坐标,原点左上,越界不夹边。含非 ASCII 字符的文本走剪贴板注入(需要该 VM 的凭证和客机上已登录的桌面),只备份还原文本剪贴板。

编排

hyperv_sequence(vm, steps, defaultSettleMs?) 把 click / type / key / combo / scroll / drag / wait / waitForChange / screenshot 编进同一次调用。waitForChange 用截图比对等待画面变化,超时报 TIMEOUT;任何一步失败立即停止,并附一张该时刻的现场截图。

两种执行工具的区别

hyperv_host_exec

hyperv_exec

在哪跑

宿主机

客机

权限

提权到宿主管理员

客机内完整管理员(无 UAC)

需要客机系统

否

是

超时行为

提权进程内部计时,到点真正停止

只限制宿主等待,客机里的命令会继续跑完

输出上限

200 000 字符,保留头尾

不截断

心跳与电源状态

Running 只说明通电,不说明有活着的操作系统。新建未装系统、开机中、崩溃的虚拟机都能列出、开关机和改配置,只有 hyperv_exec 需要活着的 Windows 客机。

Heartbeat

hyperv_exec

Ok

可以连接

NoContact / Lost / Error

无法连接

Disabled / Unknown

仍尝试连接

重要限制

  • hyperv_exec 只支持 Windows 客机:PowerShell Direct 也支持 Linux,本工具未实现。

  • 客机必须先装好系统:没装系统的 VM 只能用列表、截图、开关机和 hyperv_host_exec。

  • 截图可能全黑:增强会话、没有基本会话连接、或客机息屏时都是这样,不是工具故障。

  • 合成鼠标/键盘只对基本会话有效:增强会话期间会明确报错,而不是“成功但没反应”。

  • 非 ASCII 文本走剪贴板注入:需要该 VM 已保存凭证,且客机上有已登录的交互桌面。

  • hyperv_sequence 失败即停:不会继续执行后续步骤。

  • hyperv_exec 超时不中断客机命令。

  • 客机内是 Session 0 后台会话:命令能跑,但弹出的 GUI 窗口用户看不见。

  • 每次调用约 2–6 秒:每次都要启动一个提权进程,未实现常驻通道。

  • 凭证失效会自动清除:仅在 VM_NOT_FOUND 与 AUTH_FAILED 时;GUEST_UNAVAILABLE 与 VM_NOT_RUNNING 不清除。

  • HTTP 是无内置 TLS 的单用户服务:不是多租户网关。

文档

docs/ 目录下的文档目前仅提供中文版。

开发与测试

npm test                    # 运行 test/ 下的全部测试
npm run check               # 语法检查 + 全部测试
npm run live-check          # 只读真机冒烟
npm run screenshot-check    # 截图真机冒烟
npm run input-check         # 输入真机冒烟(会操作客机桌面)

真机脚本的注意事项见 CONTRIBUTING.md。

许可证

MIT

Available Tools

12 tools
hyperv_credential_clearA

Delete the stored guest credential for a Hyper-V virtual machine. Use it when rotating credentials or when a stored credential is known to be wrong.

Inputs: vm (required).

hyperv_credential_setA

Store the guest administrator username and password for a Hyper-V virtual machine. Omit password (or pass an empty string) when the guest account has no password. The password is never returned or logged by this tool; it is written to this plugin's local configuration file under the harness home, so it survives restarts without touching the shared credential store. Ask the user once, store it, and reuse it — do not re-ask on every run.

Inputs: vm (required), username (required), password.

hyperv_execA

Run a PowerShell command inside a Hyper-V guest as its administrator, over PowerShell Direct. Returns the guest output verbatim plus the guest exit code. Requires a stored credential (hyperv_credential_set). REQUIRES A LIVE GUEST OPERATING SYSTEM — a powered-on VM is not enough: PowerShell Direct has no channel into a guest that has not booted a Windows OS with the Hyper-V integration services running. If the VM is off it is started automatically and waited for, and then the guest heartbeat is waited on; when no guest ever answers, the tool reports GUEST_UNAVAILABLE and KEEPS the stored credential, because that failure is not a password problem. Use hyperv_vm_list to see each VM's heartbeat, and hyperv_host_exec for host-side work that needs no guest at all. The working directory defaults to whatever the remote session inherits, which is stable but not obvious; set workingDirectory when the script uses relative paths, and the resolved directory is reported back with the output. timeoutMs bounds only the host-side wait: a command already running inside the guest keeps running after this call times out, because the guest is a separate machine. hyperv_host_exec behaves differently — it owns a timer inside the elevated process and does stop its script. It is a Session 0 background session: commands run, but GUI windows it opens are not visible to the user.

Inputs: vm (required), command (required), timeoutMs, workingDirectory.

hyperv_host_execA

Run a PowerShell script on the HOST machine with Hyper-V administrator rights (elevated). Use this instead of a plain shell tool for any Hyper-V work that needs host administrator access, which a non-elevated shell answers with "Access denied": Get-VMHost*, Get-VMHostPartitionableGpu / Get-VMGpuPartitionAdapter / Add-VMGpuPartitionAdapter, Get-VMProcessor / Set-VMProcessor, Get-VMNetworkAdapter*, Mount-VHD / Dismount-VHD / Optimize-VHD / Resize-VHD / Compare-VHD, Import-VM / Export-VM / Move-VM, Get-VMSnapshot / Checkpoint-VM, Get-VMFirmware / Set-VMFirmware, Get-VMHost*, and reading C:\ProgramData\Microsoft\Windows\Hyper-V (including .vmcx/.vmrs files). Runs on the host, not inside a guest — use hyperv_exec for commands inside a VM. stdout and stderr are merged and returned verbatim, with the elevated process exit code. Elevation is silent when UAC allows it; otherwise the user sees a UAC prompt, and declining it is reported as an error instead of being retried. SCOPE — this tool is for Hyper-V and its virtual machines only. It is not a general administrator shell: do not use it for unrelated system changes, software installation, service or registry edits, reading or writing files the caller could reach by itself, or any script that has nothing to do with Hyper-V or its VMs. If a command needs no host administrator rights, or is not about Hyper-V and its virtual machines, use the ordinary shell tool instead. This boundary is an agreement with the user, not a technical control: nothing in the code rejects a command outside Hyper-V, so keeping to it is the caller's responsibility.

Inputs: command (required), timeoutMs, workingDirectory.

hyperv_keyboardA

Type text, press a single key or press a key combination inside a running Hyper-V guest. BASIC SESSION ONLY: Msvm_Keyboard events reach a basic session, but not an Enhanced Session Mode (RDP / HvSocket) connection, where they are silently dropped. The tool refuses to run when Get-VM reports EnhancedSessionTransportType = HvSocket, and when that property cannot be read it falls back to a black-frame probe (non-zero Msvm_VideoHead resolution but a near-black screen) and refuses with the same explanation. The clipboard route described below runs entirely inside the guest and is not affected. ROUTING: text that is pure ASCII is typed with Msvm_Keyboard.TypeText; tabs and line breaks in it become real Tab and Enter key presses. text containing ANY non-ASCII character is pasted: the host backs up the guest clipboard with Get-Clipboard, sets the new text, sends Ctrl+V and then restores the original clipboard. That route needs a stored credential (hyperv_credential_set; otherwise NEED_CREDENTIAL) and a logged-on interactive desktop session in the guest (otherwise a clear GUEST_ERROR), and it uses a temporary scheduled task with LogonType = Interactive running powershell.exe -NoProfile -WindowStyle Hidden -STA -EncodedCommand (never -File, which returns -196608 on this guest without executing anything). The temporary task and temp files are always removed. Only TEXT on the clipboard is backed up and restored: if the original clipboard held an image or files, that content is not preserved. SendKeys targets the foreground window, so a higher-integrity foreground window blocks the paste via UIPI. key accepts Enter, Esc, Tab, Backspace, Delete, Insert, Home, End, PageUp, PageDown, arrows (Left/Up/Right/Down), Space, F1-F12, Shift/Ctrl/Alt/Win on their own (useful to wake a blank guest display), a single letter or digit, and common punctuation on a US layout. combo is a modifier combination such as Ctrl+V or Ctrl+Shift+Esc; modifiers are pressed in order and released in reverse. provide at least one of text, key, combo (otherwise INVALID_ARGUMENT). Actions run in the order text, key, combo, and submit presses Enter last when true (default false). settleMs (default 250) is the pause after each action. Errors: VM_NOT_FOUND, VM_NOT_RUNNING, NEED_CREDENTIAL, GUEST_ERROR (enhanced session or no interactive session), INVALID_ARGUMENT for bad arguments. This tool is not concurrency safe: it is serialized with other guest input, screenshots and lifecycle calls.

Inputs: vm (required), key, text, combo, +2 more.

hyperv_mouseA

Move, click, drag or scroll the mouse inside a running Hyper-V guest, using the hypervisor's synthetic mouse (Msvm_SyntheticMouse). No guest OS cooperation and no credential are needed; the VM only has to be Running. BASIC SESSION ONLY: synthetic mouse events reach a basic session, but not an Enhanced Session Mode (RDP / HvSocket) connection — the click is silently dropped there. The tool therefore refuses to run when Get-VM reports EnhancedSessionTransportType = HvSocket, and when that property cannot be read it falls back to a black-frame probe (non-zero Msvm_VideoHead resolution but a near-black screen) and refuses with the same explanation. Disconnect the enhanced session (switch vmconnect back to a basic session) and retry. Coordinates are guest pixels of the guest's CURRENT resolution with the origin at the top-left (read from Msvm_VideoHead). Valid x is 0..width-1 and y is 0..height-1; out-of-range values are rejected as INVALID_ARGUMENT after the resolution is read, never clamped. action=click moves the pointer first, then calls ClickButton; count=2 is a double click (two ClickButton calls about 100 ms apart). action=drag presses the button at x,y, moves through five interpolated points and releases at toX,toY, pausing briefly on the end point before release. action=scroll moves to x,y and calls SetScrollPosition with delta; -120 is approximately two lines, so delta is approximate and its exact effect is guest- and application-specific. settleMs (default 250) is the pause after the action, before the call returns. The result text states what was done, the target coordinates, the guest resolution, the detected session type and the observed elapsed time. Errors: VM_NOT_FOUND, VM_NOT_RUNNING — the VM must be Running; HYPERV_UNAVAILABLE when the per-VM mouse device or the resolution cannot be resolved; INVALID_ARGUMENT for bad arguments or out-of-range coordinates; GUEST_ERROR when an enhanced session (or a suspected one) was detected. This tool is not concurrency safe: it is serialized with other guest input, screenshots and lifecycle calls.

Inputs: vm (required), action (required), x, y, +6 more.

hyperv_sequenceA

Run a whole sequence of mouse and keyboard actions in one call, to save the round trips between the agent and this tool. Each elevated call costs several seconds of process startup, so consecutive actions are compiled into a single guest-side script and executed there; only a text step containing non-ASCII characters breaks the sequence into another segment, because that step has to go through the guest clipboard (see hyperv_keyboard). Step types and their fields: click {x, y, button?, count?}; type {text} — routed exactly like hyperv_keyboard (ASCII via TypeText, non-ASCII via clipboard paste, which needs a credential and a logged-on interactive guest session); key {key}; combo {combo}; scroll {x, y, delta}; drag {x, y, toX, toY, button?}; wait {ms}; waitForChange {timeoutMs = 5000, threshold = 0.01, region?} — captures a baseline frame, then re-captures every 500 ms (plus capture time) and succeeds as soon as the ratio of differing pixels exceeds threshold; on timeout the whole sequence fails; region limits the comparison to a rectangle {x1,y1,x2,y2} in guest pixels; screenshot {savePath?} — saves a PNG using the same naming rules and default directory as hyperv_vm_screenshot. Each step is followed by defaultSettleMs (default 250), which a step can override with its own settleMs; a wait step sleeps ms and then the usual settle applies as well. BASIC SESSION ONLY, like hyperv_mouse and hyperv_keyboard: an Enhanced Session Mode (RDP / HvSocket) connection receives no synthetic input, so the sequence refuses to run when that transport is detected instead of silently doing nothing. FAILURE: the first failing step stops everything. The error names the step number, the step type and the reason, and a screenshot of that moment is saved; a waitForChange timeout is reported as TIMEOUT, out-of-range coordinates as INVALID_ARGUMENT. SUCCESS: the result lists how many steps ran, a summary line per step and the path of the last PNG. Coordinates are guest pixels of the current resolution with the origin at the top-left and are validated against Msvm_VideoHead after it is read. This tool is not concurrency safe: it is serialized with other guest input, screenshots and lifecycle calls.

Inputs: vm (required), steps (required), defaultSettleMs.

hyperv_vm_listA

List Hyper-V virtual machines on this machine with their state, generation, CPU, memory, guest heartbeat, and whether a guest credential is already stored for them. Start here: it tells you which VM to target and whether you need to call hyperv_credential_set first. The HEARTBEAT column is what decides whether hyperv_exec can reach the guest at all: a powered-on VM with no operating system installed, or one still booting or crashed, reports NoContact and cannot accept a PowerShell Direct connection, no matter what credential is stored. Listing, start/stop/restart and hyperv_host_exec never need a guest OS.

Inputs: no named parameters.

hyperv_vm_restartB

Restart a Hyper-V virtual machine: stop, wait for Off, start, wait for Running.

Inputs: vm (required), mode, timeoutSec.

hyperv_vm_screenshotA

Capture the current screen of a running Hyper-V virtual machine, save it as a PNG, and return both the absolute file path and the image itself. The frame comes from the hypervisor's synthetic video device (GetVirtualSystemThumbnailImage), so it is exactly the guest's current resolution and is decoded from an RGB565 buffer: expect slight color banding compared with a real screenshot, and expect large resolutions (4K) to be noticeably slower to capture and convert. No guest OS, credential or PowerShell Direct is involved; the VM only has to be Running. A NEARLY BLACK IMAGE IS USUALLY NOT A FAILURE: while an Enhanced Session Mode connection is active, or when no basic session is connected at all, the framebuffer the hypervisor exposes is simply empty and the PNG comes out black. A guest whose display has gone to sleep looks the same until something wakes it, and the result text says so when it happens. region is an optional crop rectangle in guest pixels with the origin at the top-left; it must fit inside the current resolution, and an out-of-range region is rejected as INVALID_ARGUMENT instead of being silently clamped. savePath takes any absolute path: an existing directory, or a path with no extension, receives the generated name -.png, while a path ending in .png is used verbatim and overwritten. Any other extension, or a relative path, is rejected as INVALID_ARGUMENT. Without savePath the file goes to /screenshots/, where dataDir is DATA_DIR or the default ~/.mcp/data/dsh-ht-better-hyperv. An existing generated name gets a numeric suffix instead of being overwritten. Errors: VM_NOT_FOUND for an unknown name, VM_NOT_RUNNING when the VM is not Running, HYPERV_UNAVAILABLE when no resolution can be read, and GUEST_ERROR when the capture API returns a non-zero code — the code and its meaning are in the message, and 32775 (Invalid state for this operation) most often means the requested size is larger than the guest's current resolution.

Inputs: vm (required), region, savePath.

hyperv_vm_startA

Start a Hyper-V virtual machine and wait until it is Running.

Inputs: vm (required), timeoutSec.

hyperv_vm_stopA

Stop a Hyper-V virtual machine and wait until it is Off. mode=shutdown (default) closes down cleanly; mode=turnoff cuts power and loses unsaved guest data.

Inputs: vm (required), mode, timeoutSec.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A4/5.0

    Scored across 12 tools

    Disambiguation4/5

    The set is largely distinct: lifecycle (list/start/stop/restart), guest input (mouse/keyboard/sequence), screenshots, credentials, and execution are separate concerns. The only pair an agent could confuse is hyperv_exec (inside guest) vs hyperv_host_exec (host, elevated), and hyperv_sequence vs hyperv_mouse/hyperv_keyboard, but the descriptions make the boundaries explicit and hard to misselect.

    Naming Consistency4/5

    All names are lowercase snake_case with a consistent hyperv_ prefix, and the dominant hyperv_vm_<action> and hyperv_credential_<action> patterns are predictable. Minor deviations exist (hyperv_host_exec and hyperv_exec place the verb last, and exec vs host_exec differ by one word), but nothing is ambiguous or chaotic.

    Tool Count5/5

    12 tools is well within a healthy range and each one earns its place: VM lifecycle, guest execution, input primitives, batching, screenshot, and credential management. There is no filler or trivially redundant tool, and the batching tool (hyperv_sequence) exists for a real round-trip cost rather than convenience alone.

    Completeness4/5

    Core workflows are covered end to end: discover VMs, power cycle them, get credentials, run commands, see the screen, and drive input. Gaps like VM creation/deletion, snapshots/checkpoints, and guest file transfer are not native tools, but the elevated hyperv_host_exec escape hatch explicitly covers checkpoints, import/export, and host-side Hyper-V cmdlets, so agents can work around them.

    Maintenance

    ActivityMaintained
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • F
      license
      Not graded
      quality
      D
      maintenance
      Enables controlled Hyper-V virtual machine operations over MCP, including status queries, checkpoints, in-guest command execution, and file transfers, without requiring guest networking or WinRM.
      1
      -
    • A
      license
      Not graded
      quality
      C
      maintenance
      Enables MCP clients to manage local VMware Workstation, Fusion, and Player virtual machines via vmrun, including power control, snapshots, guest file operations, and screen captures.
      BSD 2-Clause "Simplified"
    • A
      license
      Not graded
      quality
      B
      maintenance
      Enables remote control of a Windows desktop via MCP, including screenshots, mouse and keyboard, window management, PowerShell, files, services, registry, scheduled tasks, event log, and network checks.
      68 npm
      4
      GPL 3.0
    • A
      license
      Not graded
      quality
      C
      maintenance
      Enables MCP clients on Windows 10/11 to control an interactive desktop through screenshots, mouse and keyboard actions, window management, UI Automation, clipboard access, and multi-display switching. Supports batched actions, application access controls, and visual or text-based desktop interaction.
      33 npm
      1
      MIT