20 Commits
Author SHA1 Message Date
yuanyuanxianganddeepseek-flash a818ace83c Fix(mcp): declare conditional tool arguments and surface probe headers
Several tools enforced argument requirements that existed only in prose,
so a model had to send a bad call to learn them. A new
AppendConditionalRequired helper emits allOf/if/then entries, and the
schemas now say:

- get_screenshot: mode=region needs width and height; mode=window needs
  hwnd. monitor keeps its default of 0.
- remote_keyboard: action=type needs text; key_down/key_up/key_press
  need key.
- remote_mouse: action=drag needs x2 and y2.
- terminal_exec: command or session_id, at least one (anyOf), matching the
  handler's -32602 when both are missing.

http_probe put the response headers only in structuredContent, which a
client that reads the text block never sees; Location, Set-Cookie and
Content-Type are exactly what a redirect or auth decision needs. The
text block now starts with a headers section, bounded to 4096 bytes and
1200 bytes per line, backing off to a UTF-8 boundary when a line has to
be cut. The full set stays in structuredContent.headers.

mcp/tools.json mirrors the schemas and tools_minimal.json is regenerated.
Verified against a fresh Debug build: verify_tools --live reports 49
tools identical.

Co-Authored-By: deepseek-flash
2026-11-13 13:12:10 +01:00
yuanyuanxianganddeepseek-flash 31883edc09 Fix(mcp): align Go tool text and list_files batch with Win32
The Go minimal server sent models after tools it does not have: read_file
pointed at download_file and search_file, both absent from its nine-tool
set, and the 2 MiB message named a download path that does not exist. It
now names list_files, terminal_exec and the Windows controller server.

Terminal errors lost the one piece of state the model needs to recover.
A busy terminal now says the holder is the web console (no MCP session to
close), and a cancelled exec carries the session_id to poll or release.

list_files ids[] was advertised in the shared schema but answered -32005.
It now implements the Win32 batch contract: 50 ids, ids past the 50 s
deadline marked skipped rather than failed, results in input order. The
deadline only gates starting a host; one already running finishes on its
own timeout, so its result is never mislabelled as a client abort. Each
entry takes the per-device lock the single-host path gets, so a host busy
with another tool fails that entry with -32003 instead of running beside
it. An empty ids array is a valid empty batch, as on Win32.

The initialize instructions now describe only what this build implements.

Co-Authored-By: deepseek-flash
2026-11-13 12:57:12 +01:00
yuanyuanxianganddeepseek-flash 61b9031269 Fix(mcp): bound host_inspect, precheck remote_open, name the busy holder
Three smaller contract fixes that remove ways for an agent call to hang
or fail without an explanation:

- host_inspect with several aspects opens one sub-connection per aspect
  (5s ready + 12s list each), so all ten could run ~170s and outlive the
  caller's HTTP timeout. After 60s no new aspect is started; the running
  one finishes on its own timeout and the skipped ones land in
  errors.<aspect> with code -32001 and a "skipped:" message, so the model
  can retry with fewer aspects.
- remote_open checked nothing before opening the hidden screen session.
  A Linux host that declares capability bits but not
  CLIENT_CAP_SCREEN_PREVIEW has no X11 display, so capture and injection
  cannot work: return -32005 immediately instead of waiting out
  timeout_ms and then reporting a sub-connection timeout. Android is
  deliberately excluded -- its SCREEN_PREVIEW bit tracks accessibility
  (API 30+ takeScreenshot for get_screenshot), while remote control uses
  MediaProjection capture and dispatchGesture, which can work without it.
  Old hosts with empty caps are still let through.
- The -32003 busy errors in remote_open now append the DescribeBusy
  suffix (tool, elapsed), matching the other busy paths.

tools.json descriptions are kept byte-identical to the C++ literals.
Debug build green; check_platform_table, gen_go_tools --check and
go test ./... pass.

Co-Authored-By: deepseek-flash
2026-11-13 12:43:37 +01:00
yuanyuanxianganddeepseek-flash d49ebe521d Docs(mcp): correct claims in the server instructions agents rely on
The initialize.instructions text is the only guide a model gets (it cannot
read docs/), and several statements disagreed with the code:

- get_keylog was described as always visible; it is gated by McpKeylog and
  hidden when the switch is off.
- Dangerous machine actions were not mentioned: freeze/thaw and
  stop/restart stay in tools/list but need McpMachineDangerous and return
  -32006 at call time.
- -32006 was described as policy/admin-only; MFC also returns it when an
  old client lacks CLIENT_CAP_V2. The Go server returns -32005 for that
  case, so its own instructions now say so.
- -32001 advice assumed every failure is a timeout; it also covers
  cancellations, http_probe parse failures and unconfirmed writes.
- "Unsupported combos always return -32005 immediately" ignored paths that
  surface as -32001 once a sub-connection is involved.
- Linux matrix listed all host_* as unsupported, but host_set_remark and
  host_set_watch_level only touch server-local data.
- local_dir / local_path are paths on the controller, not the user's box.

Also align the error table and platform distribution in the docs, and note
that hidden fallback aliases remain callable. Debug build green; go test,
check_platform_table and gen_go_tools --check pass.

Co-Authored-By: deepseek-flash
2026-11-13 12:32:33 +01:00
yuanyuanxianganddeepseek-flash 292c3191dc Fix(mcp): make declared schemas match what the handlers return
Several tool contracts disagreed with the runtime shape, which forces an
agent to guess instead of following outputSchema:

- get_server_status returned {"status": {...}} while outputSchema has the
  fields at top level; return the status object directly.
- get_screenshot description claimed structuredContent.image carries the
  base64 data; it only carries mimeType/width/height/bytes, the bytes are
  in the content image block.
- host_control_service accepted service_name silently, but not in schema;
  document the alias and add anyOf [{required:[name]},{required:[service_name]}]
  so a call missing both fails at validation, not at execution.
- kill_network_connection dry_run invented dryRun/connection fields absent
  from ActionOutputSchema; use the shared BuildDryRunResult shape.
- search_file outputSchema left files.items untyped; declare
  path/name/modified/dir/size and the paging fields it already emits.
- chat_* id hints still named the removed list_online_hosts/search_hosts.

tools.json hunks keep the live-dump key order (alphabetical inside schemas),
tools_minimal.json is regenerated, and mcp_smoke.ps1 now reads the flat
structuredContent. Debug build green; check_platform_table, gen_go_tools
--check and go test ./... pass.

Co-Authored-By: deepseek-flash
2026-11-13 12:23:39 +01:00
yuanyuanxianganddeepseek-flash 5e012019ba Fix(mcp): list the whole directory before paging list_files
list_files stopped parsing at 500 entries, so a larger directory reported
total=500 with hasMore=false and offsets past 500 returned nothing: the model
was told a false limit and could not reach the tail. Parse the full
TOKEN_FILE_LIST payload (100000 cap only to bound a pathological directory),
page over it, and report truncated=true plus a summary note when the cap hits.

Only an empty path now means list drives. Windows "." "/" "\" are normalized
to empty in BuildListFiles, while Linux/macOS "/" is a real root directory and
is listed; OnDriveList no longer keeps its own copy of the magic-path rule.

The file-manager channel carries GBK both ways (Windows FindFirstFileA;
common/FileManager.h runs gbkToUtf8 on incoming paths, utf8ToGbk on outgoing
names). The old CP_UTF8 choice for LNX/MAC decoded GBK names wrongly and sent
UTF-8 paths to a client that treats them as GBK. Paths now go out as GBK, or
as raw UTF-8 when GBK cannot represent them (the client's iconv then passes
the bytes through). Names decode GBK-first, UTF-8 on failure: UTF-8-first
misreads ~18% of common hanzi whose GBK bytes are also valid UTF-8.

Go's server gets the same contract: 100000 cap, truncated in
structuredContent, and the cap check after a real record so an exact-cap
listing with trailing padding is not called truncated. tools_minimal.json is
regenerated; the Go truncation test and the design doc are updated.

Debug server builds; check_platform_table, gen_go_tools --check and
go test ./... pass. The Release instance was not rebuilt or restarted.

Co-Authored-By: deepseek-flash
2026-11-13 12:13:20 +01:00
yuanyuanxianganddeepseek-flash 42dd70fe20 Fix(mcp): make terminal busy and cancel semantics usable by an agent
exec_command answered -32003 "device busy" with no way forward: the message
named neither the occupying session nor how to free it, and mcp_cancel_session
could only target in-flight calls, so a persistent terminal left behind by an
earlier session blocked the host until its idle timer expired. An agent had no
route back to a working state.

Build the busy text from the live session table: terminal sessions now report
parent session_id, idle and elapsed seconds, and point at terminal_exec (or
terminal_close with id and session_id) when a persistent session holds the
host, or at mcp_cancel_session(request_id) when the occupier is a running
exec_command. exec_command sweeps idle terminals before it begins a pending
wait, so a session abandoned after 300s does not require a terminal_* call
first; SweepIdleTerminals now requires started so it cannot reclaim a session
that is still in BeginTermPending and hand the device to a second caller.

Cancel becomes addressable and honest. id=0 is rejected with -32602 instead of
being treated as "all hosts", the calling request is excluded from matched and
released (previously the poll saw itself and released was never true), rows
carry cancellable, and when nothing was cancelled the reply lists what matched
and which close tool takes it. Instructions, tool description, inputSchema
(anyOf request_id/id/session_id) and the released description now agree:
kind=call only, persistent sessions close by id+session_id, pending and
file_transfer entries are released by cancelling the call that owns them.

tools.json is regenerated for the schema and description changes. Debug server
builds, check_platform_table.py and gen_go_tools.py --check pass; the Release
instance was not rebuilt or restarted.

Co-Authored-By: deepseek-flash
2026-11-13 11:56:25 +01:00
yuanyuanxianganddeepseek-flash 3d18b2119a Fix(mcp): put listing rows and host ids into text blocks
MCP clients that surface only content[].text saw just count summaries from
list_hosts and get_audit_log; the 64-bit host id lived only in
structuredContent. Without the id, read_file, get_host_detail and
terminal_exec cannot be addressed, so the tools were unusable from those
clients.

Append a tab-separated table after the summary for every list-shaped local
tool: list_hosts (id first, then name/ip/group/os/online/clientType/
last_seen), get_audit_log (time/type/msg), list_files (drives and directory
entries) and get_host_detail (compact host JSON; id/ok/detail rows for a
batch call). Only the returned page is rendered, cells are flattened to one
line, and the truncation note stays on its own line before the table.

structuredContent is unchanged and remains the authoritative copy. Tests
cover row contents, paging, escaping and truncation ordering; a live run
against a Debug client confirmed the id is now visible in text. The MFC
server needs no equivalent change: BuildResult already appends the full
structuredContent as a second text item, so text-only clients there already
receive host ids. Go's envelope emits a single text item, which is why the
rows go into it.

Co-Authored-By: deepseek-flash
2026-11-13 11:25:57 +01:00
yuanyuanxianganddeepseek-flash 70556391dd Docs(mcp): record the Go MCP overall acceptance
Run the section 5 checklist end to end against the debug Go server and a
Windows debug ghost: nine tools called, tools/list at 22578 B, twenty
consecutive terminal_exec calls with zero failures, read_file SHA-256
matched, 30 audit entries with device/tool/code/ms, and --subset passing
in both 9-tool and readonly 7-tool modes. Race tests stay clean.

Two checklist items get corrected rather than ticked: hub did change
(SendToConn in M6 and the terminal lease generation in M4a, both needed
and unit tested), and the MFC regression has no target because the whole
milestone range touches no C++ file. Note the running Release binary is
an older build reporting the old tool names; it was left alone.

Co-Authored-By: deepseek-flash
2026-11-12 23:12:29 +01:00
yuanyuanxianganddeepseek-flash d4f10db1f2 Feature(Go): verify_tools --subset and MCP deployment docs
Add a third mode to verify_tools.py that validates the Go server end to
end: it fetches /mcp tools/list and requires the name set to equal the
nine implemented tools exactly (seven in readonly mode), compares
description / inputSchema / outputSchema field by field against
mcp/tools.json, and also checks the published order. Unlike --live,
extra or missing tools are failures, not notes.

The field-comparison loop is factored into report_field_diffs so
--offline / --live and --subset share one comparison, diff printer and
FIELDS tuple.

Document and deploy the endpoint: the systemd env example gains
YAMA_MCP_TOKEN / READONLY / TERM_IDLE / MAX_CONCURRENCY / READ_MAX,
the design doc moves to implemented and its section 10 now matches the
code (embedded tools_minimal.json, the three packet dispatch groups).
The tools README explains gen_go_tools.py --check and --subset.

Verified against a freshly built debug Go server on 16543/18090:
read-write mode passes with 9 tools, YAMA_MCP_READONLY=1 passes with 7,
and both mismatch directions (extra tools, missing tools) fail with
exit 1. gen_go_tools.py --check stays clean; no Go code changed.

Co-Authored-By: deepseek-flash
2026-11-12 23:09:33 +01:00
yuanyuanxianganddeepseek-flash 9ce1a58bc3 Feature(Go): read_file over the V2 stream receiver
read_file reuses the list_files handshake: COMMAND_LIST_DRIVE opens the
file-manager sub-conn, which then gets
[CMD_DOWN_FILES_V2][targetDir\0][path\0][\0] and streams
COMMAND_SEND_FILE_V2 chunks plus a COMMAND_FILE_COMPLETE_V2 carrying the
whole-file SHA-256. Windows clients open a fresh authenticated sub-conn
for the chunks; POSIX clients stream on the file-manager conn itself, so
that conn is retired when the call ends rather than right after the
request. TOKEN_DOWNLOAD_ERROR on the file-manager conn maps to -32009 /
-32010 / -32000 like the Win32 server.

Bytes land only in a per-call os.MkdirTemp dir; the client name is
checked against the target dir (separator-normalised, path.Clean, so
..\.., absolute, UNC and mixed separators are refused) as
defence-in-depth, never used as a path. First chunk enforces the size
gate (ReadMax) and rejects multi-file batches, so an expanded directory
fails with -32602 instead of returning its first file. Chunks from a
sub-conn opened for an earlier call are dropped by connection ID, data
sub-conns are closed when the call ends, and a closed sub-conn fails the
call fast instead of waiting for the stall watchdog.

Text windowing, encoding detection (BOM / UTF-8 / GBK / explicit /
latin1) and EOL handling mirror McpServer.cpp. Verified with the Debug
ghost on Windows 11 and the WSL Ubuntu ghost: .env text plus newline is
byte-identical, sha256 equals SHA-256 over the file, windows/GBK/empty/
max_bytes/directory/size-gate/missing-path/POSIX-path cases all pass.

Co-Authored-By: deepseek-flash
2026-11-12 23:04:35 +01:00
yuanyuanxianganddeepseek-flash d7accf1d30 Feature(Go): list_files over the file-manager sub-connection
The MCP server could not browse a device's file system. It now sends
COMMAND_LIST_DRIVE on the main connection, waits for the client to open
its file-manager sub-connection and report drives, then reuses that same
sub-connection for COMMAND_LIST_FILES with the directory path. Replies
are TOKEN_DRIVE_LIST, TOKEN_FILE_LIST or TOKEN_FILE_LIST_ERROR, decoded
from the same GBK the C++ client writes on every platform.

An empty or missing path returns the drive list, matching the published
tool description. Any other path, including /, lists one level of that
directory; the Win32 server folds / into the drive list, but doing so
would make a POSIX root listing unreachable. Entries carry name, isDir,
size and an mtime converted from FILETIME, and the 500-entry cap matches
the served contract and the Win32 parser; a truncated listing says so in
the summary. The reply is paged with the usual limit/offset window.

Errors are translated like the Win32 server: win32 5 is a permission
error, 2 and 3 are not-found, anything else is internal. Legacy clients
stay silent instead of reporting an error, which surfaces as a timeout
with an explanation.

The sub-connection is a resource the client allocates per call, so one
deferred cancel is the single retirement point: it reports the sub-conn
it saw and that connection is closed on every exit path, including a
call that gives up while the drive list is already queued. Packets that
arrive after the call returned are treated as orphans and retired, and
only the connection that answered the drive-list phase may answer the
directory request.

Also add a uniqueness test over the command and token byte constants,
and SendToConn so sub-connections are written through the hub's framing
path instead of a raw conn write.

Co-Authored-By: deepseek-flash
2026-11-12 22:34:17 +01:00
yuanyuanxianganddeepseek-flash 5227d4d78e Feature(Go): get_screenshot over the main-connection preview RPC
COMMAND_SCREEN_PREVIEW_REQ (247) / TOKEN_SCREEN_PREVIEW_RSP (248) is a
request/reply pair on the device's main connection: the client captures,
scales and encodes the frame itself, so no sub-connection is opened and no
screen-session slot is taken. get_screenshot can therefore run while a
human is watching the same machine.

The server keeps one pending request per device in a small table, matches
replies by reqId and drops foreign or late ones, and bounds a round trip
with an 8s timer. A missing CLIENT_CAP_SCREEN_PREVIEW bit is refused with
-32005 before anything is sent; region/window/monitor parameters are
refused with the same code because the v2 CLIENT_CAP_SCREEN_REGION
extension is not implemented in this build. Status 4 maps to -32602
because the caller can fix the target, while capture/encode failures stay
-32000.

Windows clients return JPEG directly. Linux clients have no JPEG encoder
and return top-down BGRX, which the server converts (R/B swap, opaque
alpha) before wrapping the frame as an MCP image item. The image item is
new to the content envelope; text tools keep text-only items.

Verified live against x64\Debug\ghost.exe (JPEG FF D8 FF, decoded size
matches metadata, max_width clamped to 64) and against linux/ghost under
WSL (BGRX path, valid JPEG, black frame from the known Xwayland capture
limitation). gofmt/vet clean, unit and -race tests green.

Co-Authored-By: deepseek-flash
2026-11-12 22:07:07 +01:00
yuanyuanxianganddeepseek-flash 808747f9d2 Feature(Go): terminal_close, idle sweep and legacy-client guard
Add the terminal_close tool so a caller can release a shell session
explicitly instead of waiting for it to age out. The tool is idempotent
for the session it names, rejects a session_id that does not match the
live session with -32002, and runs without the per-device lock so it can
interrupt a terminal_exec call that is still polling on the same device.

Give hub leases a generation counter: the generation is bumped when a
pending lease is created and carried across a device re-login. MCP-side
closes pass the generation, so a stale session can no longer tear down a
shell a human operator opened after the device reconnected. The reaper
runs on a 30 s ticker (shortened when TermIdle is smaller), skips
sessions that are still opening, and reclaims idle sessions as well as
commands overdue past the one-hour busy cap.

The pre-bind terminal-close path in cmd no longer closes
unconditionally; it touches only a pending lease, because an unbound
sub-connection carries no lease identity and may be a stale orphan.

Covered by unit tests for close semantics, lock exemption, reaper
lifecycle and lease-generation ownership, plus a live run against a
Debug ghost: close before and during a command, reopen, idle reap and
mismatched-id rejection all behave as specified.

Co-Authored-By: deepseek-flash
2026-11-12 21:53:54 +01:00
yuanyuanxianganddeepseek-flash 599c891c00 Feature(Go): terminal_exec with sentinel cleaning and polling
Implement M4b of the Go MCP minimal plan: terminal_exec runs one command in a
device's persistent shell and polls the rest of a timed-out command.

Wire format follows the Win32 server: ConPTY sends "@echo off & <cmd>" plus a
sentinel line carrying %errorlevel%; POSIX PTY clears PS1 and uses $?. Output
cleaning is a byte-faithful port of the MFC stages (ANSI, CRLF, echoed input,
sentinel remnants) and is shared by commands and polls.

A timed-out call leaves the session and the command running; the next call with
only session_id delivers from the cursor it left. Per-window output is bounded
by max_output_bytes, truncated on a line boundary, and ring evictions are
reported as dropped_bytes. When the shell dies mid-command the session stays
reachable until its buffered tail has been polled, then is released without
touching the hub, which may already belong to a new viewer.

Adds ClientCapTerminal (0x8000) for the Android gate; older APKs, macOS and
legacy non-PTY shells are refused with -32005.

Co-Authored-By: deepseek-flash
2026-11-12 21:38:00 +01:00
yuanyuanxianganddeepseek-flash 12b1bd4786 Feature(Go): MCP terminal sessions with a 256 KiB ring buffer
Add the server-side half of the terminal tools: a per-device session
table that claims the hub's single-viewer shell lease for MCP, and an
output ring that survives a timed-out request so a later poll can still
collect the command's result (terminal_exec itself arrives in M4b).

The ring keeps the newest 256 KiB of shell output, tracks absolute
offsets, and counts dropped bytes so callers can report truncation. A
sentinel scanner looks for the per-command done marker, skipping the
echoed command line and accepting Windows' negative error codes; its
scan position is incremental with a small overlap so a marker split
across TCP reads is still found.

Server implements hub.EventHandler and cmd subscribes it when the
endpoint is enabled; only the three terminal callbacks do work, and
OnTerminalData stays cheap on the TCP read loop (lookup, append, scan,
broadcast). Opening inserts the session before calling the hub so an
early OnTerminalReady cannot be lost, stale close events that race a
fresh open are ignored while the hub still holds the lease, and idle
sweeps verify session identity. The reaper and terminal_close land in
M4c.

Co-Authored-By: deepseek-flash
2026-11-12 21:14:53 +01:00
yuanyuanxianganddeepseek-flash 1076e7614a Feature(Go): per-device locks, a global call gate and tool-call audit
Add the three cross-cutting guards the Go MCP endpoint needs before any
tool talks to a client. Each tools/call now takes one of MaxConcurrency
global slots and, for single-host tools, that host's device lock; both are
non-blocking, so contention returns -32003 instead of queueing. Panicking
handlers are converted to -32000 rather than dropping the connection.

Write one mcp.tool.call audit record per named call, including rejected
ones: actor/role/source, tool, device, ok/code, duration, a size-only
result summary and a truncated argument digest. Commands keep only their
first word plus length, and free-form or credential fields (text, message,
body, headers, password, token) are replaced by their size, so secrets do
not reach the audit file.

Co-Authored-By: deepseek-flash
2026-11-12 21:05:37 +01:00
yuanyuanxianganddeepseek-flash 774c0d2545 Feature(Go): four local MCP read tools and a shared audit query package
Implement milestone M2 of the minimal MCP plan: the tools that answer from
the server's own state instead of opening a device channel.

- Extract the audit-log scanner from web into package auditquery so the
  admin page and get_audit_log share one implementation. The web handler
  keeps its 500-row cap, the MCP tool uses the protocol's 1000-row cap.
  Query gains json tags for the web snake_case wire format (device_id,
  warn_only) and reports TotalAll before filters.
- Add package buildinfo and inject Version/Commit with -X from build.ps1
  and the Makefile; go-winres refreshes Windows resources from the git tag
  when available. An unversioned build reports "", and only initialize
  substitutes "dev".
- list_hosts: online/offline pools, include_offline merge, every
  documented filter, limit/offset paging with total/totalAll/hasMore, and
  schema-named host fields (authStatus/tls/remark are never fabricated).
- get_host_detail: single id or a batch of up to 50, online lookup then
  the last history record, capabilities from protocol.SupportsCap plus the
  Windows/registry/virtual-desktop rules; v2 is not listed.
- get_server_status: version, uptime, online/offline counts, port and
  bind. sessions stays absent until the MCP session table lands in M3.
- get_audit_log: case-insensitive event substring, keyword, paging;
  hasMore turns false at the MaxOffset clamp so paging cannot loop.

Wire hub, history, audit path and listen address through mcp.Config from
cmd/main.go. Tests cover pools/filters/paging, capability bits, batch
failures, audit paging and the unversioned build.

Co-Authored-By: deepseek-flash
2026-11-12 20:55:18 +01:00
yuanyuanxianganddeepseek-flash 3f1957a9c9 Feature(Go): MCP endpoint with bearer auth and tools/list
Add a stateless POST /mcp endpoint to the Go server, mounted by the web
server and built from an environment-driven Config in cmd.

The endpoint gates on YAMA_MCP_TOKEN: without it the route is not
registered and /mcp 404s. Requests use a constant-time bearer compare,
and transport failures stay transport failures (401 with a
WWW-Authenticate challenge, 405 for anything but POST, 413 above 8 MiB,
204 for notifications). Everything after a parsed JSON-RPC request is
HTTP 200, including -32600 for batch arrays and -32601 for unknown
methods or tools.

tools/list returns the nine minimal tools verbatim from an embedded
copy of the canonical schemas. tools/mcp_tools/gen_go_tools.py extracts
them from mcp/tools.json, preserving order and only the four published
fields, and its --check mode detects drift. Readonly mode hides and
refuses terminal_exec/terminal_close (-32006); tools that are listed but
not implemented yet answer -32000 until their milestone lands.

Also sync design §3.2 and the M2/M7/M8 plan text to tools.json, which
is the sole schema contract: files not entries, line-based read_file,
no since, camelCase capabilities, max_width [64,1920] defaulting to
1024, and outputSchema included in the M8 subset comparison.

Co-Authored-By: deepseek-flash
2026-11-12 20:35:03 +01:00
yuanyuanxianganddeepseek-flash 5f124fcb3a Docs(mcp): add Go minimal MCP design and implementation plan
Add the v1.0 design for the Go-side minimal MCP server (nine read-only
tools over hub, audit log, terminal and file channels) and the staged
plan that turns it into eight commits.

Record the five decisions settled before construction: extract the audit
query scanner into server/go/auditquery, inject version and commit via a
buildinfo package plus go-winres, treat mcp/tools.json as the only tool
schema contract, verify against a real client, and expose seven tools in
readonly mode.

Add the M0 findings: TestRun.exe cannot log in, because it needs
ServerDll.dll loaded through MemoryDllRunner and the release build deletes
itself when started outside its install path. A Debug ghost.exe came
online against a local Go server in trial signer mode within ten seconds.

Co-Authored-By: deepseek-flash
2026-11-12 20:17:54 +01:00
52 changed files with 14465 additions and 564 deletions

No files matched your search

+1
View File
@@ -95,6 +95,7 @@ server/go/web/assets/index.html
server/go/users.json
server/go/devices.json
server/go/build/
server/go/cmd/*.syso
server/go/.claude/settings.json
android/app/.cxx/
+36 -1
View File
@@ -74,8 +74,28 @@ function Build-GoServer {
} else {
Join-Path $binDir "YamaGo_x64.exe"
}
# Version/commit metadata injected into serverInfo and get_server_status.
# Empty when git is unavailable (source tarball, IDE build) — the server
# then reports no version rather than a fabricated one.
$gitVersion = ""
$gitCommit = ""
if (Get-Command git -ErrorAction SilentlyContinue) {
$gitVersion = (& git -C $rootDir describe --tags --always --dirty 2>$null | Select-Object -First 1)
if ($LASTEXITCODE -ne 0 -or -not $gitVersion) { $gitVersion = "" } else { $gitVersion = "$gitVersion".Trim() }
$gitCommit = (& git -C $rootDir rev-parse --short HEAD 2>$null | Select-Object -First 1)
if ($LASTEXITCODE -ne 0 -or -not $gitCommit) { $gitCommit = "" } else { $gitCommit = "$gitCommit".Trim() }
}
$buildinfoPkg = "github.com/yuanyuanxiang/SimpleRemoter/server/go/buildinfo"
$ldflagParts = @()
# Release strips debug info for smaller binary; Debug keeps symbols.
$ldflags = if ($Configuration -eq "Debug") { "" } else { "-s -w" }
if ($Configuration -ne "Debug") { $ldflagParts += @("-s", "-w") }
if ($gitVersion) { $ldflagParts += @("-X", "$buildinfoPkg.Version=$gitVersion") }
if ($gitCommit) { $ldflagParts += @("-X", "$buildinfoPkg.Commit=$gitCommit") }
$ldflags = $ldflagParts -join " "
if ($gitVersion) {
Write-Host "Version: $gitVersion ($gitCommit)" -ForegroundColor DarkGray
}
# Save the caller's Go env so a direct .\build.ps1 invocation does not
# leave GOOS=linux behind for later builds in the same shell.
@@ -90,6 +110,21 @@ function Build-GoServer {
# Cross-compiling for Linux requires a pure-Go build; the server has
# no cgo dependencies, so this is the normal configuration.
if ($TargetOS -eq "linux") { $env:CGO_ENABLED = "0" }
# Refresh the Windows resources before linking: go-winres rewrites the
# manifest identity, FileVersion and ProductVersion from the git tag so
# Explorer's file properties match the tag while the runtime version
# string stays the full `git describe` output. Missing go-winres or a
# non-git tree keeps the checked-in .syso files unchanged.
if ($TargetOS -eq "windows" -and $gitVersion) {
if (Get-Command go-winres -ErrorAction SilentlyContinue) {
& go-winres make --in cmd/winres/winres.json --out cmd/rsrc --product-version git-tag --file-version git-tag
if ($LASTEXITCODE -ne 0) {
Write-Host "WARNING: go-winres failed; keeping existing cmd/rsrc_*.syso" -ForegroundColor Yellow
}
} else {
Write-Host "WARNING: go-winres not found; version resources not refreshed (go install github.com/tc-hib/go-winres@latest)" -ForegroundColor Yellow
}
}
if ($ldflags) {
& go build -ldflags $ldflags -o $outFile ./cmd
} else {
+6 -6
View File
@@ -511,7 +511,7 @@ void CMcpSettingsDlg::OnBnClickedBtnSave()
- `structuredContent` 统一附 `total` / `totalAll` / `offset` / `limit` / `hasMore`,与 `McpMachine.cpp` 既有约定一致(`host_list_*` / `list_network_connections` 本来就是这样)。
- `content` 摘要统一为「共 N <单位>,本次返回第 a-b 条(还有更多,可用 offset 继续取)。」;`hasMore=false` 时不再出现「继续取」的误导提示;`offset` 越界时明确写「offset 超出范围,本次返回 0 条」。
- 实现集中在 `McpInternal.h/.cpp`:`PageWindow` / `ResolvePageWindow` / `ApplyPageWindow` / `WritePageFields` / `AppendPagingProps` / `PageSummary`。
- `list_files` 仍受服务端 `ParseFileList` 的 500 条硬限制(`total=500` 且原目录确有更多条目时表示截断,不是服务端分页)。客户端侧不截断、按需扩缓冲一次性回全量;本轮未加 `truncated` 标记(要加得改服务端 `ParseFileList` 的调用约定),仍靠「`total=500` 且 `hasMore`」判断。
- `list_files` 整目录解析后再分页:`ParseFileList` 的上限是 100000 条,只用于兜住病态目录;到上限时 `structuredContent.truncated=true`,摘要与 `total` 也会说明 `total` 只是上限内的数量。`total` / `hasMore` 反映真实目录条目数,`offset` 可翻到 500 条之后。分页由服务端完成(`limit` 默认 100、上限 1000),客户端仍一次性回全量。
---
@@ -597,7 +597,7 @@ token 只从 `-Token` / env 读取,不落仓库、不打印;无在线主机
### 10.8 D 批:拒绝也入审计
动机:所有策略拒绝(只读模式、`Mcp*` 开关关闭、主机不支持某能力)都返回 `-32006`,而审计里只有 `CALL_FAIL`——和「参数错」「主机离线」「超时」混在一起,事后分不清「没人调过」和「被策略拦下」。
动机:策略拒绝(只读模式、`Mcp*` 开关关闭,以及老客户端 V2 这类能力缺失)返回 `-32006`;平台/能力位不匹配的多数返回 `-32005`。此前审计里只有 `CALL_FAIL`——和「参数错」「主机离线」「超时」混在一起,事后分不清「没人调过」和「被策略拦下」。
- 实现放在 `tools/call` 的统一出口(`CMcpServer` 的 HTTP 处理器),不在 24 个 `-32006` 分支里逐个埋点:成功解析响应体后多取 `error.code` / `error.message`,`code == -32006` 就追加一条
```
@@ -628,7 +628,7 @@ token 只从 `-Token` / env 读取,不落仓库、不打印;无在线主机
排查「改动到底生效没有」「为什么某个工具被拒」时,原先只能靠 `list_online_hosts` 加 `get_audit_log` 侧面推断;现在有一个服务端自身的状态快照。纯内存、只读、不建子连接。
返回(`structuredContent.status`):
返回(`structuredContent` 顶层,与 outputSchema 字段一一对应;早期版本曾多包一层 `status`,已修):
| 字段 | 含义 |
|---|---|
@@ -678,12 +678,12 @@ token 只从 `-Token` / env 读取,不落仓库、不打印;无在线主机
| `-32600` | Invalid Request | 缺 `jsonrpc` / `method` / 非法 `tools/call` 结构 | 修正请求 |
| `-32601` | Method not found | `method` 不是 `initialize` / `tools/list` / `tools/call` 等 | 修正请求 |
| `-32602` | Invalid params | 未知工具名、缺必填参数、参数类型/取值非法、批量 `ids` 超过 50 个、`search_file` 过滤参数非法、文本无法转 GBK | 改参数重试,重试同样的请求不会成功 |
| `-32001` | Timeout | 等客户端就绪/等子连接/等搜索结果超时(`timeout_ms` 内没等到) | 可加大 `timeout_ms` 重试;持续出现看主机是否卡住 |
| `-32001` | Timeout / execution failure | 多为等客户端就绪/等子连接/等搜索结果超时(`timeout_ms` 内没等到);也用于工具自身失败(`http_probe` 解析失败、目标端未确认写入)与已取消(`Request cancelled`) | 先看 `message`:超时且工具支持 `timeout_ms` 可加大重试;子连接没建立/反复超时通常重试无效;`Request cancelled` 可直接重试;其余按 `message` 处理 |
| `-32002` | Host offline / not found | 主机 id 不存在、主连接已断、会话 id 不存在或已关闭 | 先 `list_online_hosts` 刷新再选主机 |
| `-32003` | Busy | 该主机已有同类请求在飞(终端/截屏/文件/聊天会话),或同设备重复 `chat_open`。`message` 末尾带 `(tool=..., elapsed=Ns)` 点名占用者 | 用 `mcp_list_sessions` 看全部会话;等前一个结束、先 `*_close`,或 `mcp_cancel_session` 释放 |
| `-32004` | Send failed | 命令写入主连接失败(连接刚断) | 重试一次;仍失败按 `-32002` 处理 |
| `-32005` | Not supported on this host | 能力限制,改参数也修不好:需要 Windows 的工具用在 LNX/MAC/APK 主机上;`remote_open` 遇到多显示器(阶段一);主机无屏幕预览/控制能力位 | 换主机或换工具;不要改参数重试 |
| `-32006` | Policy refused | 只读模式 / 对应 `Mcp*` 开关关闭 / 主机不支持该能力(如 V2 文件传输) | **不要重试**:这是配置决定,需管理员改服务端配置 |
| `-32006` | Policy refused | 只读模式 / 对应 `Mcp*` 开关关闭;MFC 端还包括老客户端不支持 V2 文件传输(`download_file` / `upload_file` / `read_file` / `copy_files_c2c`;Go 端这种情况返回 `-32005`) | **不要重试**:开关/只读需管理员改服务端配置,老客户端需升级 |
| `-32007` | Not in command whitelist | `exec_command` 的命令不在 `McpCmdWhitelist` 里,或词边界不匹配(`dir` 过、`dirx` 拒) | **不要重试**:换成白名单内的命令,或请管理员加白名单项 |
| `-32012` | Rejected by validation | 只覆盖「参数被校验拒绝、改参数可修」:`exec_command` 含 shell 元字符(Windows `&\|<>^`;Linux `&\|<>;` 与反引号、`$(` `${` `!`)或控制字符(含 `\r\n`);`terminal_exec` 含控制字符(含换行),或**老非 PTY 会话**里含 `&`/`\|`,或 POSIX 会话里含裸后台 `&`;路径/参数含非法字符。**`-32008` 是同一语义的历史别名**(早期实现用它,已发布的客户端/文档可能仍在匹配),新代码一律用 `-32012` | 按 `message` 修正参数后重试 |
| `-32009` | Target not found | 远端路径/注册表键不存在(win32 `2`/`3`,由新客户端主动回报);`kill_network_connection` 的四元组在当前连接表里查不到(`dry_run` 传假四元组最常见) | 先用 `list_files`/`list_registry`(或 `host_list_network_state`)确认目标存在 |
@@ -848,7 +848,7 @@ ECDSA 这条是 MS Software KSP 唯一可行的一条,其余几条均已实测
### 14.3 验证
Debug 实例(`Bin\Yama_x64d.exe`,临时端口)实测:`list_all_hosts` 的 `content[1]` 含完整主机 JSON(`id` / `ip` / `last_seen` …),`get_server_status` 的 `content[1]` 是 `{"status":{…}}`,`search_hosts` 空结果时是 `{"hasMore":false,"hosts":[],…}`;`content[0]` 的既有摘要文案一字未改。
Debug 实例(`Bin\Yama_x64d.exe`,临时端口)实测:`list_all_hosts` 的 `content[1]` 含完整主机 JSON(`id` / `ip` / `last_seen` …),`search_hosts` 空结果时是 `{"hasMore":false,"hosts":[],…}`;`content[0]` 的既有摘要文案一字未改。`get_server_status` 的 `content[1]` 是状态对象本身(与 outputSchema 的顶层字段一致;早期版本多包了一层 `status`,已修)。
### 14.4 影响面
+860
View File
@@ -0,0 +1,860 @@
# Go 服务端 MCP 最小工具集设计
> 版本:v1.0(定稿) 状态:**已实施(M0–M8 全部落地,2026-11-12)** 日期:2026-11-12
>
> 实施计划与各里程碑验收口径见 `Mcp_Go_Minimal_Implementation_Plan.md`。
>
> 前置文档:`Mcp_Tool_Optimization_Plan.md`(MFC 侧工具优化,已全部落地)、
> `Mcp_FileTransfer_Design.md`(V2 文件传输协议与无头接收端)、
> `Mcp_Design.md`(MCP 协议/错误码基线)、`FILE_TRANSFER_V2.md`(V2 协议清单)。
>
> 适用范围:`server/go` 新增 MCP 端点与 9 个工具。**不改客户端**——所有用到的
> 命令与令牌均为 `common/commands.h` 既有定义,客户端已实现。
>
> 本文与 MFC 侧的差异只有一个来源:**Go 服务端的协议实现面比 MFC 窄**。MFC 有 54 个
> 工具,是因为它把 20 多条客户端命令都接进了服务端;Go 目前只接了 4 条。所以这里的
> "最小"不是"先做简单的",而是"按 Go 已具备的协议能力面裁剪,剩下的按需补齐"。
---
## 0. 结论摘要
1. **v1 交付 9 个工具**,全部命名、参数、错误码与 MFC 对齐,同一句提示词在两个后端都能跑通:
`list_hosts` / `get_host_detail` / `get_server_status` / `get_audit_log` /
`get_screenshot` / `terminal_exec` / `terminal_close` / `list_files` / `read_file`。
2. **四条设备通道,三种是既有基础设施**:终端(`hub` 已有,只需加哨兵与输出缓冲)、
主连接 RPC(`hub.SendToDevice`)、文件管理器子连接(`TOKEN_CONN_AUTH` 已把 clientID
钉在 ctx 上,按 clientID 路由即可,**不需要** MFC 那套 pending + CancelIO)。
只有 V2 流式子连接的接收端是全新的。
3. **`get_screenshot` 走主连接 RPC(`COMMAND_SCREEN_PREVIEW_REQ`),不碰屏幕流。**
屏幕流是持续推的 H.264(首帧裸 BGRA),取一帧就得建屏幕子连接、占住每设备唯一的
屏幕槽位、用完再拆——代价远大于收益。预览 RPC 是主连接上的一次性请求响应,
客户端自己抓屏编码回 JPEG(Linux 客户端回 BGRX,服务端编码)。不占任何槽位。
4. **终端槽位是 Go 独有的硬约束**:`hub.go:86` 写明 *at most one web terminal per device*。
v1 不做抢占——浏览器开着终端时 MCP 返回 `-32003`,空闲 3 分钟自动释放。
这是安全默认,代价是"人在用终端时 AI 用不了",写进工具描述让模型自己换路。
5. **MCP 端点零新增端口**:挂在现有 Web 服务的 `/mcp`(`web/server.go:126` 的 mux 里加一行),
无状态 JSON-RPC,不引入 `Mcp-Session-Id`。鉴权用单一静态令牌(`YAMA_MCP_TOKEN`),
映射到固定 principal `mcp`(role=admin)。
6. **明确不做**:`remote_*`、`chat_*`、`host_*`、进程/服务/注册表/窗口枚举、文件写操作、
`exec_command`(白名单一次性执行,被 `terminal_exec` 覆盖)、`outputSchema`。
---
## 1. 范围
### 1.1 做
| 层 | 内容 |
|---|---|
| 端点 | `POST /mcp`(JSON-RPC 2.0 / MCP 2025-06-18),`initialize` / `notifications/initialized` / `ping` / `tools/list` / `tools/call` |
| 鉴权 | `Authorization: Bearer $YAMA_MCP_TOKEN`,常量时间比较 |
| 工具 | 9 个(见 §3) |
| 审计 | 每次调用一条 `mcp.tool.call` 记录,进既有审计通道 |
| 设施 | 每设备单请求互斥、终端会话表、主连接 RPC 请求表、V2 接收端 |
### 1.2 不做
| 不做 | 理由 |
|---|---|
| `remote_open` / `remote_keyboard` / `remote_mouse` 等 | Go 有屏幕流但没有"注入结果回执",做出来无法验证;且属高风险写操作,先不开放给模型 |
| `chat_*` | Go 无 `COMMAND_CHAT` 实现 |
| `host_inspect` / `host_control_*` / 进程/服务/注册表/窗口枚举 | Go 协议层完全没有这些命令(`protocol/commands.go` 只声明了 4 条命令族) |
| 文件写(`delete_path` / `move_path` / `upload_file` / `create_folder`) | V2 上传方向需要服务端作 sender,工作量与本期的接收端不对称;先只读 |
| `download_file` | 接收端与 `read_file` 完全共用,v1.1 加约 20 行即可(差别只是落盘后不删)。v1 先只做"读",避免多一个往主控磁盘写文件的入口 |
| `exec_command`(白名单一次性执行) | `terminal_exec` 已覆盖同一场景且无白名单摩擦(MFC 实测 `-32007` 全是白名单误拒) |
| `outputSchema` | MFC 实测 outputSchema 占 `tools/list` 的 49,320 / 136,692 字节。9 个工具没必要背这个体积 |
| 多用户令牌 / 按分组授权 | v1 单 principal;多用户留到 Go 侧真正多租户部署时(见 §12 R6) |
---
## 2. 基线
### 2.1 MFC 侧已交付(可直接对标的参照)
`mcp/tools.json` 当前 `toolCount=54`(优化前 63),默认配置下可见 21 个。
`Mcp_Tool_Optimization_Plan.md` 的八项已全部落地,其中三项对 Go 有直接约束力:
| MFC 改动 | 对 Go 的约束 |
|---|---|
| `terminal_exec` 的 `session_id` 可变可选、无会话时隐式创建 | Go 不设 `terminal_open`,`terminal_exec` 隐式建会话 |
| 超时保留会话、返回部分输出、`session_id` 轮询续取 | Go 同款语义,见 §6.6 |
| `read_file` 复用 `download_file` 的 V2 接收端 | Go 的 `read_file` = 下载到临时目录 + 读 + 删,两者共用一份接收端 |
### 2.2 Go 侧现状
`protocol/commands.go:105-140` 声明的命令常量里,真正有发送点的只有三处:
| 能力 | 状态 | 位置 |
|---|---|---|
| 屏幕查看 / 控制 / 剪贴板 | 已实现(H.264 流 + 鼠标键盘) | `cmd/main.go` `handleScreenFrame` |
| PTY 终端(每设备单会话) | 已实现,**仅浏览器流式转发** | `hub.go:756` / `hub.go:983` / `cmd/main.go:101-109` |
| 卸载被控端 | 已实现 | `web/ws_handlers.go:1139` |
| 设备 / 用户 / 分组 / 审计 | 已实现 | `hub.ListDevices` / `devicehistory.Offline` / `web/audit_query.go` |
| 子连接鉴权(clientID 绑定) | 已实现 | `cmd/main.go` `handleConnAuth` |
| 文件管理器(列盘/列目录/读/写) | **完全没有** | — |
| 一次性命令执行 | **完全没有** | — |
| 屏幕预览 RPC | **完全没有** | — |
### 2.3 两条可直接复用的结论
1. **终端是"跑命令"的唯一入口**。MFC 实测 186 次调用里 109 次是 `terminal_exec`
(58.6%),且 59% 的命令本质是"读"。Go 没有必要先做一堆专用只读工具,
把 `terminal_exec` 做扎实就是最高性价比。
2. **但 `read_file` 不能省**。MFC 的优化结论是"`read_file` 是唯一真正的功能缺口"——
终端读文件会被 PTY 回显、ANSI 转义、ConPTY 重绘污染,`.env` 这类文件读出来是脏的。
Go 既然要上文件管理器,就一次做对。
---
## 3. 工具集
### 3.1 清单
| # | 工具 | 通道 | 只读 | 依赖能力位 |
|---:|---|---|:--:|---|
| 1 | `list_hosts` | 本机 | ✅ | — |
| 2 | `get_host_detail` | 本机 | ✅ | — |
| 3 | `get_server_status` | 本机 | ✅ | — |
| 4 | `get_audit_log` | 本机 | ✅ | — |
| 5 | `get_screenshot` | 主连接 RPC | ✅ | `CLIENT_CAP_SCREEN_PREVIEW` |
| 6 | `terminal_exec` | 终端子连接 | ❌ | — |
| 7 | `terminal_close` | 终端子连接 | ❌ | — |
| 8 | `list_files` | 文件管理器子连接 | ✅ | — |
| 9 | `read_file` | V2 流式子连接 | ✅ | —(见 §5.4 的说明) |
`YAMA_MCP_READONLY=1` 时只暴露 1/2/3/4/5/8/9 七个(6/7 隐藏)。
### 3.2 逐个定义
本节只用于阅读;**参数名与返回字段的唯一契约是 `mcp/tools.json` 的 `inputSchema` /
`outputSchema`**(M1 起 `tools/list` 原样返回这些定义)。Go 取不到的字段省略,不伪造。
#### `list_hosts`
```jsonc
// input(全部可选)
{ "client_type": "EXE", "group": "asm", "include_offline": false, "ip": "10.",
"limit": 100, "name": "ASM-", "offset": 0, "online": true, "os": "Windows",
"query": "asm" }
// output.structuredContent
{ "hosts": [ /* ... */ ], "total": 7, "totalAll": 9, "limit": 100, "offset": 0, "hasMore": false }
```
`client_type/group/ip/os` 为大小写不敏感子串过滤;`name` 只匹配计算机名,`query` 同时匹配
计算机名、备注与 IP;`online=true`(默认)只列在线,`false` 只列历史中存在但当前离线的;
`include_offline=true` 时再合并 `devicehistory.Store.Offline(online)`。`total` 是过滤后命中数,
`totalAll` 是过滤前总数,`hasMore` 表示同一条件下还有下一页。
`hosts[]` 的字段按 `outputSchema`:`id/name/group/version/clientType/os/ip/rtt/activeWindow/
screen/online/last_seen`,以及 hub 或历史记录里确有的 `location/install_time`;两个服务端都
没有 `authStatus/tls/remark`,不输出。离线历史条目不存 `clientType`,也没有 `rtt/activeWindow`。
#### `get_host_detail`
```jsonc
{ "id": "7888521104752806905" } // 或 { "ids": ["…", "…"] }(≤50 台,批量)
```
单台返回 `{ host: {...} }`;批量返回 `{ tool, total, succeeded, failed, skipped, results[] }`。
`host.capabilities` 由 `protocol.SupportsCap` 逐位解出,字段名与 schema 一致:
`screenPreview / screenRegion / windowInfo / fileTransferV2 / c2cPaths / registry /
remoteControl / platform`。
注意**不要把 `v2` 放进 capabilities**:`CLIENT_CAP_V2` 在 `DefaultCaps()` 里全平台恒真
(`common/commands.h:1289`),列出来只会误导模型。
#### `get_server_status`
无参。返回字段按 `outputSchema`:`version / uptime_sec / hosts / sessions / port / bind /
switches / blocked_auth_ips / exe_build_time / app_name`。Go v1 只填能如实取到的:
`version`(buildinfo)、`uptime_sec`、`hosts`(在线/历史计数)、`sessions`(MCP 活动调用,
M3 起)、`port`、`bind`;其余属 MFC 专有,直接不给(schema 的 `required` 为空)。
`version` 取 `-ldflags -X` 注入的 `buildinfo.Version`——**Go 侧目前没有版本变量**
(`cmd/main.go` 里查不到),需要新增 `buildinfo` 包并在 `Makefile` / `build.ps1` 里注入;
拿不到时返回空串,不要伪造。`commit` 只用于日志与排障,不塞进 schema 未定义的返回字段。
#### `get_audit_log`
```jsonc
{ "keyword": "terminal", "type": "mcp", "limit": 100, "offset": 0 }
```
复用 `web/audit_query.go` 的查询器(M2 抽成 `auditquery`),返回
`{ entries, total, totalAll, limit, offset, hasMore }`。**没有 `since`**:MFC 的 schema 里就没有。
#### `get_screenshot`
```jsonc
{ "id": "...", "max_width": 1024 }
// output: content[] 里一项 image(mimeType=image/jpeg, base64 data)
// structuredContent: { image: { mimeType, width, height, bytes },
// capture: { mode, x, y, width, height, scale, native } }
```
`max_width` 钳制到 `[64,1920]`;缺省/0 时 Go v1 固定 1024(没有 MFC 的 RTT 自适应档位)。
`mode=region/window/monitor` 与 `hwnd/x/y/width/height` 需要 `CLIENT_CAP_SCREEN_REGION` 扩展,
M5 之前传任一参数都返回 `-32005` 并在 message 里点名。细节见 §7。
#### `terminal_exec`
```jsonc
// 执行
{ "id": "...", "command": "sc query AssemblyManager", "timeout_ms": 20000, "session_id": "..." }
// 轮询(不带 command)
{ "id": "...", "session_id": "s-3f2a", "timeout_ms": 20000 }
// output
{ "session_id": "s-3f2a", "stdout": "...", "done": true, "exit_code": 0,
"is_pty": true, "reused": false, "truncated": false, "dropped_bytes": 0, "elapsed_ms": 412 }
```
超时未完成时 `done=false`、无 `exit_code`;`stdout` 是已产生的部分输出,**会话保留**,
用同一 `session_id` 轮询。`max_output_bytes`(1024..1048576,默认 65536)按行截断并置
`truncated`,剩余内容下次轮询取。
#### `terminal_close`
```jsonc
{ "id": "...", "session_id": "s-3f2a" } // 幂等:会话不存在也返回成功
```
#### `list_files`
```jsonc
{ "id": "...", "path": "C:\\ProgramData\\AssemblyManager", "limit": 100, "offset": 0 }
// output
{ "files": [ { "name": "settings.ini", "isDir": false, "size": 1204, "mtime": 1699999999 } ],
"total": 42, "totalAll": 42, "limit": 100, "offset": 0, "hasMore": false }
```
`path` 为空时返回盘符列表 `{ drives: [{ drive, typeName, fileSystem, totalMB, freeMB }] }`。
批量传 `ids` 时结果按台汇总在 `results` 里。注意返回数组字段是 `files`,不是 `entries`。
#### `read_file`
```jsonc
{ "id": "...", "path": "C:\\ProgramData\\AssemblyManager\\.env",
"offset": 0, "limit": 2000, "max_bytes": 262144, "encoding": "auto" }
// output
{ "path": "...", "size": 4096, "encoding": "utf-8", "eol": "lf",
"lines_total": 120, "offset": 0, "lines_returned": 120,
"text": "IR_ENDPOINT=...", "sha256": "...", "truncated": false }
```
**行语义**:`offset` 是起始行(0 基,负数表示末尾 N 行),`limit` 是行数(1..200000,默认
2000),`max_bytes` 是本次返回文本的字节上限(1024..2097152,默认 262144=256KB),
超出按行截断并置 `truncated`。`encoding`:`auto`(BOM → UTF-8 合法性 → GBK 回退)/
`utf-8` / `gbk` / `gb18030` / `latin1`;`eol` 为 `crlf/lf/cr/mixed/none`。
**整文件上限 2 MiB**(`YAMA_MCP_READ_MAX`):V2 下载没有区间参数,只能整文件拉,超过就拒绝
(`-32602`)。`offset`/`limit` 是下载后的窗口裁剪,绕不过这个门。
### 3.3 文本块(`content[].text`)
`structuredContent` 是权威数据,但部分 MCP 客户端只把 `content[].text` 交给模型,
`structuredContent` 不会出现在模型上下文里。因此列表类工具的文本块不能只有「共 N 台」
这样的汇总——主机 64 位 id 是 `read_file`、`get_host_detail`、`terminal_exec` 等后续调用
的寻址键,模型拿不到就等于工具不可用。
| 工具 | 汇总行之后 |
|---|---|
| `list_hosts` | 表头 `id name ip group os online clientType last_seen`,随后每台一行 |
| `get_host_detail` | 单台:主机 JSON(compact);批量:`id ok detail`,成功行是主机 JSON,失败行是错误信息 |
| `list_files` | 盘符 `drive typeName fileSystem totalMB freeMB`;目录 `name isDir size mtime` |
| `get_audit_log` | `time type msg`,`msg` 是去掉信封字段后的 compact JSON |
列用制表符分隔,首列一定是后续调用的寻址键(主机 id / 文件名)。单元格内的制表符与换行
替换成空格,精确值以 `structuredContent` 为准;空值显示 `-`。分页只渲染当前页,不会把
全表塞进文本块。
MFC 端不需要同样的改动:`McpInternal.cpp` 的 `BuildResult` 会把整个
`structuredContent` 作为**第二个** `type:"text"` 项追加到 `content`(除非 builder 用
`SetStructuredTextPayload` 指定了更小的载荷)。实测线上 `list_hosts` / `get_audit_log`
的 `content[1]` 已是完整 JSON(含主机 id),文本型客户端本来就能拿到。Go 的
`newToolResult` 只写一个 text 项,所以把行放进第一项。
---
## 4. 端点
### 4.1 `POST /mcp`
在 `web/server.go:126` 起的 mux 里加一行:
```go
mux.HandleFunc("/mcp", s.mcp.Handle)
```
**不能复用 `s.requireBearer`**:它校验的是浏览器会话令牌(`s.auth.ValidateToken`),
MCP 用的是独立的静态令牌,两套凭据语义不同。鉴权在 `mcp.Handle` 内部自己做
(§4.2)。`basePath` 由 `s.mount` 统一处理,`/mcp` 不需要自己感知前缀。
协议形态:
| 项 | 取值 |
|---|---|
| 协议版本 | `2025-06-18`(与 MFC `tools.json` 的 `protocolVersion` 一致) |
| 会话 | **无状态**。不生成、不校验 `Mcp-Session-Id` |
| `POST` 响应 | `Content-Type: application/json`,单条 JSON-RPC 响应 |
| `GET /mcp` | `405 Method Not Allowed`(v1 无服务端主动推送流;MCP 规范允许此返回) |
| `DELETE /mcp` | `405` |
| 批量请求 | 不支持(数组入参返回 `-32600`) |
| 通知(无 `id`) | 一律 `204 No Content`,不返回体 |
无状态的代价是**没有 `notifications/progress` / `notifications/cancelled`**。
取消靠 HTTP 请求断开——`r.Context()` 被取消时,处理函数释放设备锁、终端会话按
§6.6 处理(不销毁)。这与 MFC 的 `-32800 请求被取消` 语义对齐。
### 4.2 令牌
```
YAMA_MCP_TOKEN=<32 位十六进制> # 必填;未设置 = MCP 端点不注册(/mcp 返回 404)
YAMA_MCP_READONLY=1 # 可选,只读模式(隐藏 terminal_exec / terminal_close)
YAMA_MCP_TERM_IDLE=180 # 可选,终端会话空闲回收秒数
YAMA_MCP_MAX_CONCURRENCY=16 # 可选,全局并发上限
YAMA_MCP_READ_MAX=2097152 # 可选,read_file 文件大小门(字节,默认 2 MiB)
```
- 未设置时**不注册路由**,并在启动日志打一行 `MCP endpoint disabled: YAMA_MCP_TOKEN not set`。
不自动生成——生成的令牌若只落在日志里,等于没有密钥管理。
- 比较用 `subtle.ConstantTimeCompare`,长度不等直接失败(不 leak 长度)。
- principal 固定为 `{actor: "mcp", role: "admin"}`。审计记录里 `actor=mcp`,
`source=mcp`,与浏览器会话(`actor=<username>`)可区分。
- 不做失败计数封禁:令牌是 32 位十六进制(128 bit),且端点不对外暴露时无爆破面。
若将来暴露到公网,按 `web/ws_handlers.go` 的登录节流同款加计数(记入 §12 R6)。
### 4.3 错误码
与 MFC 完全对齐(`McpServer.cpp:296-312` 的官方说明),Go 侧只实现用得到的:
| 码 | 语义 | Go 侧触发点 |
|---:|---|---|
| `-32001` | 超时 | 等子连接/等响应超时;`done=false` 不算此码 |
| `-32002` | 主机离线或不存在 | `hub.IsOnline` 为假 |
| `-32003` | 主机忙 | 设备锁被占 / 终端槽位被浏览器持有 |
| `-32004` | 命令未送达 | `hub.SendToDevice` 返回错误 |
| `-32005` | 主机不支持该能力 | 缺 `CLIENT_CAP_SCREEN_PREVIEW`(截屏);非 PTY 客户端用 `terminal_exec` |
| `-32006` | 策略拒绝 | 只读模式下调用写工具 |
| `-32009` | 目标不存在 | `list_files` 的 `TOKEN_FILE_LIST_ERROR` 且 win32err∈{2,3} |
| `-32010` | 权限不足 | `TOKEN_FILE_LIST_ERROR` 且 win32err=5 |
| `-32602` | 参数错误 | schema 校验失败 |
| `-32601` | 方法不存在 | 未知 method / 未知工具名 |
| `-32000` | 内部错误 | 其余 |
### 4.4 审计
每次 `tools/call` 产出一条记录,字段沿用 `web/audit.go` 的形状:
```
event=mcp.tool.call actor=mcp role=admin source=mcp
tool=<name> device=<id|-> ok=<bool> code=<err|0> ms=<duration>
args=<截断到 512 字节的摘要> result=<ok 时的体积摘要 / 失败时的 message>
```
`args` 里的敏感值(`command` 全文可能含密码)**不入审计**——只记命令首词与长度,
与 MFC 的做法一致(MFC 审计只记 `host <id> <tool>`)。完整命令进 `debug` 级日志。
---
## 5. 四条设备通道
```
MCP client ──HTTP POST /mcp──▶ mcp.Server
├─ 本机:hub.ListDevices / devicehistory / audit_query
├─ 主连接 RPC SendToDevice(247) ─────────▶ 设备主连接
├─ 终端 OpenTerminalSession ───────▶ 终端子连接
├─ 文件管理器 COMMAND_LIST_DRIVE(1) ─────▶ 文件管理器子连接
└─ V2 CMD_DOWN_FILES_V2(94) ─────▶ V2 流式子连接
```
### 5.1 主连接 RPC(`get_screenshot`)
请求走 `hub.SendToDevice(deviceID, pkt)`,响应在 `cmd/main.go` 的 `OnReceive`
里按 `data[0] == TOKEN_SCREEN_PREVIEW_RSP` 分派。**不走子连接,不占任何槽位。**
需要一个请求表:
```go
type pendingRPC struct {
reqID uint16
ch chan []byte // 缓冲 1,迟到的响应写不进去就丢弃
}
m := map[uint64]*pendingRPC{} // key = deviceID(每设备同时只允许一个,与设备锁一致)
```
`reqID` 用 `atomic.Uint32` 自增后取低 16 位;**必须校验响应里的 `reqId` 与在途请求一致**,
否则丢弃——MFC 的 `TakePreviewResponse(devId, reqId, ...)` 就是干这个的
(`2015RemoteDlg.cpp:7520`),原因是主连接上可能同时有别的预览在飞。
### 5.2 终端子连接(`terminal_exec` / `terminal_close`)
完全复用 `hub` 现有设施,**不改 hub**:
| 动作 | 调用 |
|---|---|
| 开会话 | `hub.OpenTerminalSession(deviceID)`;已存在返回 `ErrTerminalBusy` |
| 等就绪 | 订阅 `EventHandler.OnTerminalReady(deviceID, isPTY)` |
| 发输入 | `hub.SendToTerminal(deviceID, bytes)`;行尾按 §6.4 区分 `\n` / `\r\n` |
| 收输出 | 订阅 `EventHandler.OnTerminalData(deviceID, packet)`,剥掉 4 字节 `TRM1` 前缀 |
| 关会话 | `hub.CloseTerminalSession(deviceID)` |
`mcp.Server` 在启动时 `hub.Subscribe(self)` 一次,作为常驻订阅者;
只有"当前有 MCP 终端会话的设备"才把数据写进环形缓冲,其余直接丢弃(零开销)。
### 5.3 文件管理器子连接(`list_files`)
时序:
```
MCP ──▶ 主连接: COMMAND_LIST_DRIVE(1) [1 字节]
客户端 ──▶ 新子连接(EnableSubConnAuth)
└─ TOKEN_CONN_AUTH(246) ──▶ Go: 校验 + 把 clientID 钉在 ctx 上 + 回 ack
└─ TOKEN_DRIVE_LIST(103) ──▶ Go: 解析盘符(子连接保持打开)
MCP ──▶ 同一子连接: COMMAND_LIST_FILES(2) [cmd][path\0]
└─ TOKEN_FILE_LIST(104) ──▶ Go: 解析目录项
或 TOKEN_FILE_LIST_ERROR(171) ──▶ Go: 按 win32err 翻译
└─ Go: 关子连接(COMMAND_BYE → 500ms → Close)
```
注意 `TOKEN_DRIVE_LIST` 到达后**不能立刻关子连接**——列目录还要在同一个子连接上发
`COMMAND_LIST_FILES`。MFC 的注释写得很明确:*此时不关子链接,交给 TOKEN_FILE_LIST
分支收尾*(`2015RemoteDlg.cpp:7647`)。
关键点:
- **子连接带 ConnAuth**(`client/KernelManager.cpp:1773` 对 `COMMAND_LIST_DRIVE`
调了 `EnableSubConnAuth()`),所以 `handleConnAuth` 已把 `ClientID` 钉在 ctx 上,
Go **不需要** MFC 那套 `IsPending(devId)` 守卫。按 `ctx.GetInfo().ClientID` 路由即可。
- 子连接由客户端创建、**由服务端关闭**(MFC 注释:*此时不关子链接,交给
TOKEN_FILE_LIST 分支收尾*)。关闭用 `hub` 同款优雅关闭:发 `COMMAND_BYE(204)`,
500 ms 后 `ctx.Close()`。
- `TOKEN_DRIVE_LIST` 与 `TOKEN_FILE_LIST` 的记录格式见附录 A,直接照 MFC 的
`ParseDriveList` / `ParseFileList`(`McpServer.cpp:506/548`)移植。
- 文件名是**客户端 ANSI**,用 `protocol.DecodeClientString(data, hub.Capability(id), "")` 解码。
### 5.4 V2 流式子连接(`read_file`)
时序:
```
MCP ──▶ 主连接: COMMAND_LIST_DRIVE(1)
└─ 文件管理器子连接建立(同 §5.3)
MCP ──▶ 文件管理器子连接: CMD_DOWN_FILES_V2(94) [cmd][targetDir\0][path\0][\0]
└─ 服务端关掉文件管理器子连接
客户端 ──▶ 新子连接(EnableSubConnAuth)
└─ COMMAND_SEND_FILE_V2(85) × N ──▶ Go: 校验路径 → 落盘
└─ COMMAND_FILE_COMPLETE_V2(91) ──▶ Go: 校验 SHA-256 → 完成
MCP: 读临时文件 → 返回 → 删临时目录
```
- `targetDir` 是**主控本机**的保存目录,由服务端指定;客户端把它拼进每个 chunk 的
`filename` 回填。所以服务端必须用一个**每次请求新建的临时目录**
(`os.MkdirTemp("", "yama-mcp-read-*")`),并在 `defer` 里 `RemoveAll`。
- **路径校验是硬性安全要求**:`filename` 由客户端提供,必须校验它落在 `targetDir` 之内
(**用 `filepath.Rel` 判越界,不能用字符串前缀比较**,见 §8.3),否则拒收并中止传输。
没有这一步,被控端可以把任意文件写到主控磁盘任意位置。
- **能力检查只作诊断兜底**。`CLIENT_CAP_V2` 在 `common/commands.h:1289` 的
`DefaultCaps()` 里被**所有现代客户端无条件声明**,拿它做真门等于没门。Go 侧保留
`SupportsCap(…, CLIENT_CAP_V2)` 检查的唯一作用,是让"能力串为空"的极老客户端直接
得到 `-32005`,而不是等到 94 号命令静默超时(见下一条)。MFC 侧的 V2 是**服务端
开关**(`2015RemoteDlg.cpp:2822` 的 `EnableFileV2`,默认关),不是客户端能力;
Go 侧不搬这个开关,恒用 V2。
- 真正的失败模式是**老客户端不认识 94 号命令**:它收到 `CMD_DOWN_FILES_V2` 后
不建子连接、不回任何包,表现为 `-32001` 超时。工具描述里要写明这条,
避免模型反复重试。
---
## 6. 终端会话
### 6.1 会话对象
```go
type termSession struct {
id string // "s-" + 6 位 hex
deviceID string
isPTY bool
createdAt time.Time
lastUsed time.Time
mu sync.Mutex
buf []byte // 环形,cap 256 KiB
base uint64 // buf[0] 的绝对偏移
total uint64 // 累计写入字节
delivered uint64 // 已交付给客户端的绝对偏移
pending *pendingCmd // 在途命令;nil = 空闲
}
type pendingCmd struct {
sentinel string
deadline time.Time
done bool
exitCode int
raw []byte // 从 sentinel 之前回切出的原始片段
}
```
### 6.2 租约与争用
- `hub.OpenTerminalSession` 本身就是互斥(`ErrTerminalBusy`),MCP 直接复用它。
- 撞上 `ErrTerminalBusy` → `-32003`,message 写
`terminal busy: another viewer (web console or another MCP call) holds it; retry later`。
- **v1 不做抢占**。理由:抢占会把正在敲命令的人踢下线,而模型无法判断"人是不是在忙"。
需要抢占时由运维在 Web 控制台关掉那个终端。
- 空闲释放:`lastUsed` 超过 `YAMA_MCP_TERM_IDLE`(默认 180 s)由后台 ticker 调
`CloseTerminalSession`。这是防止模型忘了 `terminal_close` 把人的终端锁死。
### 6.3 环形缓冲与游标
- 容量 256 KiB,超出丢弃最旧数据,`base` 前移,丢弃量记 `droppedBytes` 并在
返回体里体现(`truncated=true`)。
- 绝对偏移 `total` 单调递增,`offset` 参数与返回里的 `offset` 都用绝对偏移。
- 缓冲随会话存在:会话关闭(`terminal_close` / 空闲回收 / 设备掉线)时整体释放。
### 6.4 哨兵与退出码
沿用 MFC 的两种形态(`McpServer.cpp:3991-3998`),**必须分两行下发**:
| 客户端 | 下发 | 哨兵 |
|---|---|---|
| POSIX PTY(Linux/Android) | `cmd\n` + `echo "__MCP_DONE_<id>__$?"\n` | `__MCP_DONE_<id>__<n>` |
| ConPTY(新 Windows) | `cmd\r\n` + `echo __MCP_DONE_<id>__%errorlevel%\r\n` | 同上 |
为什么要分两行:`rem` / `cmd` / `exit` / `if` / `for` 这类"吞行"命令会把同一行后面的
内容一起吞掉(MFC 的 P1 教训)。分两行后哨兵独立执行,退出码才可信。
`<id>` 用 6 位随机 hex,每次命令重新生成——避免上一条命令的输出里残留同名哨兵被误命中。
### 6.5 输出清洗
三段清洗,顺序不能变(MFC `McpServer.cpp:3946-4040`):
1. **剥回显**:PTY 会把输入整行回显。删掉命令行本身与哨兵行。
2. **剥 ANSI**:`\x1b[...m`、`\x1b[?25h/l` 等 CSI/OSC 序列。
3. **剥哨兵**:把哨兵文本及其后的退出码切掉,`exit_code` 单独解析。
ConPTY 是"屏幕渲染流"而不是字节流,光标重绘会让同一行出现两次,剥完 VT 后
文字会重复(MFC 实测 `rem hello` 只剩哨兵、`cmd /c echo abc` 变成
`abc__MCP_DONE_x__0`)。**这三段必须整体移植,不能自己重写**——这是踩过坑的代码。
### 6.6 轮询模式
`terminal_exec` 不带 `command`、只带 `session_id` 时进入轮询:从 `delivered` 开始
取增量,等到 `done` 或超时。
- 超时**不销毁会话**(MFC 优化的核心结论):命令可能还在跑,销毁等于毁掉现场
(cwd、环境变量、后台任务)。MFC 在优化前两次 `-32002` 都是这么来的。
- HTTP 请求被客户端断开(`r.Context()` done)时同样只标记放弃,不动会话。
- 会话内已有在途命令时,再带 `command` 调用 → `-32003`(同一会话单命令)。
### 6.7 平台范围
**v1 只支持 PTY 客户端**(ConPTY / POSIX PTY)。老的非 PTY cmd-pipe 路径
(`TOKEN_SHELL_START(128)`)在 `OnTerminalReady` 里能识别(`isPTY=false`),
此时 `terminal_exec` 直接返回 `-32005` 并在 message 里说明"该客户端版本不支持"。
理由:非 PTY 路径的回显跳过依赖"按写入长度跳过",且单行哨兵会被吞行命令吃掉,
Go 侧没有实测数据支撑,先不开放比做错好。
若客户端根本不支持 shell(`COMMAND_SHELL` 发出后迟迟没有子连接),
`OpenTerminalSession` 会一直停在 pending,表现为 `-32001` 超时。这里**不设能力门**——
`CLIENT_CAP_TERMINAL` 只有新版 Android 声明,Windows/Linux 一直支持却不声明
(`common/commands.h:151` 的注释),拿它做门会误拒所有桌面客户端。message 里加一句
"若反复超时,可能该客户端版本不支持远程 shell"。
---
## 7. `get_screenshot`
### 7.1 为什么不用屏幕流
屏幕流是 H.264:`TOKEN_FIRSTSCREEN(116)` 是裸 BGRA 首帧,之后全是
`TOKEN_NEXTSCREEN(117)` / `TOKEN_KEYFRAME(134)` 的编码帧。**不采用首帧方案**,原因不是
解码(首帧本来就是裸的),而是**代价**:拿首帧必须先发 `COMMAND_SCREEN_SPY` 建立屏幕
子连接、等客户端绑定、等首帧到达,用完还要拆——它占着每设备唯一的屏幕会话槽位,
和正在看画面的人直接冲突,而且拆不干净就会一直推流。
`COMMAND_SCREEN_PREVIEW_REQ(247)` 是**主连接 RPC**:客户端自己抓屏、自己缩放、
自己编码 JPEG 回包(`TOKEN_SCREEN_PREVIEW_RSP(248)`),不建子连接、不占槽位、
一次请求一次响应。这是 MFC `get_screenshot` 的既有实现
(`McpServer.cpp:2199`、`2015RemoteDlg.cpp:10449`),Go 照做即可。
### 7.2 请求 / 响应
```c
struct ScreenPreviewReq { // 8 字节
uint8_t cmd; // 247
uint16_t reqId;
uint16_t maxWidth;
uint8_t jpegQuality; // 1..100
uint16_t reserved;
};
struct ScreenPreviewRspHeader { // 16 字节
uint8_t token; // 248
uint16_t reqId;
uint8_t status; // 0=OK 1=抓屏失败 2=编码失败 3=不支持 4=目标无效
uint8_t format; // 0=JPEG 3=BGRX
uint16_t width, height;
uint32_t bytes;
uint8_t reserved[3];
// 后接 data[bytes],可选再跟 ScreenCaptureMeta
};
```
v1 只发 8 字节基础请求(等价于整虚拟桌面),**不发 v2 扩展**——`region/window/monitor`
需要 `CLIENT_CAP_SCREEN_REGION`,属后续增强。
参数映射:`max_width` 钳制到 `[64, 1920]`,缺省/0 时 Go v1 固定 1024;`jpegQuality` 固定 80。
### 7.3 BGRX → JPEG
Linux 客户端没有 JPEG 编码库,回 `format=3`(BGRX,自上而下逐行、每像素 4 字节
`B,G,R,X`,无行填充,`bytes == width*height*4`)。Go 用标准库转:
```go
img := image.NewRGBA(image.Rect(0, 0, w, h))
for i := 0; i < w*h; i++ {
img.Pix[i*4+0] = src[i*4+2] // R ← B
img.Pix[i*4+1] = src[i*4+1] // G
img.Pix[i*4+2] = src[i*4+0] // B ← R
img.Pix[i*4+3] = 0xFF
}
jpeg.Encode(&buf, img, &jpeg.Options{Quality: 80})
```
`bytes != w*h*4` 时按畸形包丢弃(返回 `-32000`)。
### 7.4 能力门与超时
- 缺 `CLIENT_CAP_SCREEN_PREVIEW(0x0004)` → `-32005`。
MFC 同款门(描述里写明"老客户端返回 -32005")。
- 超时 8 s。**不做取消**:MFC 明确写了"屏幕预览 = 主连接 RPC,不能 CancelIO"
(`2015RemoteDlg.cpp:7514`)。超时后把请求表项删掉,迟到的响应按 `reqId` 不匹配丢弃。
- 响应 `status != 0` 时按码翻译:1/2 → `-32000`(带 status 文案),3 → `-32005`,
4 → `-32602`。
---
## 8. 文件工具
### 8.1 `list_files`
见 §5.3。解析细节:
- `TOKEN_DRIVE_LIST`:`[token][letter:1][type:1][totalMB:4][freeMB:4][typeName\0][fileSystem\0]` 循环,
`letter=='\0'` 终止。
- `TOKEN_FILE_LIST`:`[token]([attr:1][name\0][sizeHigh:4][sizeLow:4][ftLow:4][ftHigh:4])*`,
空名终止(尾部零填充)。`attr & 0x10` 为目录。
- `TOKEN_FILE_LIST_ERROR`:`[token][win32err:4 LE]`,按 §4.3 映射。这是**新客户端**才有的
失败回执;老客户端路径不存在时直接不回包,表现为 `-32001` 超时(message 里要提示
"路径可能不存在,先用 list_files 确认")。
`total` 与本次返回条数分开:客户端一次返回全部,服务端做 `limit`/`offset` 窗口裁剪并在
`structuredContent` 里如实给出 `total`/`totalAll`/`hasMore`(与 MFC 的分页语义一致)。
### 8.2 `read_file`
见 §5.4。落盘完成后:
1. 校验 SHA-256(`COMMAND_FILE_COMPLETE_V2` 里带的 32 字节)。
2. 按 `encoding` 解码全文(`auto`:BOM → 严格 UTF-8 → GBK 回退;`gb18030`/`latin1` 显式指定)。
3. 按行切分,按 `offset`(0 基,负数=末尾 N 行)/`limit`/`max_bytes` 取窗口;`max_bytes`
按行边界截断,避免切坏 UTF-8/GBK 多字节字符。
4. 返回 `text` + `size` + `encoding` + `eol` + `lines_total` + `offset` + `lines_returned` +
`truncated` + `sha256`。
5. `defer os.RemoveAll(tmpDir)`。
**大小门**:`CMD_DOWN_FILES_V2` **没有区间参数,只能整文件下载**,所以大小门必须卡在
下载前——在首个 `COMMAND_SEND_FILE_V2` chunk 里读 `fileSize`,超过
`YAMA_MCP_READ_MAX`(默认 2 MiB,与 MFC 的 `kReadFileSizeGate` 一致)立即中止传输、
删临时目录、返回 `-32602`,message 说明"文件超过 2 MiB,本工具不支持"。不要先落盘
200 MB 再报错。
`offset` / `limit` 是**下载完成之后**对返回窗口的裁剪(`limit` 默认 256 KiB、
上限 4 MiB),不能用来绕过大小门——大文件在 Go 侧目前无解,这是协议限制,
工具描述里要写明。
### 8.3 路径校验(安全,必读)
V2 的 `filename` 由客户端提供。必须:
```go
clean := filepath.Clean(filepath.Join(targetDir, filepath.FromSlash(name)))
rel, err := filepath.Rel(targetDir, clean)
if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(os.PathSeparator)) {
abortTransfer() // 拒收并中止
}
```
`filepath.HasPrefix` 字符串前缀比较不够——`/tmp/ab` 会匹配 `/tmp/abc`。用 `filepath.Rel` 判越界。
同理 `list_files` 的 `path` 与 `read_file` 的 `path` 不做本地校验(它们在远端),
但**不允许包含 NUL 与换行**——那会截断/拆开 C 字符串协议字段。
---
## 9. 并发、配额、生命周期
| 项 | 规则 |
|---|---|
| 每设备单请求 | `map[deviceID]*sync.Mutex` 的 `TryLock`;占用返回 `-32003`,message 带占用工具名与已持续时长 |
| 全局并发 | `YAMA_MCP_MAX_CONCURRENCY`(默认 16)信号量;超出直接 `-32003` |
| 单次请求上限 | `terminal_exec` 120 s,`read_file` 120 s,`get_screenshot` 8 s,其余 10 s |
| 设备锁释放 | `defer` 释放;HTTP ctx 取消也走同一条 defer |
| 终端空闲回收 | ticker 30 s 扫一次,`lastUsed` 超 180 s 关闭 |
| 进程退出 | `mcp.Server.Close()` 关闭所有终端会话(避免留下孤儿 shell 子连接) |
设备锁的粒度是"整台设备"而不是"每通道",与 MFC 一致(`-32003` 说明里写明
"列表、截屏、文件、管理动作共用这一道锁")。理由是主连接 RPC 与子连接命令
在客户端侧可能共用同一份状态,并发只会让现场更难读。
---
## 10. 代码结构与依赖方向
```
server/go/mcp/
server.go # /mcp handler、JSON-RPC 分发、鉴权、tools/list
tools.go # //go:embed tools_minimal.json;只读过滤、工具表
tools_minimal.json # gen_go_tools.py 从 mcp/tools.json 抽取的 9 个工具(勿手改)
tools_local.go # list_hosts / get_host_detail / get_server_status / get_audit_log
tools_term.go # terminal_exec / terminal_close
errors.go # 错误码 + JSON-RPC 错误映射
audit.go # mcp.tool.call 审计
lock.go # 设备锁 + 全局信号量
session.go # 终端会话表、空闲回收
term.go # 哨兵、环形缓冲
clean.go # 终端输出清洗(逐字节移植 MFC 的 CleanTerminalOutput)
screen.go # 主连接预览 RPC
filemgr.go # 文件管理器子连接(list_files)
filev2.go # V2 流式接收端(read_file)
```
依赖方向(无环):
```
cmd/main.go ──▶ web ──▶ mcp ──▶ hub ──▶ connection / protocol
│ └──▶ devicehistory
└──▶ wsauth
```
- `mcp` 只 import `hub` / `protocol` / `devicehistory` / `logger`,**不 import `web`**。
- **构造顺序**:`mcp.Server` 在 `cmd/main.go` 里先建,再分别注入两侧——
`web.New(...).WithMCP(mcpSrv)`(沿用 `WithDeviceHistory` / `WithConfig` 的链式风格,
`web/server.go:94`),以及 `MyHandler.mcp = mcpSrv`(TCP 分派侧)。
这样 `web` 和 `cmd` 都只依赖 `mcp`,不存在 `mcp → web` 的反向依赖。
- TCP 侧的分派(`cmd/main.go` 的 `OnReceive`)按到达的连接分成三组,未命中在途请求就丢弃:
- `mcp.Server.OnPacket`:`TokenScreenPreviewRsp(248)`(主连接上的截图 RPC 回包)
- `mcp.Server.OnFilePacket`:`TokenDriveList(103)` / `TokenFileList(104)` /
`TokenFileListError(171)`(文件管理器子连接)
- `mcp.Server.OnTransferPacket`:`CommandSendFileV2(85)` / `CommandFileCompleteV2(91)`
(独立数据子连接或 POSIX 的文件管理器子连接)与 `TokenDownloadError(173)`
**为什么 embed 一份生成的 `tools_minimal.json`、而不是手写或直接引用 `mcp/tools.json`**:
`mcp/tools.json` 在仓库根,`//go:embed` 不能引用父目录;手写 9 个 schema 又无法证明
与 MFC 的 JSON 一致。所以由 `tools/mcp_tools/gen_go_tools.py` 从 `mcp/tools.json` 原样
抽取(保持顺序,只留 name/description/inputSchema/outputSchema)生成 go 包内的副本并
嵌入二进制——改工具定义必须改 `mcp/tools.json` 再重新生成,不存在两份手写文字漂移的余地。
两道防漂移检查:`gen_go_tools.py --check`(生成副本是否为最新)与
`verify_tools.py --subset`(线上 `tools/list` 是否与 `mcp/tools.json` 同名工具逐字段
一致、名字集合是否恰好 9 个/只读 7 个)。
---
## 11. 施工顺序与验收
| 序 | 内容 | 依赖 | 可独立验收 |
|---:|---|---|---|
| 1 | `mcp` 包骨架 + `/mcp` + 鉴权 + `initialize`/`ping`/`tools/list` | — | ✅ `curl` 打通 |
| 2 | 4 个本机只读工具(`list_hosts`/`get_host_detail`/`get_server_status`/`get_audit_log`) | 1 | ✅ 不碰设备即可测 |
| 3 | 设备锁 + 全局信号量 + 审计 | 1 | ✅ |
| 4 | 终端会话表 + 订阅 + 环形缓冲 | 3 | ✅ 浏览器开终端时能观察到缓冲 |
| 5 | 哨兵 + 输出清洗 + `terminal_exec` 执行/轮询 | 4 | ✅ 对照 MFC 同款命令的输出现象 |
| 6 | `terminal_close` + 空闲回收 | 5 | ✅ |
| 7 | 主连接 RPC 请求表 + `get_screenshot` | 3 | ✅ |
| 8 | 文件管理器子连接 + `list_files` | 3 | ✅ |
| 9 | V2 接收端 + `read_file` + 路径校验 | 8 | ✅ |
| 10 | `verify_tools.py --subset` | 1 | ✅ |
**整体验收**(用同一套 ASM 工位任务重跑):
- 9 个工具全部可调用,`tools/list` 响应 < 24 KB(无 outputSchema 的直接收益)
- `terminal_exec` 连续 20 条命令零失败;超时后轮询能取回完整输出
- 浏览器开着终端时 `terminal_exec` 返回 `-32003` 而不是把人的会话踢掉
- `read_file` 读 `.env`(含单引号、CRLF)字节级一致,SHA-256 与远端 `sha256sum` 相同
- `get_screenshot` 在 Windows / Linux 各出一张图,Linux 走 BGRX→JPEG 分支
- 审计里每次调用一条 `mcp.tool.call`,`device`/`tool`/`code`/`ms` 齐全
---
## 12. 风险与未决
| # | 风险 | 影响 | 处置 |
|---:|---|---|---|
| R1 | 哨兵清洗移植不完整 | 输出带垃圾/退出码错 | 按 MFC 三段顺序整体移植,用 MFC 记录的实测样例做 Go 单测(`rem hello`、`cmd /c echo abc`、`type .env`) |
| R2 | 终端槽位被 MCP 长期占用 | 人用不了终端 | 空闲 180 s 回收 + `-32003` 明确告知 + 工具描述写明 |
| R3 | 老客户端不认识 `CMD_DOWN_FILES_V2(94)` | `read_file` 静默超时 | 工具描述写明"超时可能是不支持 V2 的旧客户端";§5.4 |
| R4 | 老客户端缺 `CLIENT_CAP_UTF8` | 文件名 GBK 解码 | 新客户端 `DefaultCaps()` 恒带此位(`commands.h:1289`),只有很老的客户端会缺;与既有 `activeWindow` 路径同源,后续在 `hub.DeviceInfo` 暴露 `clientType` 后一并修 |
| R5 | 非 PTY 老客户端 | 无法用 `terminal_exec` | v1 明确 `-32005`,描述里说明 |
| R6 | 多用户 / 分组授权缺失 | 所有 MCP 调用都是 admin | v1 明确单 principal;多租户部署前必须补 token 表 + `allowedGroups` 校验 |
| R7 | 无 `notifications/progress` | 长任务(`read_file` 大文件)模型以为卡死 | 工具描述写明预期耗时;v2 再上 SSE |
| R8 | `read_file` 只能整文件下载,2 MiB 封顶 | 读大日志无解 | 与 MFC 同款限制(`kReadFileSizeGate`)。绕法是 `terminal_exec` + `tail`,工具描述里给出这个替代路径 |
---
## 附录 A:协议速查
| 名称 | 值 | 方向 | 载荷 |
|---|---:|---|---|
| `COMMAND_LIST_DRIVE` | 1 | S→C 主连接 | `[cmd]` |
| `COMMAND_LIST_FILES` | 2 | S→C 文件子连接 | `[cmd][path\0]` |
| `COMMAND_SCREEN_SPY` | 16 | S→C 主连接 | `[cmd]` |
| `COMMAND_BYE` | 204 | S→C 任意 | `[cmd]` |
| `COMMAND_SCREEN_PREVIEW_REQ` | 247 | S→C 主连接 | `ScreenPreviewReq`(8B) |
| `COMMAND_SEND_FILE_V2` | 85 | C→S V2 子连接 | `FileChunkPacketV2`(77B)+ name + data |
| `COMMAND_FILE_COMPLETE_V2` | 91 | C→S V2 子连接 | `FileCompletePacketV2`(69B) |
| `CMD_DOWN_FILES_V2` | 94 | S→C 文件子连接 | `[cmd][targetDir\0][path\0][\0]` |
| `TOKEN_DRIVE_LIST` | 103 | C→S 文件子连接 | `[token]` + 盘符记录 |
| `TOKEN_FILE_LIST` | 104 | C→S 文件子连接 | `[token]` + 文件记录 |
| `TOKEN_FILE_LIST_ERROR` | 171 | C→S 文件子连接 | `[token][win32err:4 LE]` |
| `TOKEN_CONN_AUTH` | 246 | C→S 子连接 | `ConnAuthPacket`(512B) |
| `TOKEN_SCREEN_PREVIEW_RSP` | 248 | C→S 主连接 | `ScreenPreviewRspHeader`(16B)+ data |
`FileChunkPacketV2` 字段:`cmd(1) transferID(8) srcClientID(8) dstClientID(8)
fileIndex(4) totalFiles(4) fileSize(8) offset(8) dataLength(8) nameLength(8)
flags(2) checksum(2) reserved(8)` = 77 字节。
---
## 附录 B:自审记录
写完初稿后按"每个结论都必须能在代码里指到行"重核了一遍,发现并修掉以下问题:
| # | 问题 | 处置 |
|---:|---|---|
| 1 | 初稿写"文件管理器子连接不带 ConnAuth,需要 pending 标记",照搬了 MFC 的做法 | **错**。`client/KernelManager.cpp:1773` 对 `COMMAND_LIST_DRIVE` 调了 `EnableSubConnAuth()`,Go 的 `handleConnAuth` 已把 clientID 钉在 ctx 上。改为按 clientID 路由,删掉 pending 方案,省掉一个 hub 改动 |
| 2 | 初稿把 `get_screenshot` 设计成"抓 `TOKEN_FIRSTSCREEN` 原始帧" | **改**。`TOKEN_FIRSTSCREEN` 虽注释为 raw BGRA,但它依附于屏幕会话(占槽位、要建子连接)。改用 `COMMAND_SCREEN_PREVIEW_REQ` 主连接 RPC——与 MFC 一致,不占任何槽位 |
| 3 | 初稿写"终端槽位需要给 hub 加 owner 字段" | **简化**。`hub.OpenTerminalSession` 的 `ErrTerminalBusy` 本身就是互斥,v1 不抢占就不需要 owner。删掉 hub 改动,v1 对 `hub` **零改动** |
| 4 | 初稿写 `read_file` 用 `filepath.HasPrefix` 校验路径 | **错**。字符串前缀会让 `/tmp/ab` 匹配 `/tmp/abc`。改为 `filepath.Rel` 判越界 |
| 5 | 初稿漏了非 PTY 客户端的处理 | **补** §6.7:v1 明确 `-32005`,不做半吊子支持 |
| 6 | 初稿写"审计记录完整 command" | **改**。命令全文可能含密码,改为只记首词与长度,全文进 debug 日志 |
| 7 | 初稿的 `list_files` 没写 `total` 与 `returned` 的区别 | **补** §8.1,避免模型把截断当成"目录里只有这么多" |
| 8 | 初稿写"`terminal_exec` 的 reqId 用时间戳" | **改**。时间戳在并发下会撞;改 `atomic.Uint32` 取低 16 位,并**必须**校验响应 reqId(MFC `TakePreviewResponse` 同款) |
| 9 | 初稿把 `get_screenshot` 的 `max_width` 固定 1600 | **改** 为可传,钳制 `[320,3840]`,与 MFC 的 `max_width` 参数对齐 |
| 10 | 初稿没写"客户端 V2 开关关闭会静默超时" | **改**。核查后发现 V2 开关是**服务端**的(`2015RemoteDlg.cpp:2822` `EnableFileV2`,默认关),不是客户端。且 `CLIENT_CAP_V2` 在 `DefaultCaps()` 里全平台无条件声明,做门等于没门。改为"无能力门 + 老客户端不认识 94 号命令会静默超时",见 §5.4 |
| 11 | 初稿把 `read_file` 的能力门写成 `CLIENT_CAP_V2` | **删**。同 #10,该位恒为真。表格与 §5.4 一并改 |
| 12 | 初稿写 `/mcp` 用 `s.requireBearer` 包一层 | **错**。`requireBearer` 校验的是浏览器会话令牌(`web/server.go:269` 的 `s.auth.ValidateToken`),MCP 静态令牌过不去。改为 `mux.HandleFunc("/mcp", s.mcp.Handle)`,鉴权在 handler 内做 |
| 13 | 初稿写"`mcp` 在 `web.Start()` 里构造" | **错**。TCP 侧 `cmd/main.go` 的 `OnReceive` 也要把包转给 `mcp`,两边需要同一实例。改为在 `cmd/main.go` 先建,再 `web.New(...).WithMCP(srv)` + `MyHandler.mcp = srv` |
| 14 | 初稿写"非 PTY 客户端 `-32005`",但没说"根本不支持 shell 的客户端怎么办" | **补** §6.7:不设能力门(`CLIENT_CAP_TERMINAL` 只有 Android 声明),走 `-32001` 超时 + message 提示 |
| 15 | §5.3 时序图自相矛盾:`TOKEN_DRIVE_LIST` 后写"关子连接",下一行又写"同一子连接"发 `COMMAND_LIST_FILES` | **改**。列目录必须复用同一个子连接(`2015RemoteDlg.cpp:7647` 的注释),改为"保持打开,`TOKEN_FILE_LIST` 分支收尾" |
| 16 | §5.4 仍写 `filepath.HasPrefix` 校验路径,与 §8.3 自相矛盾 | **改**。统一指向 §8.3 的 `filepath.Rel` 判越界 |
| 17 | §7.1 说"屏幕流全是 H.264",据此否掉首帧方案 | **错两处**:首帧 `TOKEN_FIRSTSCREEN` 本来就是裸 BGRA,不需要解码;否掉它的真正理由是**要建屏幕子连接、占唯一槽位、还要拆**。改为按代价论证 |
| 18 | §8.2 建议大文件"直接用 `download_file`" | **错**。`download_file` 在 v1 不做(§1.2),不能建议一个不存在的工具。改为"卡在下载前的大小门 + 用 `terminal_exec` 兜底" |
| 19 | §8.2 只说"`limit` 上限 4 MiB",没意识到 V2 是整文件下载 | **补**。`CMD_DOWN_FILES_V2` 无区间参数,大小门必须卡在首个 chunk 的 `fileSize` 上(2 MiB,与 MFC `kReadFileSizeGate` 一致),否则会先落盘再报错 |
| 20 | §3.2 `get_server_status` 返回 `version`/`commit`,但 Go 侧没有这两个变量 | **补**。`cmd/main.go` 查不到版本常量,需新增 `var version, commit string` + Makefile `-X` 注入;拿不到返回空串 |
| 21 | §3.2 `get_host_detail.capabilities` 里列了 `v2` | **删**。该位全平台恒真(同 #10),列出来误导模型。换成 `utf8`/`screen_preview`/`screen_region`/`window_info` |
| 22 | §5.2 写死 `SendToTerminal(cmd+"\n")`,与 §6.4 的 ConPTY `\r\n` 冲突 | **改** 为按平台分行尾 |
| 23 | §3.2 的输入/输出形状是自造结构,与 `mcp/tools.json` 不一致(`online_only`、`entries`、`since`、`bytes_read`、`output`、capabilities 下划线命名、`max_width` 1600/[320,3840]) | **改**。已确认 `mcp/tools.json` 是唯一契约,§3.2 按 `inputSchema`/`outputSchema` 重写:`list_files` 返回 `files`、`read_file` 为行语义、审计无 `since`、capabilities 用 camelCase、`max_width` 钳制 `[64,1920]` 默认 1024;M1 起 `tools/list` 原样回显该 schema |
**结论**:以上 23 处已全部修入正文,无遗留。v1 对 `server/go` 的改动是
**新增 `mcp` 包 + `web/server.go` 一行路由 + `web.Server` 一个 `WithMCP` + `cmd/main.go` 六个 case + `protocol` 六个常量 + 两个版本变量**,
`hub` 零改动。
+545
View File
@@ -0,0 +1,545 @@
# Go 服务端 MCP 实施计划
> 版本:v1(草稿,待评审) 日期:2026-11-12
>
> 依据:`docs/Mcp_Go_Minimal_Design.md` v1.0(下称"设计文档")。
> 本文只回答**怎么施工**:顺序、改动面、完成定义、验证手段、提交边界。
> 设计取舍一律以设计文档为准,本文不重复论证;与设计文档不一致的地方在 §1 单列。
>
> 工作方式:沿用本项目既有节奏——**做一段、验一段、审一段、提交一段**,每段一个可独立
> 回滚的提交。Go 侧提交前缀用仓库既有约定 `Feature(Go):` / `Fix(Go):`。
---
## 0. 交付面与总量
| 类别 | 内容 | 规模 |
|---|---|---:|
| 新包 | `server/go/mcp/`(server / tools / errors / audit / lock / session / term / screen / filemgr / filev2) | ≈2,300 行(含测试 ≈900) |
| 抽包 | `server/go/auditquery/`(从 `web/audit_query.go` 提出查询器,见 §1.1) | ≈180 行搬移 |
| 接线 | `web/server.go`(`WithMCP` + 一行路由)、`cmd/main.go`(构造/注入/六个 case/版本变量)、`protocol/commands.go`(常量)、`build.ps1` + `Makefile`(`-X` 注入) | ≈120 行 |
| 工具校验 | `tools/mcp_tools/verify_tools.py` 增 `--subset` | ≈80 行 |
| 文档 | `deploy/yama-server.env.example` 补 5 个变量;`docs/Mcp_Go_Minimal_Design.md` 状态改"已实施" | — |
**8 个提交,8 个里程碑,预估 62 小时**(明细见 §3 / §7)。`hub` 零改动——这是设计文档
自审后的结论,本计划沿用;若施工中发现必须改 `hub`,先停下来改设计文档。
---
## 1. 开工前必须先定的 5 件事
这 5 项都会阻塞某个里程碑,且都需要一次性拍板。建议按顺序在本计划评审时定掉。
### 1.1 `get_audit_log` 的代码复用方式(阻塞 M2)
设计文档 §3.2 要求"复用 `web/audit_query.go` 的查询器",§10 又要求"`mcp` 不 import `web`"。
两者冲突:查询器 `queryAuditLog` 及其类型/过滤/时间解析全是 `web` 包私有(`web/audit_query.go:158-328`)。
| 方案 | 做法 | 代价 |
|---|---|---|
| **A(推荐)** | 新增 `server/go/auditquery` 包,把 `queryAuditLog` + `auditQueryRequest/Result` + `auditRecordMatches` / `auditEventFilterMatches` / `auditStringField` / `parseAuditTime` / `clamp*` 整体搬过去并导出(`Scan(path string, q Query) (Result, error)`);`web/audit_query.go` 只留 handler 与回包整形 | 搬移 + `web/audit_query_test.go`(294 行)机械改调用名;依赖方向保持不变 |
| B | `mcp` 自己实现一个精简扫描器(keyword/type/limit/offset) | 少动 `web`,但审计格式一旦变就有两份实现 |
| C | `mcp` import `web` | 破环:`web → mcp` 已存在(`WithMCP`),反向成环直接编译失败 |
**已确认:采用 A**。M2 的第一步就是搬包,`go test ./web/...` 全绿后再写工具。
### 1.2 版本号与提交号注入(阻塞 M2 的 `get_server_status`)
`cmd/main.go` 目前没有版本常量(全文件 grep 不到)。**已确认**的做法:
- 新增 `server/go/buildinfo`,只放 `var Version, Commit string`(零值空串)+ `Snapshot()`。
不塞 `main`:`mcp` 不能依赖 `main`,也不该为两个字符串在装配链上多传两层。
- 注入:`-X github.com/yuanyuanxiang/SimpleRemoter/server/go/buildinfo.Version=…`,同样注入 `.Commit`。
取值 `Version=$(git describe --tags --always --dirty)`、`Commit=$(git rev-parse --short HEAD)`
(现在是 `v1.4.2-72-g425d737-dirty` / `425d737`)。
- `build.ps1`:Debug/Release **都**拼 `-X`(Debug 只是不剥符号);`Makefile` 的 `LDFLAGS`
用 `$(shell git …)` 同步。
- 取不到(无 git、源码包构建)就保持空串,`get_server_status` 原样返回空串,**不伪造**。
- Windows 资源同步:`cmd/winres/winres.json` 里的版本号改成占位,构建前跑
`go-winres make --in cmd/winres/winres.json --out cmd/rsrc --product-version git-tag --file-version git-tag`
(实测会把 manifest identity / FileVersion / ProductVersion 三处一起覆盖成 `1.4.2`);
`go-winres` 不存在时警告并跳过。`server/go/cmd/*.syso` 加进 `.gitignore`,不再出现在
`git status` 里。文件属性 = 干净 tag,运行时 `version` = `git describe` 全串,各司其职。
### 1.3 工具 schema 用哪一份(阻塞 M2/M5/M6/M7)
设计文档 §3.2 给的参数集与 `mcp/tools.json`(MFC 现网 schema)**并不完全一致**:
| 工具 | 设计文档 §3.2 | `mcp/tools.json` 实际 |
|---|---|---|
| `list_hosts` | `group` `name` `online_only` `limit` `offset` | `client_type` `group` `include_offline` `ip` `limit` `name` `offset` `online` `os` `query` |
| `get_host_detail` | `id` | `id` `ids` |
| `get_audit_log` | `keyword` `type` `since` `limit` `offset` | `keyword` `limit` `offset` `type` |
| `get_screenshot` | `id` `max_width` | `id` `max_width` `height` `hwnd` `mode` `monitor` `width` `x` `y` |
| `terminal_exec` | 一致 | 一致 |
| `terminal_close` | `session_id` | `id` `session_id` |
| `list_files` | `id` `path` `limit` | `id` `ids` `limit` `offset` `path` |
| `read_file` | `id` `path` `offset` `limit` `encoding` | 同 + `max_bytes` |
设计文档自称"全部命名、参数、错误码与 MFC 对齐",实际只有 naming 与错误码对齐。
**已确认:`mcp/tools.json` 是唯一契约**——`name` / `description` / `inputSchema` /
`outputSchema` 和工具顺序都按它来(`verify_tools.py:12` 的比对口径)。
- 9 个工具的这四份字段由 `tools/mcp_tools/gen_go_tools.py` 从 `mcp/tools.json` 抽取(保持相对顺序),
写到 `server/go/mcp/tools_minimal.json`,Go 侧 `//go:embed` 原样回 `tools/list`;脚本支持
`--check`(子集与抽取结果不等则非零退出),加一个 Go 单测锁名字与顺序。
- `tools.json` 里没有 `annotations`,MFC 也不发,Go 不发(M1 的测试相应改为"不带 annotations")。
- 输出按对应 `outputSchema` 的字段名组装,**不套用设计文档 §3.2 的自造形状**。
| 参数 | Go 侧处理 |
|---|---|
| `list_hosts` 全部 10 个 | 全部实现(`DeviceInfo` 上做字符串过滤,成本可忽略) |
| `get_host_detail.ids` | 实现批量(≤50),按 `outputSchema` 的 `{tool,total,succeeded,failed,skipped,results[]}` 汇总 |
| `get_audit_log` | `keyword` / `type`(映射 `auditquery.Event`)/ `limit` / `offset`;**没有 `since`**(MFC 的 schema 里就没有) |
| `get_screenshot` 的非整屏参数 | `mode=region/window/monitor` 或 `hwnd/x/y/width/height` 任一出现 → `-32005`,报文点名参数并说明需要 `CLIENT_CAP_SCREEN_REGION` 扩展请求;不静默忽略 |
| `get_screenshot.max_width` | 钳制 `[64,1920]`(schema 与 `McpServer.cpp:3386` 一致);缺省/0 → Go v1 固定 1024(没有 MFC 的 RTT 自适应档位) |
| `terminal_close.id` | 必需;用于定位设备,`session_id` 用于匹配会话 |
| `list_files` 的 `id/ids/path/limit/offset` | 全部实现;`offset` 是服务端在完整列表上做窗口裁剪;批量走 results 汇总 |
| `read_file` 的语义 | **行语义**:`offset` 起始行(负数=末尾 N 行)、`limit` 行数、`max_bytes` 字节上限;`encoding` 支持 `auto/utf-8/gbk/gb18030/latin1` |
| 输出字段 | `list_hosts` → `hosts/total/totalAll/limit/offset/hasMore`;`list_files` → `files`(不是 `entries`)/`drives`;`get_host_detail.capabilities` → `screenPreview/screenRegion/windowInfo/fileTransferV2/c2cPaths/registry/remoteControl/platform`;`read_file` → `encoding/eol/lines_total/lines_returned/sha256/size/text/truncated` |
| hub 没有的字段 | `authStatus/tls/location/install_time/remark` 不伪造、直接不给(`outputSchema` 只强制 `hosts`) |
`read_file` 的整文件下载仍受 `YAMA_MCP_READ_MAX`(2 MiB)硬门约束,超过 → `-32602`(schema 描述同款口径)。
### 1.4 测试环境与"真机"路径(阻塞 M4 起的全部验收)
**已确认并已由 M0 实测**(详见 §4.3):本机真客户端用 **`x64\Debug\ghost.exe`**,
`TestRun.exe` 不可用(依赖 `ServerDll.dll` 内存加载;Release 版从非安装路径启动会走安装
流程并自删)。Go 服务端默认 **trial** 签名即可,客户端已上线;屏幕/文件能力是否解锁
在 M5/M6 实测(`YAMA_LICENSE_DISABLED=1` 的 NoOp 会让客户端拒绝这两类功能,不要用于
M5 之后的验收)。
### 1.5 只读模式下的工具集合(阻塞 M8)
`YAMA_MCP_READONLY=1` 时 `tools/list` 只出 7 个。`--subset` 必须支持"期望集合 7 或 9"两种,
由环境变量或 `--readonly` 参数决定;不能写成硬编码 9。
---
## 2. 里程碑与提交边界
| 里程碑 | 提交标题(建议) | 设计文档 § | 依赖 | 完成定义(可验收) | 预估 |
|---|---|---|---|---:|
| M1 | `Feature(Go): MCP endpoint with bearer auth and tools/list` | §4、§3.1 | — | `curl` 打通 initialize/ping/tools/list;错误令牌 401;GET 405;通知 204 | 6h |
| M2 | `Feature(Go): four local MCP read tools and a shared audit query package` | §3.2、§1.1 | M1 | 4 个工具返回真实数据;`go test ./web/...` 与新增用例全绿 | 10h |
| M3 | `Feature(Go): per-device locks, concurrency cap and MCP audit trail` | §9、§4.4 | M1 | 并发调用返回 -32003;每次调用一条 `mcp.tool.call` | 4h |
| M4a | `Feature(Go): MCP terminal sessions with a ring buffer` | §6.1-§6.3 | M3 | 会话表 + 订阅 + 缓冲;浏览器开终端时 MCP 返回 -32003 | 6h |
| M4b | `Feature(Go): terminal_exec with sentinel cleaning and polling` | §6.4-§6.6 | M4a | 20 条连续命令零失败;超时后轮询取回完整输出 | 8h |
| M4c | `Feature(Go): terminal_close, idle sweep and legacy-client guard` | §6.2、§6.7 | M4b | 关闭幂等;空闲 180s 回收;非 PTY 返回 -32005 | 2h |
| M5 | `Feature(Go): get_screenshot over the maintenance-free preview RPC` | §7 | M3 | Windows/Linux 各出一张图;BGRX 分支有单测 | 6h |
| M6 | `Feature(Go): list_files over the file-manager sub-connection` | §5.3、§8.1 | M3 | 盘符/目录/错误三种路径;老客户端超时有明确 message | 8h |
| M7 | `Feature(Go): read_file over the V2 stream receiver` | §5.4、§8.2-§8.3 | M6 | `.env` 字节一致且 SHA-256 匹配;路径穿越全部拒收 | 10h |
| M8 | `Feature(Go): verify_tools --subset and MCP deployment docs` | §10、§4.2 | M1 | 9(或 7)个工具的 schema/description 与 `tools.json` 严格一致 | 3h |
M4 拆成三个提交是因为它占全量工作量的 1/4,一次提交无法审查;其余里程碑按设计文档
§11 的 10 个施工序合并(§11 的 3 并进 M3,4/5/6 并成 M4a/b/c,7 是 M5,8 是 M6,9 是 M7,10 是 M8)。
---
## 3. 里程碑细则
### M1 骨架与鉴权(设计 §4)
**新增文件**
```
server/go/mcp/server.go // Config、Server、New、Enabled、Handle、Close
server/go/mcp/jsonrpc.go // 请求/响应结构、错误对象、批量拒绝
server/go/mcp/tools.go // //go:embed tools_minimal.json,tools/list 原样返回
server/go/mcp/tools_minimal.json // gen_go_tools.py 从 mcp/tools.json 抽取的 9 个工具
server/go/mcp/errors.go // -32001…-32602 常量与 message 模板
tools/mcp_tools/gen_go_tools.py // 抽取脚本,--check 模式供验收
```
**实现要点**
1. `Config` 从环境变量读全(`cmd/main.go` 解析后传入,`mcp` 包不直接读 env):
`Token` / `Readonly` / `TermIdle` / `MaxConcurrency` / `ReadMax`。
2. `Handle` 分支表:`POST` 之外一律 `405`(带 `Allow: POST`);无 `id` 的通知 `204`;
数组入参 `-32600`;未知 `method` `-32601`;`tools/call` 未知工具名 `-32601`。
3. 鉴权:`subtle.ConstantTimeCompare`,长度不等直接失败;缺令牌 → `401` +
`WWW-Authenticate: Bearer realm="mcp"`,不带 JSON-RPC 体(规范要求传输层失败)。
4. 体积:`http.MaxBytesReader(w, r.Body, 8<<20)`,超限 `413`。
5. `initialize` 回 `protocolVersion=2025-06-18`、`capabilities.tools={listChanged:false}`、
`serverInfo={name:"yama", version:<build>}`、`instructions=<Go 后端差异说明>`。
`serverInfo.name` 与 MFC 一致,Go 差异只写 `instructions`——避免客户端按 name 分叉。
6. 路由注册:`web/server.go` 加 `WithMCP`,`Start()` 里
`if s.mcp != nil && s.mcp.Enabled() { mux.HandleFunc("/mcp", s.mcp.Handle) }`,
否则打一行 `MCP endpoint disabled: YAMA_MCP_TOKEN not set`。
7. `cmd/main.go`:在 `web.New(...)` 之前构造 `mcpSrv`,再 `.WithMCP(mcpSrv)` +
`handler.mcp = mcpSrv`(`MyHandler` 加字段);`mcp` 只依赖 `hub`/`protocol`/`devicehistory`/`logger`。
**测试**(`mcp/server_test.go`,`httptest` + fake hub)
- 令牌:正确 / 错误 / 长度不同 / 缺失 → 200 / 401 / 401 / 401。
- 方法:`initialize`、`ping`、`tools/list`、`notifications/initialized`(204)、未知方法(-32601)。
- 形态:批量数组 → -32600;GET/DELETE → 405;超大体 → 413。
- `tools/list`:数目与 `Readonly` 相符;工具定义与 `tools_minimal.json` 逐字一致且顺序不变
(无 `annotations`,与 MFC 一致)。
**验收命令**
```bash
cd server/go
go build ./... && go test ./mcp/...
curl -s -X POST localhost:18090/mcp -H "Authorization: Bearer $YAMA_MCP_TOKEN" \
-H 'Content-Type: application/json' \
-d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'
```
### M2 本机只读四工具(设计 §3.2)
**改动**
1. 先做 §1.1 的 `auditquery` 抽包:搬移 → `web` 改调用 → `go test ./web/...` 全绿。
2. 新增 `mcp/tools_local.go`:
- `list_hosts`:`hub.ListDevices()` + `history.Offline(onlineSet)` 合并;`include_offline`
决定是否并入历史;`online/ip/os/group/name/client_type/query` 全为过滤(`name`/`query`
大小写不敏感子串);按 `outputSchema` 返回 `{hosts,total,totalAll,limit,offset,hasMore}`,
host 字段按 schema 命名组装,hub/历史里确有的 `location/install_time/screen/version` 照填,
两边都没有的 `authStatus/tls/remark` 不伪造。
- `get_host_detail`:`id` 或 `ids`(≤50,批量走 `{tool,total,succeeded,failed,skipped,results[]}`);
`capabilities{screenPreview,screenRegion,windowInfo,fileTransferV2,c2cPaths,registry,remoteControl,platform}`
(`protocol.SupportsCap` 逐位)——**不含 `v2`**(恒真,列出来误导)。
- `get_server_status`:按 `outputSchema` 的字段名组装,Go 只填能如实取到的
`version / uptime_sec / hosts / sessions / port / bind`(其余 MFC 专有字段不给);
`version` 取 `buildinfo`(§1.2),`uptime_sec` 用 `mcp.Config.StartedAt`,`commit`
只进日志,不塞进 schema 未定义的返回字段。
- `get_audit_log`:`auditquery.Scan`;`type` 映射事件过滤;无 `since`。
3. `buildinfo` 包 + `build.ps1` / `Makefile` 的 `-X` + winres 重建(§1.2)。
**测试**(`mcp/tools_local_test.go`)
- `devicehistory.New(t.TempDir()+"/devices.json", 10, log)` + `hub.Register` 造 3 台在线、2 台历史
离线;断言过滤/分页,以及 `total`(命中数)、`totalAll`(过滤前)、`hasMore` 三者分离。
- `get_host_detail` 的能力位:给一个 capability 串(含/不含 `0x0004`)两种。
- `get_audit_log`:用 `logger.Audit` 写临时文件后查询(`auditquery` 的用例在搬包时一并迁)。
### M3 锁、并发与审计(设计 §9、§4.4)
**新增** `mcp/lock.go`、`mcp/audit.go`。
1. 设备锁:`map[string]*sync.Mutex` + `TryLock`,占用即 `-32003`,message 带占用工具名与
已持续时长(`since` 记录在持锁结构里)。
2. 全局信号量:`chan struct{}` 容量 `MaxConcurrency`,`TryAcquire` 失败 `-32003`。
3. 审计:每次 `tools/call` 一条 `log.Audit("mcp.tool.call", …)`,字段
`actor=mcp role=admin source=mcp tool device ok code ms args=<首词+长度> result=<体积摘要>`;
**不记命令全文**(进 debug 日志)。HTTP `r.Context()` 取消同样走 defer 释放锁。
**测试**:并发两个同设备调用 → 第二个 -32003;`close(cancel)` 后锁被释放;审计行字段齐全
(读临时审计文件断言)。
### M4a 终端会话(设计 §6.1-§6.3)
**新增** `mcp/session.go`(会话表 + 空闲回收)、`mcp/term.go`(环形缓冲 + 哨兵检测骨架)。
1. `mcp.Server` 实现 `hub.EventHandler` 全接口(`OnDeviceOnline/Offline/Update`、
`OnScreenFrame`、`OnResolutionChange`、`OnCursorChange`、`OnClipboardText`、
`OnTerminalReady/Data/Closed`),只有终端三个方法做事,其余空实现;
`cmd/main.go` 里 `deviceHub.Subscribe(mcpSrv)`,退出时 `hub.Unsubscribe` + `Close()`。
2. `OnTerminalData` 在 TCP 读循环上执行,**必须不阻塞**:只做"查会话 → 追加环形缓冲 →
剥 4 字节 `TRM1` 前缀 → 哨兵扫描 → `sync.Cond` 唤醒",任何长操作都不允许(设计 §6.3)。
非 MCP 会话的设备直接丢弃(零开销)。
3. 环形缓冲 256 KiB + `base/total/delivered` 绝对偏移;溢出丢最旧并累计 `droppedBytes`。
4. 会话表 key 用 `deviceID`;`session_id` 为 `"s-"+6hex`;对外只暴露 `session_id`。
**测试**:`hub.PublishTerminalData` 灌 1 MB → 缓冲不涨、`truncated` 语义正确;关闭后释放;
浏览器(另建一个订阅者 `OpenTerminalSession`)占用时 `OpenSession` 返回 busy。
### M4b `terminal_exec` 执行与轮询(设计 §6.4-§6.6)
1. 打开:`hub.OpenTerminalSession(deviceID)`;`ErrTerminalBusy` → `-32003`;等
`OnTerminalReady`(带超时 → `-32001`);非 PTY → `-32005`(M4c 收紧)。
2. 下发:行尾按 `isPTY`/平台(设计 §6.4 的表);`hub.SendToTerminal`。
3. 清洗三段**整体移植**:`StripEchoedInput` → `StripAnsi` → `StripSentinelText`
(对应 MFC `McpServer.cpp:3946-4040`),顺序不可换。Go 侧用表驱动单测锁住行为。
4. 等待与交付:`done`/`closed`/超时三分支;超时**不销毁会话**,`delivered` 游标支持
`terminal_exec` 不带 `command` 的轮询;`max_output_bytes` 按行截断(保留换行)并置
`truncated`(防止把 UTF-8/GBK 多字节字符切坏)。
5. 返回体:`{session_id, output, exit_code?, done, offset, truncated, is_pty, reused}`。
**单测**(表驱动,样例来自 MFC 实测)
`rem hello`、`cmd /c echo abc`、`type .env`、SPAM 循环、`ping -n 30` 超时后轮询、
`cmd /\c` 折行回显、退出码 0/1 与非 PTY 单行哨兵。
**集成**(假设备,§4.2):模拟 `TOKEN_TERMINAL_START` → 输出 → 哨兵,断言 `exit_code`。
### M4c 关闭、回收与老客户端(设计 §6.2、§6.7)
1. `terminal_close`:**幂等**(会话不存在也 200);只关 MCP 自己创建的会话(`hub.CloseTerminalSession`
只有在会话表里有该设备且 `hub.TerminalIsPTY` 一致时才调用,避免误关浏览器会话——实现上
以"会话表命中"为准)。
2. 在途命令被 `terminal_close` 撞上:对齐 C++ 的 `waiters` 教训(`McpServer.cpp:12611`)——
置 `closed` 唤醒等待者交付剩余缓冲,无等待者则立即擦会话并 `CloseTerminalSession`。
3. 空闲回收 ticker 30s 扫一次,`lastUsed > TermIdle` 关闭;`Close()` 关掉全部会话。
4. 非 PTY(`TOKEN_SHELL_START`)→ `terminal_exec` 直接 `-32005`,message 写明"该客户端版本
不支持 PTY 会话"。不支持 shell 的客户端不设能力门,超时文案带一句提示(设计 §6.7)。
**测试**:closing 幂等;关闭后立刻重开 <1s;空闲回收(把 `TermIdle` 调成 100ms);
在途关闭与无等待者两条分支(各一个用例)。
### M5 `get_screenshot`(设计 §7)
**新增** `mcp/screen.go`;`protocol/commands.go` 加 `CommandScreenPreviewReq=247`、
`TokenScreenPreviewRsp=248`;`cmd/main.go` `OnReceive` 加两个 case 转 `mcp.OnPacket`。
1. 请求表 `map[deviceID]*pendingPreview{reqID uint16; ch chan []byte}`,
`reqID` 用 `atomic.Uint32` 取低 16 位;**响应 reqID 不匹配直接丢弃**(对齐 MFC
`TakePreviewResponse`)。
2. 能力门:缺 `protocol.ClientCapScreenPreview` → `-32005`。
3. 8 字节请求体;`max_width` 钳制 `[64,1920]`、缺省/0 → 1024;`jpegQuality` 固定 80。
4. 响应:`status != 0` → 1/2 `-32000`、3 `-32005`、4 `-32602`;`format=0` 直接返回 JPEG,
`format=3`(BGRX)→ 先 `image.RGBA` 再 `jpeg.Encode`;`bytes != w*h*4` 视为畸形包 `-32000`。
5. 超时 8s,超时删表项,**不 CancelIO**(主连接 RPC,MFC 同款)。
6. 返回 `content[]` 一项 `image`(base64 JPEG)+ `structuredContent{width,height,bytes,format,source}`。
**测试**:JPEG 魔数(`FF D8 FF`)、BGRX→JPEG 像素抽样、reqID 错包被丢弃、status 映射、
超时。
### M6 `list_files`(设计 §5.3、§8.1)
**新增** `mcp/filemgr.go`;`protocol` 加 `CommandListDrive=1`、`CommandListFiles=2`、
`TokenDriveList=103`、`TokenFileList=104`、`TokenFileListError=171`(**加一个常量唯一性单测**:
新值不得与既有 `protocol` 常量重复,`103/104` 紧邻 `TOKEN_LOGIN=102`,值写错会吃主连接登录包)。
1. 主连接 `hub.SendToDevice(dev, []byte{CommandListDrive})`;等文件子连接:在
`OnReceive` 顶部(终端 short-circuit 之后)先喂 `mcp.OnPacket(ctx, data)`,`mcp` 按
`ctx.GetInfo().ClientID` 找到 pending 请求并**记住 ctx**(后续 `COMMAND_LIST_FILES` 要用它)。
2. `TOKEN_DRIVE_LIST` 到达后**不关子连接**,同一 ctx 下发 `[CommandListFiles][path\0]`;
`TOKEN_FILE_LIST` / `TOKEN_FILE_LIST_ERROR` 才收尾。
3. 解析按设计附录 A;`attr & 0x10` 判目录;文件名 `protocol.DecodeClientString(data, capability, "")`。
4. 错误映射:`win32err ∈ {2,3}` → `-32009`;`5` → `-32010`;其它 → `-32000`。
老客户端无 `TOKEN_FILE_LIST_ERROR` → 超时;message 提示"路径可能不存在,先列目录确认"。
5. 收尾:`COMMAND_BYE` → 500ms → `ctx.Close()`(`hub` 同款优雅关闭)。
**测试**:盘符/文件/错误三种黄金字节(照 MFC `ParseDriveList`/`ParseFileList` 的样例抓真实包,
存为 `testdata/*.bin`);`offset/limit` 语义;客户端中途断开 → `-32001` 且 pending 表被清。
### M7 `read_file`(设计 §5.4、§8.2-§8.3)
**新增** `mcp/filev2.go`;`protocol` 加 `CommandSendFileV2=85`、`CommandFileCompleteV2=91`、
`CmdDownFilesV2=94`;`cmd/main.go` 加两个 case。
1. 流程:列盘(复用 M6 的子连接)→ 同一子连接发 `[CmdDownFilesV2][targetDir\0][path\0][\0]`
→ 服务端关掉文件子连接 → 客户端建 V2 子连接(`ConnAuth` 已钉 `ClientID`)→
`COMMAND_SEND_FILE_V2 × N` → `COMMAND_FILE_COMPLETE_V2`。
2. `targetDir := os.MkdirTemp("", "yama-mcp-read-*")`,`defer os.RemoveAll`。
3. **大小门**:首个 chunk 的 `fileSize` 超 `ReadMax` → 立即中止、删目录、`-32602`
(不要先落盘再报错)。
4. **路径校验**(安全,必须单测):`filepath.Clean(filepath.Join(targetDir, FromSlash(name)))`
+ `filepath.Rel` 判越界;另拒 NUL / 换行;`name` 允许客户端回填为相对路径。
5. SHA-256 校验(完成包 32 字节)→ 编码判定(BOM → `utf8.Valid` → 回退
`simplifiedchinese.GBK`,`latin1` 逐字节)→ 按行切分并取
`offset`/`limit`/`max_bytes` 窗口 → 返回
`{path,size,encoding,eol,lines_total,offset,lines_returned,truncated,text,sha256}`。
6. 超时/断流:`-32001`;工具描述写明"超时可能是不支持 V2 的旧客户端"(设计 R3)。
**测试**:路径穿越用例集(`../x`、`..\\..\\x`、绝对路径、UNC、混合分隔符、`a/../../b`);
大小门;SHA 不符;GBK 文件;负 offset;`transferID` 不匹配的迟到 chunk 被丢弃。
### M8 校验工具与文档(设计 §10)
1. `verify_tools.py --subset <tools.json> [token] [port] [--readonly]`:
抓 Go 服务端 `tools/list`,与 `tools.json` 同名工具逐字段比 `description` / `inputSchema` /
`outputSchema`(与 `verify_tools.py` 的 `FIELDS` 口径一致);名字集合必须恰好等于
期望的 9(或 7),多一个少一个都失败。
2. 同批更新:`deploy/yama-server.env.example` 加 `YAMA_MCP_TOKEN` / `YAMA_MCP_READONLY` /
`YAMA_MCP_TERM_IDLE` / `YAMA_MCP_MAX_CONCURRENCY` / `YAMA_MCP_READ_MAX`;
设计文档状态改"已实施"。
---
## 4. 测试与验证
### 4.1 三档测试
| 档 | 跑什么 | 覆盖 | 何时跑 |
|---|---|---|---|
| 1 纯函数单测 | 清洗三段、哨兵、环形缓冲、解析器、路径校验、schema 校验、JSON-RPC | 全部逻辑分支 | 每次提交 |
| 2 假设备集成(进程内) | 真 `hub` + 假设备 ctx + `httptest` 的 `/mcp` | 九工具端到端、并发、取消、审计 | 每次提交 |
| 3 真客户端 smoke | `x64\Debug\ghost.exe`(§4.3)或 Linux ghost → 本机 Go 服务端 | 真实 PTY/文件/截屏链路 | 每个里程碑收尾 + 整体验收 |
档 2 是主力:不依赖网络、可在 CI 跑,且能精确控制入站包的字节。
### 4.2 假设备 harness(`mcp/harness_test.go`)
```go
h := hub.New()
sent := make(chan []byte, 16) // 出站包,带缓冲 channel 避免数据竞争
h.SetSender(func(ctx *connection.Context, data []byte) error {
sent <- append([]byte(nil), data...); return nil
})
cfg := logger.DefaultConfig(); cfg.Level = logger.LevelError
mcpSrv := mcp.New(mcpCfg, h, history, logger.New(cfg))
unsubscribe := h.Subscribe(mcpSrv) // Subscribe 返回退订闭包(hub 没有 Unsubscribe 方法)
ts := httptest.NewServer(http.HandlerFunc(mcpSrv.Handle))
// 假设备:拿到 sent 里的 COMMAND_SHELL 后,模拟回 TOKEN_TERMINAL_START 与输出:
mcpSrv.OnPacket(devCtx, append([]byte{protocol.TokenTerminalStart}, ...))
h.PublishTerminalData(devID, []byte("hello\r\n__MCP_DONE_ab12cd__0\r\n"))
```
要点:
- 造设备:`h.Register(&hub.Device{ID:"dev", PeerIP:"10.0.0.1"}, devCtx)`;
`devCtx` 的 `Info.ClientID` 按子连接需要设置(模拟 `handleConnAuth` 的钉值)。
- `sent` 用带缓冲 channel(上面写法),测试里 `select` 带超时地读,不 sleep。
- 收尾:`defer unsubscribe()` + `defer mcpSrv.Close()`;再断言没有残留会话
(`mcpSrv.SessionCount()==0`,为此在会话表上留一个只读访问器给测试用)。
### 4.3 真客户端 smoke(M0 已实测,2026-11-12)
**结论:Windows 真客户端用 `x64\Debug\ghost.exe`,`TestRun.exe` 不可用。**
- `test.cpp` 用 `MemoryDllRunner` 加载同目录的 `ServerDll.dll`(`client/test.cpp:448`);
没有它时静默每 3 秒重试,Go 侧也没有这条内存 DLL 链路。
- Release `TestRun.exe` 从非安装路径启动时 `RegisterStartup()` 返回 0 → `self_del()`
自删(`client/test.cpp:323-334`);M0 第一次尝试确实删掉了 `release\TestRun.exe`,
已用 Release 重建恢复(359936 → 425472 字节)。`-cmd=0` 绕不过安装流程。
- Release `ghost.exe` 同样会走安装流程(dst = `%ProgramData%\Windows Ghost\WinGhost.exe`),
因此本机测试统一用 Debug ghost:`RegisterStartup` 在 `_DEBUG` 下直接返回 1(`reg_startup.c:413`)。
**M0 实测记录**:
- 服务端 `Bin\YamaGo_x64.exe -port 16543 -http-port 18090`(18080 被 python/wslrelay 占用),
`YAMA_DEVICES_FILE` 指向临时文件;默认签名模式 **TRIAL**(`https://web.just-do-it.icu:8080`)。
- `x64\Debug\ghost.exe 127.0.0.1 16543` → 10 秒内设备上线:
`event=device.online computer=A6/default device_id=445427540237756328 os="Windows 11"`,
`devices.json` 写入 `first_seen/last_seen`,服务端无错误日志。
- 清理:Debug ghost 的 `SetSelfStart` 会在 `HKCU\...\Run` 写一条哈希名,按运行前快照删除新增项;
用户既有的 `Client Demo` 计划任务与 `C:\ProgramData\Client Demo\ClientDemo.exe` 未被改动。
- 待办:trial 签名下客户端是否解锁屏幕/文件能力,要在 M5/M6 端到端确认
(`YAMA_LICENSE_DISABLED=1` 的 NoOp 已知会被客户端拒绝)。
```powershell
cd C:\github\YAMA
.\build.ps1 -GoServer -Config Debug
$msb = "C:\Program Files\Microsoft Visual Studio\18\Insiders\MSBuild\Current\Bin\MSBuild.exe"
& $msb client\ghost_vs2015.vcxproj -p:Configuration=Debug -p:Platform=x64 -p:SolutionDir=C:/github/YAMA/ -m -v:m
$env:YAMA_MCP_TOKEN="<32hex>"; $env:YAMA_DEVICES_FILE="$env:TEMP\yama_m0\devices.json"
Start-Process .\Bin\YamaGo_x64.exe -ArgumentList '-port','16543','-http-port','18090'
Start-Process .\x64\Debug\ghost.exe -ArgumentList '127.0.0.1','16543'
curl -s -X POST localhost:18090/mcp -H "Authorization: Bearer $env:YAMA_MCP_TOKEN" ...
```
注意:Debug ghost 的 `Mprintf` 走 `TRACE`(`common/logger.h:379`),客户端侧没有日志文件,
验收以服务端 audit/日志为准。
### 4.4 与 MFC 的对照验收
同一批命令在两个后端各跑一遍,比对 `exit_code` 与清洗后的文本(不一致就是移植缺陷):
```
sc query AssemblyManager rem hello cmd /c echo abc
type C:\...\.env ping -n 30 127.0.0.1 for /L %i in (1,1,1000000) do @echo SPAM-%i
```
### 4.5 每个提交前必跑
```bash
cd server/go
gofmt -l . ; go vet ./... ; go test ./... ; go test -race ./mcp/...
go build ./cmd
```
MFC 侧测试:M0–M8 的改动全在 `server/go`、`tools/mcp_tools` 与文档,**没有触碰任何
C++ / 客户端文件**(`git diff --name-only 5f124fc..HEAD` 可证),因此原计划的
`verify_live_6555.py` 回归没有对象。注意:本机在跑的 Release `Yama_x64.exe` 是更早的
构建(`tools/list` 仍是 `list_online_hosts` 旧名),按约束未重启它;这与本次改动无关,
也不影响上述结论。
---
## 5. 整体验收(对齐设计 §11)
验收日期 2026-11-12。现场:`Bin\YamaGo_x64.exe -port 16543 -http-port 18090` +
`x64\Debug\ghost.exe`(Windows 11)+ WSL Ubuntu 24.04 ghost,临时 token/devices/audit。
- [x] 9 个工具全部可调用;`tools/list` 响应 < 24 KB
—— 22578 B(只读 18288 B);九个工具逐一实调通过
- [x] `terminal_exec` 连续 20 条命令零失败;超时后轮询取回完整输出
—— 同一会话 20 条 `echo ACCEPT_n` 全部取回哨兵(M4b 另有超时轮询实测)
- [x] 浏览器开着终端时 `terminal_exec` → `-32003`,人的会话不受影响
—— `session_test.go:192` 证明浏览器持租约时返回 `ErrTerminalBusy`,
`tools_term.go:273` 映射为 `-32003`;另有 `terminal_close` 不动浏览器租约的用例
- [x] `read_file` 读 `.env` 字节级一致,SHA-256 与远端 `sha256sum` 相同
—— Windows 与 WSL 两边分别实测(M7);本轮 CRLF/单引号样本再验一次
- [x] `get_screenshot` Windows / Linux 各一张,Linux 走 BGRX→JPEG
—— Windows 1024x304 JPEG 本轮实测;Linux 在 M5 实测(WSLg 下画面全黑是
Xwayland 的已知限制,屏幕子连接与 BGRX→JPEG 链路本身通过)
- [x] 审计每次 `mcp.tool.call` 一条,`device`/`tool`/`code`/`ms` 齐全
—— 本轮 30 条,样例含 `"device"`/`"tool"`/`"code"`/`"ms"`
- [x] `verify_tools.py --subset` 通过(9 个 / 只读 7 个两种模式)
—— 读写 9、`YAMA_MCP_READONLY=1` 7 均 PASS;两种反向错配均按预期 FAIL
- [x] `go test -race ./mcp/...` 无数据竞争
- [ ] `hub` 零改动 —— **不成立且不可取**:`hub` 新增 `SendToConn`(M6,往任意子连接
回包必须走编码器)与终端租约代数 `terminalGen` / `OpenTerminalSessionLease`
(M4a,防止失去租约的查看者关掉别人的 shell)。两项都是设计遗漏、实现阶段补的,
均有单测;`hub` 原有对外行为不变。
---
## 6. 风险(在设计 R1-R8 之上新增)
| # | 风险 | 影响 | 处置 |
|---:|---|---|---|
| R9 | `OnTerminalData` 在 TCP 读循环上阻塞 | 整个设备通道卡死(浏览器画面/终端一起停) | 只做内存追加与唤醒;缓冲满丢最旧;禁止在回调里调用 `hub` 的会加锁方法 |
| R10 | 文件子连接 ctx 生命周期 | 客户端中途断开 → 后续发送到已关闭 ctx / pending 表泄漏 | pending 表带超时与 `OnDisconnect` 清理;发送失败即失败收尾 |
| R11 | `103/104` 常量与主连接 token 相邻 | 值写错会把登录包当文件列表(反之亦然) | 常量唯一性单测 + 解析前校验最小长度 |
| R12 | Windows 路径与 `filepath.Rel` | 路径穿越(被控端写主控任意位置) | 单测覆盖 `..`/绝对路径/UNC/混合分隔符;拒 NUL 与换行 |
| R13 | 客户端断开(`r.Context()`)后锁未释放 | 设备永久 `-32003` | `defer` 释放;单测用 cancel 验证 |
| R14 | 单测 goroutine 泄漏 | `-race` 偶发失败 | `Close()` 幂等;测试里 `defer Close()` |
| R15 | 真机 smoke 用 Debug ghost,与 Release 客户端有差异 | 安装/许可行为可能在 Release 上不同,本地验收未覆盖 | M0 已确认 Debug ghost 可上线;M5/M6 用 trial 签名验证屏幕/文件能力;交付说明写明该差异 |
---
## 7. 工时估算
| 里程碑 | 编码 | 测试 | 小计 |
|---|---:|---:|---:|
| M1 | 3h | 3h | 6h |
| M2 | 6h | 4h | 10h |
| M3 | 2h | 2h | 4h |
| M4a | 4h | 2h | 6h |
| M4b | 5h | 3h | 8h |
| M4c | 1h | 1h | 2h |
| M5 | 4h | 2h | 6h |
| M6 | 5h | 3h | 8h |
| M7 | 6h | 4h | 10h |
| M8 | 2h | 1h | 3h |
| 整体联调 + 真机验收 | — | — | 6h(含在 §5) |
| **合计** | **38h** | **25h** | **≈63h ≈ 8 人日** |
---
## 附录 A:`protocol/commands.go` 新增常量
| 常量 | 值 | 方向 | 里程碑 |
|---|---:|---|---|
| `CommandListDrive` | 1 | S→C 主连接 | M6 |
| `CommandListFiles` | 2 | S→C 文件子连接 | M6 |
| `CommandSendFileV2` | 85 | C→S V2 子连接 | M7 |
| `CommandFileCompleteV2` | 91 | C→S V2 子连接 | M7 |
| `CmdDownFilesV2` | 94 | S→C 文件子连接 | M7 |
| `TokenDriveList` | 103 | C→S 文件子连接 | M6 |
| `TokenFileList` | 104 | C→S 文件子连接 | M6 |
| `TokenFileListError` | 171 | C→S 文件子连接 | M6 |
| `CommandScreenPreviewReq` | 247 | S→C 主连接 | M5 |
| `TokenScreenPreviewRsp` | 248 | C→S 主连接 | M5 |
## 附录 B:环境变量
| 变量 | 默认 | 说明 | 引入里程碑 |
|---|---|---|---|
| `YAMA_MCP_TOKEN` | 空(端点不注册) | 32 位十六进制静态令牌 | M1 |
| `YAMA_MCP_READONLY` | 0 | 隐藏 `terminal_exec` / `terminal_close` | M1 |
| `YAMA_MCP_TERM_IDLE` | 180 | 终端会话空闲回收秒数 | M4c |
| `YAMA_MCP_MAX_CONCURRENCY` | 16 | 全局并发上限 | M3 |
| `YAMA_MCP_READ_MAX` | 2097152 | `read_file` 大小门(字节) | M7 |
## 附录 C:提交前自检清单(每个里程碑)
1. `gofmt -l .` 无输出;`go vet ./...` 干净。
2. `go test ./...` 与 `go test -race ./mcp/...` 全绿。
3. 新增的每个错误码都有触发它的单测(错误码不是装饰)。
4. 新增的每条审计事件都能在临时审计文件里被 `get_audit_log` 查到。
5. 提交标题用 `Feature(Go):` / `Fix(Go):`,正文说明"为什么",trailer 用当前会话模型名。
6. 未推送前发现问题用 `--amend`/squash,不堆补丁提交。
+193 -11
View File
@@ -506,7 +506,7 @@
},
{
"name": "get_screenshot",
"description": "截取指定在线主机的一帧画面,返回 base64 编码的 JPEG 图片(image 对象含 mimeType/data/width/height)。支持 Windows 与带 X11 桌面的 Linux 客户端(能力位 CLIENT_CAP_SCREEN_PREVIEW),主连接 RPC、一次性返回。Android 客户端用无障碍服务 takeScreenshot 抓屏(Android 11+ 且开启无障碍服务,此时登录会声明该能力位;只支持 mode=screen)。mode 可选 screen(默认,整虚拟桌面)/region(指定矩形)/window(指定 hwnd)/monitor(指定显示器);后三种默认按源尺寸 1:1 原生分辨率抓取(适合 OCR/视觉读字),需要较新的 Windows 客户端(CLIENT_CAP_SCREEN_REGION,否则 -32005),结果在 structuredContent.capture 里回报实际源矩形与缩放比例。",
"description": "截取指定在线主机的一帧画面,返回 base64 编码的 JPEG 图片:图片在 content 的 image 块(data 为 base64,mimeType=image/jpeg);structuredContent.image 只有 mimeType/width/height/bytes 元数据,不含图片数据。支持 Windows 与带 X11 桌面的 Linux 客户端(能力位 CLIENT_CAP_SCREEN_PREVIEW),主连接 RPC、一次性返回。Android 客户端用无障碍服务 takeScreenshot 抓屏(Android 11+ 且开启无障碍服务,此时登录会声明该能力位;只支持 mode=screen)。mode 可选 screen(默认,整虚拟桌面)/region(指定矩形)/window(指定 hwnd)/monitor(指定显示器);后三种默认按源尺寸 1:1 原生分辨率抓取(适合 OCR/视觉读字),需要较新的 Windows 客户端(CLIENT_CAP_SCREEN_REGION,否则 -32005),结果在 structuredContent.capture 里回报实际源矩形与缩放比例。",
"gate": null,
"platforms": [
"win",
@@ -515,6 +515,47 @@
],
"impl": "mfc",
"inputSchema": {
"allOf": [
{
"if": {
"properties": {
"mode": {
"enum": [
"region"
]
}
},
"required": [
"mode"
]
},
"then": {
"required": [
"width",
"height"
]
}
},
{
"if": {
"properties": {
"mode": {
"enum": [
"window"
]
}
},
"required": [
"mode"
]
},
"then": {
"required": [
"hwnd"
]
}
}
],
"properties": {
"height": {
"description": "region 模式必填:矩形高度(像素,1~8192)。超出虚拟桌面的部分会被裁剪。",
@@ -704,7 +745,7 @@
},
{
"name": "list_files",
"description": "列举指定在线主机的目录。省略或空 path 返回驱动器列表(drives);给定 path 返回该目录一层内的文件/子目录(files,最多 500 条,含 name/isDir/size/mtime)。只读。",
"description": "列举指定在线主机的目录。省略或空 path 返回驱动器列表(drives);给定 path 返回该目录一层内的文件/子目录(files,含 name/isDir/size/mtime),整目录解析后按 limit/offset 分页(默认 100 条、上限 1000 条,total/hasMore 是真实的目录条目数;目录超过 10 万条时按上限截断并返回 truncated=true)。Windows 上 \".\"/\"/\"/\"\\\\\" 视同省略 path;Linux/macOS 上 \"/\" 是根目录。只读。",
"gate": null,
"platforms": [
"win",
@@ -746,7 +787,7 @@
"type": "integer"
},
"path": {
"description": "要列举的目录路径(如 C:\\Windows);省略或传空则返回驱动器列表",
"description": "要列举的目录路径(如 C:\\Windows 或 /etc)。省略或传空返回驱动器列表;Windows 上 \".\"、\"/\"、\"\\\\\" 视同省略;Linux/macOS 上 \"/\" 是根目录,按真实目录列举。",
"type": "string"
}
},
@@ -816,6 +857,10 @@
},
"totalAll": {
"type": "integer"
},
"truncated": {
"description": "目录条目超过服务端解析上限(100000 条)时为 true;仅在返回 files 时可能出现,此时 total 不是真实总数。",
"type": "boolean"
}
},
"type": "object"
@@ -1255,7 +1300,7 @@
},
{
"name": "mcp_cancel_session",
"description": "取消在飞请求并尽快释放主机占用。给 request_id(tools/call 的 JSON-RPC id,类型要与调用时一致)精确取消一次调用,或按 id(主机)与 session_id 取消匹配的调用(两个都给则必须同时匹配)。工具层的等待在 ≤500ms 内退出并走既有清理路径;本工具最多等 2s,返回 cancelled(取消个数)、released(是否已释放占用)、waited_ms 与 matched(匹配到的会话)。被取消的请求以 -32800 结束。等价于对 SSE 流发 notifications/cancelled。",
"description": "取消在飞请求并尽快释放主机占用。只能取消 kind=call 的在飞调用:给 request_id(tools/call 的 JSON-RPC id,类型要与调用时一致)精确取消一次,或按 id(主机,必须非 0)/ session_id 取消匹配的调用(两个都给则必须同时匹配)。取消一次卡住的调用会连带释放它持有的 pending / file_transfer 等待;持久会话本身不会被关闭,terminal / remote_control / chat 分别用 terminal_close / remote_close / chat_close(两者都要同时给 id 与 session_id)。工具层的等待在 ≤500ms 内退出并走既有清理路径;本工具最多等 2s,返回 cancelled(真正取消的调用个数,不含本工具自身)、released(这些调用是否已释放占用)、waited_ms 与 matched(匹配到的所有会话,每项带 cancellable)。被取消的请求以 -32800 结束。等价于对 SSE 流发 notifications/cancelled。",
"gate": null,
"platforms": [
"win",
@@ -1265,6 +1310,23 @@
],
"impl": "mfc",
"inputSchema": {
"anyOf": [
{
"required": [
"request_id"
]
},
{
"required": [
"id"
]
},
{
"required": [
"session_id"
]
}
],
"properties": {
"id": {
"description": "主机 id:取消该主机上所有在飞请求",
@@ -1296,7 +1358,7 @@
"type": "array"
},
"released": {
"description": "2s 内匹配的会话是否已从服务端表中消失(主机已松开)",
"description": "2s 内被取消的在飞调用(kind=call,不含本工具自身)是否已从服务端表中消失(主机已松开)",
"type": "boolean"
},
"waited_ms": {
@@ -1554,6 +1616,18 @@
],
"impl": "mfc",
"inputSchema": {
"anyOf": [
{
"required": [
"command"
]
},
{
"required": [
"session_id"
]
}
],
"properties": {
"command": {
"description": "要执行的命令(完整 shell,不受白名单约束)。省略时进入轮询模式:不执行新命令,只等待并取回当前会话的增量输出(上一条命令超时后用这个方式继续取)。PTY 会话(Windows ConPTY / Linux PTY)下可用管道 | 与 && / || 串联,退出码取整条管道/串联;不要用后台执行符 &(POSIX)或换行。老非 PTY 客户端仍不支持 & 与 |,请拆成多条调用。Linux 下通过 POSIX shell 执行,可用 ; 串联且退出码取最后一条命令",
@@ -1671,7 +1745,7 @@
},
{
"name": "remote_open",
"description": "在指定在线 Windows、Linux 或 Android 主机上建立远程控制会话(隐藏屏幕子连接)并返回 session_id、抓屏帧尺寸(screen_w/screen_h)与目标(target)。默认推整屏/整虚拟桌面(可能等比缩放);可用 window_hwnd 只推一个窗口,或用 region 只推一个矩形区域,带宽、延迟和点击精度都更好,此时归一化坐标 0..1 相对该目标帧。后续 remote_mouse/remote_keyboard 用归一化坐标(0..1)注入输入,用毕须 remote_close。Linux 需要 X11/Xorg(或 XWayland)桌面,纯 Wayland 会话无法抓屏/注入;window_hwnd/region 仅支持声明 CLIENT_CAP_WINDOW_INFO 的新 Windows 客户端。Windows 多显示器下整屏目标需要新版客户端(整虚拟桌面抓屏),老客户端会被拒绝;window 目标不依赖虚拟桌面抓屏,不受此限。Android 主机只支持整屏目标,输入被翻译成触摸手势与全局动作(见 remote_mouse / remote_keyboard);抓屏依赖客户端已授权录屏(MediaProjection),未授权时 remote_open 会一直等不到屏幕子连接,注入还依赖无障碍服务在跑(未开启时命令照样下发但不生效,且没有回执)。",
"description": "在指定在线 Windows、Linux 或 Android 主机上建立远程控制会话(隐藏屏幕子连接)并返回 session_id、抓屏帧尺寸(screen_w/screen_h)与目标(target)。默认推整屏/整虚拟桌面(可能等比缩放);可用 window_hwnd 只推一个窗口,或用 region 只推一个矩形区域,带宽、延迟和点击精度都更好,此时归一化坐标 0..1 相对该目标帧。后续 remote_mouse/remote_keyboard 用归一化坐标(0..1)注入输入,用毕须 remote_close。Linux 需要 X11/Xorg(或 XWayland)桌面,纯 Wayland 会话无法抓屏/注入(这类主机直接返回 -32005);window_hwnd/region 仅支持声明 CLIENT_CAP_WINDOW_INFO 的新 Windows 客户端。Windows 多显示器下整屏目标需要新版客户端(整虚拟桌面抓屏),老客户端会被拒绝;window 目标不依赖虚拟桌面抓屏,不受此限。Android 主机只支持整屏目标,输入被翻译成触摸手势与全局动作(见 remote_mouse / remote_keyboard);抓屏依赖客户端已授权录屏(MediaProjection),未授权时 remote_open 会一直等不到屏幕子连接,注入还依赖无障碍服务在跑(未开启时命令照样下发但不生效,且没有回执)。",
"gate": "remote_control",
"write": true,
"platforms": [
@@ -1832,6 +1906,48 @@
],
"impl": "mfc",
"inputSchema": {
"allOf": [
{
"if": {
"properties": {
"action": {
"enum": [
"type"
]
}
},
"required": [
"action"
]
},
"then": {
"required": [
"text"
]
}
},
{
"if": {
"properties": {
"action": {
"enum": [
"key_down",
"key_up",
"key_press"
]
}
},
"required": [
"action"
]
},
"then": {
"required": [
"key"
]
}
}
],
"properties": {
"action": {
"description": "动作:key_down / key_up / key_press / type",
@@ -1916,6 +2032,28 @@
],
"impl": "mfc",
"inputSchema": {
"allOf": [
{
"if": {
"properties": {
"action": {
"enum": [
"drag"
]
}
},
"required": [
"action"
]
},
"then": {
"required": [
"x2",
"y2"
]
}
}
],
"properties": {
"action": {
"description": "动作:move / down / up / click / right_click / middle_click / drag / scroll",
@@ -2939,6 +3077,23 @@
"properties": {
"files": {
"items": {
"properties": {
"dir": {
"type": "boolean"
},
"modified": {
"type": "string"
},
"name": {
"type": "string"
},
"path": {
"type": "string"
},
"size": {
"type": "integer"
}
},
"type": "object"
},
"type": "array"
@@ -2946,6 +3101,21 @@
"finished": {
"type": "boolean"
},
"hasMore": {
"type": "boolean"
},
"limit": {
"type": "integer"
},
"offset": {
"type": "integer"
},
"total": {
"type": "integer"
},
"totalAll": {
"type": "integer"
},
"truncated": {
"type": "boolean"
}
@@ -3415,7 +3585,7 @@
},
{
"name": "host_inspect",
"description": "一次取回在线 Windows 主机的多类主机管理信息(原 10 个 host_list_* 工具合并)。aspects 必填、可多选:processes(进程:PID/架构/窗口标题/路径/优先级/线程数/用户/工作集与文件大小)| windows(当前可见顶层窗口;只含可见窗口,单次最多 96 条,超出时 truncated=true 且列表不完整,不能据此断定某窗口不存在;hwnd 可交给 host_control_window / operate_window)| network(网络连接,进程视角、含 UDP;与 list_network_connections 的「连接管理」数据源不同)| software(已安装软件,来自注册表 Uninstall 项;不提供卸载)| browser_history(IE 浏览历史,隐私数据)| favorites(IE 收藏夹,隐私数据)| win32_services(Win32 服务;服务名可用于 host_control_service)| driver_services(驱动服务;字段同 win32_services)| scheduled_tasks(计划任务;任务名 + folder 可用于 host_control_task)| hosts_file(按行返回并自动识别 UTF-8/GBK)。注意:win32_services / driver_services 要求客户端以管理员权限运行——非提权客户端拿不到 SCM 句柄后直接不回应,调用会在约 12 秒后超时(同等场景 list_services 会明确报 access denied)。过滤参数按 aspect 生效、其余忽略(见各参数说明),在服务端完成且先于分页:total 为命中数、totalAll 为该项全部条目数。单个 aspect 时顶层就是该项的列表结果(与合并前的旧工具一致);多个 aspect 时汇总在 results.<aspect>,某个 aspect 失败只记入 errors.<aspect>、不影响其它 aspect,全部失败才 isError=true。每多选一个 aspect 就多一次子连接,耗时线性增长,不需要的不要选。只读。",
"description": "一次取回在线 Windows 主机的多类主机管理信息(原 10 个 host_list_* 工具合并)。aspects 必填、可多选:processes(进程:PID/架构/窗口标题/路径/优先级/线程数/用户/工作集与文件大小)| windows(当前可见顶层窗口;只含可见窗口,单次最多 96 条,超出时 truncated=true 且列表不完整,不能据此断定某窗口不存在;hwnd 可交给 host_control_window / operate_window)| network(网络连接,进程视角、含 UDP;与 list_network_connections 的「连接管理」数据源不同)| software(已安装软件,来自注册表 Uninstall 项;不提供卸载)| browser_history(IE 浏览历史,隐私数据)| favorites(IE 收藏夹,隐私数据)| win32_services(Win32 服务;服务名可用于 host_control_service)| driver_services(驱动服务;字段同 win32_services)| scheduled_tasks(计划任务;任务名 + folder 可用于 host_control_task)| hosts_file(按行返回并自动识别 UTF-8/GBK)。注意:win32_services / driver_services 要求客户端以管理员权限运行——非提权客户端拿不到 SCM 句柄后直接不回应,调用会在约 12 秒后超时(同等场景 list_services 会明确报 access denied)。过滤参数按 aspect 生效、其余忽略(见各参数说明),在服务端完成且先于分页:total 为命中数、totalAll 为该项全部条目数。单个 aspect 时顶层就是该项的列表结果(与合并前的旧工具一致);多个 aspect 时汇总在 results.<aspect>,某个 aspect 失败只记入 errors.<aspect>、不影响其它 aspect,全部失败才 isError=true。每多选一个 aspect 就多一次子连接,耗时线性增长,不需要的不要选;多个 aspect 共用 60 秒预算,用尽后不再下发新的 aspect(正在跑的会跑完),跳过的逐个记入 errors(code=-32001,message 以 skipped 开头),少选几项重试即可。只读。",
"gate": "machine",
"platforms": [
"win"
@@ -4410,6 +4580,18 @@
],
"impl": "mfc",
"inputSchema": {
"anyOf": [
{
"required": [
"name"
]
},
{
"required": [
"service_name"
]
}
],
"properties": {
"action": {
"description": "start/stop/pause/continue/restart,以及 set_auto/set_manual(转主连接实现,需 McpManage=1)",
@@ -4596,7 +4778,7 @@
"inputSchema": {
"properties": {
"id": {
"description": "主机 id,取 list_online_hosts / search_hosts 返回的 id 字段",
"description": "主机 id,取 list_hosts 返回的 id 字段",
"type": "string"
},
"timeout_ms": {
@@ -4641,7 +4823,7 @@
"inputSchema": {
"properties": {
"id": {
"description": "主机 id,取 list_online_hosts / search_hosts 返回的 id 字段",
"description": "主机 id,取 list_hosts 返回的 id 字段",
"type": "string"
},
"message": {
@@ -4695,7 +4877,7 @@
"inputSchema": {
"properties": {
"id": {
"description": "主机 id,取 list_online_hosts / search_hosts 返回的 id 字段",
"description": "主机 id,取 list_hosts 返回的 id 字段",
"type": "string"
},
"max_messages": {
@@ -4773,7 +4955,7 @@
"inputSchema": {
"properties": {
"id": {
"description": "主机 id,取 list_online_hosts / search_hosts 返回的 id 字段",
"description": "主机 id,取 list_hosts 返回的 id 字段",
"type": "string"
},
"session_id": {
+1 -1
View File
@@ -175,7 +175,7 @@ Json::Value OutputSchema(Json::Value props, std::initializer_list<const char*> r
}
Json::Value HostIdProp() {
return PropStr(u8"主机 id,取 list_online_hosts / search_hosts 返回的 id 字段");
return PropStr(u8"主机 id,取 list_hosts 返回的 id 字段");
}
Json::Value SessionIdProp() {
+33
View File
@@ -446,6 +446,39 @@ void MakeIdOrIdsRequired(Json::Value& schema) {
schema["anyOf"] = anyOf;
}
void AppendConditionalRequired(Json::Value& schema, const char* prop,
std::initializer_list<const char*> values,
std::initializer_list<const char*> fields) {
Json::Value cond(Json::objectValue);
Json::Value ifSchema(Json::objectValue);
Json::Value reqProp(Json::arrayValue);
reqProp.append(prop);
ifSchema["required"] = reqProp;
if (values.size() > 0) {
Json::Value enums(Json::arrayValue);
for (const char* v : values)
enums.append(v);
Json::Value when(Json::objectValue);
when["enum"] = enums;
Json::Value props(Json::objectValue);
props[prop] = when;
ifSchema["properties"] = props;
}
cond["if"] = ifSchema;
Json::Value thenSchema(Json::objectValue);
Json::Value reqFields(Json::arrayValue);
for (const char* f : fields)
reqFields.append(f);
thenSchema["required"] = reqFields;
cond["then"] = thenSchema;
if (!schema.isMember("allOf") || !schema["allOf"].isArray())
schema["allOf"] = Json::Value(Json::arrayValue);
schema["allOf"].append(cond);
}
std::string PageSummary(const PageWindow& w, const char* unit) {
std::string s = std::string(u8"共 ") + std::to_string(w.total) + std::string(u8" ") + unit;
if (w.total == 0) return s + std::string(u8"。");
+9
View File
@@ -14,6 +14,7 @@
#include <string>
#include <cstdint>
#include <initializer_list>
#include <vector>
class CMy2015RemoteDlg;
@@ -178,6 +179,14 @@ void AppendBatchIdsProp(Json::Value& props);
// 把 inputSchema 的必填约束改成「id 或 ids 二选一」。
void MakeIdOrIdsRequired(Json::Value& schema);
// 往 inputSchema 追加一条条件必填:当 prop 出现且取值在 values 里(values 为空表示
// 只要出现就生效)时,fields 里的字段也必须提供。实现形态是 allOf 里的一条
// {"if":{"properties":{prop:{"enum":[...]}},"required":[prop]},"then":{"required":fields}},
// 从 schema 层面表达只写在描述里的条件约束,模型发参数前就能看到。
void AppendConditionalRequired(Json::Value& schema, const char* prop,
std::initializer_list<const char*> values,
std::initializer_list<const char*> fields);
// 统一的提示文字,例如「共 283 个进程,本次返回第 1-100 条(还有更多,可用 offset 继续取)。」
std::string PageSummary(const PageWindow& w, const char* unit);
+42 -10
View File
@@ -52,6 +52,11 @@ const int kActionTimeoutMs = 12000; // 动作 → 客户端自动回的刷新
// 每步最多 12s,故留 60s 余量;单步等待再按剩余时间收敛。
const int kSessionDeadlineMs = 60000;
// host_inspect 多 aspect 的总预算(软截止):每个 aspect 最坏 5s 就绪 + 12s 列表,10 个
// 全选要 170s,HTTP 调用方会先超时。60 秒后不再下发新的 aspect,正在跑的那个按自身
// 超时跑完;跳过的逐个记入 errors,让调用方看到「没来得及取」而不是一直等。
const int kInspectTotalBudgetMs = 60000;
// 单个包的上限:正常列表远小于此;超过即视为异常,置 clientError 并断开子连接。
const size_t kMaxPacketBytes = 8u * 1024u * 1024u;
@@ -1537,14 +1542,11 @@ std::string BuildKillNetworkConnection(const Json::Value& id, const Json::Value&
if (pidFilter < 0) pidFilter = (int)found->pid;
if (dryRun) {
Json::Value sc(Json::objectValue);
sc["ok"] = true;
sc["dryRun"] = true;
sc["target"] = target;
sc["connection"] = targetJson;
AuditManageAction(parent, ht.dev, toolName, target + " pid=" + std::to_string(pidFilter) +
" result=dry_run");
return BuildStructuredResult(id, sc, "Dry run: target found, nothing was sent");
// 与其它动作工具的 dry_run 同一个形状:ok/dry_run/action/target/state/detail,
// 不再自造 dryRun/target/connection 字段(schema 里没有,模型也得猜)。
return BuildDryRunResult(id, "kill", target, "present", targetJson);
}
// 会话保持:取列表用的是第一条 255,断开后客户端会自动再回一条 255。
@@ -2197,9 +2199,24 @@ std::string BuildHostInspect(const Json::Value& id, const Json::Value& args,
Json::Value errors(Json::objectValue);
std::string summary;
int okCount = 0, failCount = 0;
const auto deadline = std::chrono::steady_clock::now() +
std::chrono::milliseconds(kInspectTotalBudgetMs);
for (const InspectAspect* a : aspects) {
InspectRun run;
if (!summary.empty()) summary += u8";";
// 总预算用尽:剩余的 aspect 不再下发。逐个记入 errors(而不是让整个调用失败),
// 调用方据此知道是「没来得及取」,可以少选几项重试。
if (std::chrono::steady_clock::now() >= deadline) {
Json::Value e(Json::objectValue);
e["code"] = -32001;
e["message"] = std::string("skipped: host_inspect used up its ") +
std::to_string(kInspectTotalBudgetMs / 1000) +
"s budget; retry with fewer aspects or a faster host";
errors[a->name] = e;
failCount++;
summary += std::string(a->what) + u8":跳过(总预算用尽)";
continue;
}
InspectRun run;
if (RunInspectAspect(*a, id, args, parent, run)) {
results[a->name] = run.sc;
okCount++;
@@ -2581,8 +2598,9 @@ static std::string BuildHostControlService(const Json::Value& id, const Json::Va
if (dangerous && !RequireDangerous(id, errJson)) return errJson;
std::string serviceName = Trim(GetStringArg(args, "name"));
if (serviceName.empty()) serviceName = Trim(GetStringArg(args, "service_name"));
if (serviceName.empty())
return BuildError(id, -32602, "Missing required parameter: name (service name)");
return BuildError(id, -32602, "Missing required parameter: name (service name; service_name is an accepted alias)");
HostTool ht;
if (!ResolveHost(id, args, parent, ht, true, errJson)) return errJson;
@@ -3190,7 +3208,9 @@ void AppendTools(Json::Value& tools) {
u8"total 为命中数、totalAll 为该项全部条目数。"
u8"单个 aspect 时顶层就是该项的列表结果(与合并前的旧工具一致);多个 aspect 时汇总在 "
u8"results.<aspect>,某个 aspect 失败只记入 errors.<aspect>、不影响其它 aspect,全部失败才 isError=true。"
u8"每多选一个 aspect 就多一次子连接,耗时线性增长,不需要的不要选。只读。",
u8"每多选一个 aspect 就多一次子连接,耗时线性增长,不需要的不要选;多个 aspect 共用 "
u8"60 秒预算,用尽后不再下发新的 aspect(正在跑的会跑完),跳过的逐个记入 errors"
u8"(code=-32001,message 以 skipped 开头),少选几项重试即可。只读。",
BuildHostInspectInputSchema(), BuildHostInspectOutputSchema());
}
@@ -3238,9 +3258,21 @@ void AppendTools(Json::Value& tools) {
props["name"] = PropStr(u8"服务名(ServiceName,不是显示名),取 host_inspect 的 win32_services / driver_services 项的 name;与 service_name 二选一");
props["service_name"] = PropStr(u8"name 的旧参数名别名(与 name 等价,二选一)");
props["dry_run"] = PropBool(u8"true 时只校验服务存在并返回当前状态,不下发控制命令,默认 false");
// name 与 service_name 等价、二选一:只在 required 里写 id/action 会让两者都缺的
// 调用也“符合 schema”,到执行期才报错;anyOf 让契约与实现一致。
Json::Value schema = MakeSchema(props, { "id", "action" });
Json::Value anyOf(Json::arrayValue);
for (const char* key : { "name", "service_name" }) {
Json::Value alt(Json::objectValue);
Json::Value req(Json::arrayValue);
req.append(key);
alt["required"] = req;
anyOf.append(alt);
}
schema["anyOf"] = anyOf;
AddTool(tools, "host_control_service",
u8"控制在线 Windows 主机的服务:start/stop/pause/continue/restart/set_auto/set_manual。start 等五个动作走主机管理链路:客户端对每次控制都会自动回一份刷新后的服务列表,工具据此复核状态并如实返回 ok;stop 与 restart 归入危险操作,需要同时开启 McpMachineDangerous;restart 先 stop 再 start。set_auto/set_manual 没有主机管理实现,转由主连接版 control_service 处理(ok 只表示已下发、需另查状态;McpManage=0 时返回 -32006)——它们只在 McpMachine=0 时才以 control_service 之名出现在 tools/list。不提供删除服务。dry_run=true 只核实服务并返回当前状态,不下发命令(是否已是目标状态由你按 state 判断);set_auto/set_manual 不支持 dry_run(返回 -32602)。",
MakeSchema(props, { "id", "action" }),
schema,
ActionOutputSchema());
}
{
+284 -45
View File
@@ -283,30 +283,43 @@ const char* kServerInstructions =
u8"2) 工具的可见性与开关\n"
u8"tools/list 只返回当前服务端开关允许的工具:终端(terminal)、远程控制(remote_control)、"
u8"文件传输(file_transfer)、文件写入(file_write)、管理动作(manage)、主机管理(machine)、键盘记录(keylog)、"
u8"远程交谈(chat)各有独立开关。工具不在列表里就是不可用,直接调用返回 -32006;"
u8"远程交谈(chat)各有独立开关。工具不在列表里通常就不可用,直接调用会被拒(-32006 或 -32005);"
u8"例外是下文提到的降级别名(list_processes / list_windows / list_services、operate_window / "
u8"control_service,以及 list_online_hosts / search_hosts / list_all_hosts 等旧名)——"
u8"它们不在列表里但仍可调用。"
u8"当前开关状态可查 get_server_status 的 switches。只读模式(readonly=true)会挡掉大部分写工具,"
u8"但只改服务端本地数据的 host_set_remark / host_set_watch_level 仍会列出,调用时才被拒;"
u8"get_keylog 也始终可见,只读模式下只是它的 clear / set_offline 参数被拒,读取不受影响。\n"
u8"get_keylog 只受 McpKeylog 开关控制(与只读模式无关):开关关闭时它不在列表里;只读模式下"
u8"只是它的 clear / set_offline 参数被拒,读取不受影响。\n"
u8"同一能力存在两套工具时优先用主机管理族:host_inspect(aspects 选 processes / windows / "
u8"win32_services 等,支持 pid/title/status 等服务端过滤,字段更全),list_processes / "
u8"list_windows / list_services 是它在 McpMachine=0 时的降级路径。窗口与服务控制同样只有一套"
u8"名字(需 McpManage=1):McpMachine=0 时是 operate_window / control_service,开启后是 "
u8"host_control_window / host_control_service;后者也接受 close/show 与 set_auto/set_manual"
u8"(转给前一套实现)。\n"
u8"(转给前一套实现)。危险的主机管理动作目前只有两类——冻结/恢复进程、stop/restart 服务——"
u8"另需 McpMachineDangerous=1:工具照常列出,调用时返回 -32006。\n"
u8"\n"
u8"3) 错误码与动作\n"
u8"-32002 主机离线或不存在:先刷新主机列表再选,不要拿旧快照反复重试。\n"
u8"-32003 主机忙:同一台主机同一时刻只允许一个请求在飞(列表、截屏、文件、管理动作共用这一道锁,"
u8"文件传输会话另有一道互斥),并发重试只会继续被拒;message 末尾会点名占用者与已持续时长,"
u8"用 mcp_list_sessions 可看全部会话,确需打断(例如上一条请求已无意义)用 mcp_cancel_session 释放。\n"
u8"用 mcp_list_sessions 可看全部会话。确需打断用 mcp_cancel_session,但它只能取消在飞调用(kind=call);"
u8"持久会话要按类型关闭(id 与 session_id 都要给):terminal → terminal_close,remote_control → remote_close,"
u8"chat → chat_close。pending / file_transfer 是某次在飞调用的等待态,取消那次调用就一并释放。\n"
u8"-32004 命令未能送达主机:多半是链路瞬断,可重试一次。\n"
u8"-32005 该主机不支持这项能力:换主机或换工具,改参数没有用。\n"
u8"-32006 策略拒绝:开关未开或只读模式,重试无效,需要管理员改服务端配置。\n"
u8"-32006 策略拒绝:开关未开、只读模式,或目标端能力不足(老客户端不声明 CLIENT_CAP_V2 时,"
u8"download_file / upload_file / read_file / copy_files_c2c 会返回 -32006),重试无效:"
u8"前者需管理员改服务端配置,后者需升级客户端。\n"
u8"-32007 不在命令白名单:换成白名单内的命令,重试无效。\n"
u8"-32012 参数被校验拒绝(命令里的 shell 元字符、控制字符等):按 message 修正参数后重试。"
u8"历史版本用 -32008 表示同一语义,遇到时按同样方式处理。\n"
u8"-32009 目标不存在(文件/目录等):先列一次确认目标,再重试。\n"
u8"-32001 超时:可加大 timeout_ms 重试一次;持续超时说明主机卡住。\n"
u8"-32001 多为超时,也可能是工具自身失败或已被取消:先看 message。是超时时,工具支持 timeout_ms "
u8"就先加大重试一次,不支持就缩小范围(分页、限定目录/单台)再试;子连接/会话没建立、同一主机"
u8"反复超时通常重试无效(主机卡住、链路断、老客户端不认命令),先用 mcp_list_sessions 观察;"
u8"message 写 Request cancelled 的表示客户端已中止,可直接重试;http_probe 解析失败、"
u8"目标端未确认写入等其他 -32001 按 message 处理,加大 timeout_ms 没用。\n"
u8"-32800 请求被取消:这是客户端自己取消(notifications/cancelled / mcp_cancel_session / 连接断开)"
u8"导致的中止,不是主机故障;主机占用已释放,可以直接重试。\n"
u8"-32602 参数错误:按 message 修正后重试。\n"
@@ -317,6 +330,7 @@ const char* kServerInstructions =
u8"文件:list_files 列盘(省略 path)或列目录 → search_file 按名字查找(递归深度 32、最多 1 万条,"
u8"从盘符根扫描很慢且易截断,尽量指定具体目录)→ 看文本内容用 read_file(按字节解码,自动识别 UTF-8/GBK,"
u8"offset=-N 看尾部,不要用 type/Get-Content 读配置和日志)→ download_file 取回、upload_file 送到目标。"
u8"注意 local_dir / local_path 指 MCP 服务端(主控)所在机器的本地路径,不是模型或用户所在机器的路径。"
u8"整理目标机上的东西用 delete_path / move_path / create_folder(需 McpFileWrite 开关),"
u8"它们的 ok 同样只代表客户端回了完成包,真实结果看 verified(true=复核确认生效、"
u8"false=复核确认未生效、null=复核没做成);删除不可恢复,recursive 必须显式传 true。"
@@ -328,7 +342,9 @@ const char* kServerInstructions =
u8"remote_mouse / remote_keyboard 用归一化坐标(0..1)操作 → 必须 remote_close 释放会话,闲置会话会被回收。"
u8"要防止真人操作打断自动化时用 remote_block_input 锁定对端键鼠(Windows/Android;必须带 max_block_ms,到期自动解除;"
u8"客户端无管理员权限时 Windows 会让 BlockInput 静默失败,成功只代表命令已送达)。\n"
u8"命令执行:exec_command 一次性取输出(受白名单约束)。terminal_exec 无需先 terminal_open:带 command 时"
u8"命令执行:exec_command 一次性取输出(受白名单约束);同一主机已有持久终端会话时它会被 -32003 拒绝"
u8"(改用 terminal_exec 复用该会话,或 terminal_close(id, session_id) 立刻关掉;空闲会话 300s 后会在下一次"
u8" exec_command / terminal_* 调用时自动回收)。terminal_exec 无需先 terminal_open:带 command 时"
u8"自动复用或创建该主机的持久会话(cwd/环境变量跨命令保持,闲置 300 秒回收),结果里带回 session_id,"
u8"后续轮询用它;只有需要显式管理会话时才用 terminal_open / terminal_close。\n"
u8"HTTP 探测:探主机本机或同网段的接口用 http_probe(只收私网/回环 IP 与 localhost,不给域名,"
@@ -344,7 +360,8 @@ const char* kServerInstructions =
u8"lnx(LNX):不支持服务、注册表、键日志、文件搜索/删除/移动/建目录、"
u8"窗口列表(list_windows)与窗口信息(get_foreground_window)、网络连接列表与断开"
u8"(list_network_connections / kill_network_connection)、"
u8"块输入、host_* 全族、chat_* 全族、operate_window、power_action、uninstall_host。远程控制与截屏要求目标机"
u8"块输入、host_* 全族(host_set_remark / host_set_watch_level 除外,它们只改服务端本地数据,"
u8"任何平台都可用)、chat_* 全族、operate_window、power_action、uninstall_host。远程控制与截屏要求目标机"
u8"有 X11/Xorg(或 XWayland)桌面,纯 Wayland 或无桌面的服务器不行。\n"
u8"mac(MAC):在 lnx 的基础上,还不支持远程控制全族(remote_open / remote_close / "
u8"remote_mouse / remote_keyboard / remote_clipboard)、get_screenshot、"
@@ -369,7 +386,9 @@ const char* kServerInstructions =
u8"(客户端未实现 SYSTEM 等命令)。\n"
u8"copy_files_c2c 是唯一有方向性的工具:源端 src_id 必须是 win,目标端 dst_id 可以是 "
u8"win / lnx / mac。Linux 和 macOS 只能当接收方,不能当发送方(反向不支持)。\n"
u8"这些不支持的组合会立刻返回 -32005,不会白等超时;反之,遇到超时不要当成平台不支持。\n"
u8"这些不支持的组合多数会立刻返回 -32005;少数要等子连接才暴露的(老客户端不认命令等)"
u8"可能表现为 -32001 超时,平台门禁 McpPlatformGuard=0 关闭时也会这样。反之,遇到超时"
u8"也别直接当成平台不支持,先按上面的矩阵确认平台。\n"
u8"\n"
u8"6) 安全约定\n"
u8"写操作前先读一次现状,动作后再用读工具复核;删改类工具的 ok 只表示命令已送达客户端,不代表成功。"
@@ -545,17 +564,38 @@ Json::Value ParseDriveList(const std::vector<BYTE>& data, UINT cp) {
return arr;
}
// 文件管理通道上的名字解码。协议约定是客户端 ANSI/GBK(Windows 的 FindFirstFileA、
// Linux/macOS 的 common/FileManager.h 都按 GBK 收发),但 POSIX 客户端的 utf8ToGbk
// 遇到 GBK 无法表示的字符会原样返回 UTF-8。cp=CP_UTF8(POSIX 调用方)时先按 GBK
// 严格解码:能解开就当 GBK(线上常态);解不开说明客户端透传了 UTF-8,按 UTF-8 用。
// 反过来「先试 UTF-8」不行——约 18% 的常用汉字 GBK 双字节恰好也是合法 UTF-8
// (如 目录 = C4 BF C2 BC = "Ŀ¼"),会解成拉丁字母。已知限制:透传的 UTF-8
// 字节若恰好也是合法 GBK(例如 emoji)仍会被当 GBK 解,客户端侧编码转换本身不可逆。
std::string DecodeListingName(const char* s, UINT cp) {
if (cp == CP_UTF8) {
if (MultiByteToWideChar(936, MB_ERR_INVALID_CHARS, s, -1, NULL, 0) > 0)
return ToUtf8(s, 936);
return std::string(s);
}
return ToUtf8(s, cp);
}
// 解析 TOKEN_FILE_LIST 缓冲(data[0]=token,其后为
// [attr:1][filename\0][sizeHigh:4][sizeLow:4][ftLastWriteTime:8] 记录)。
// 文件名为客户端 ANSI(编码由 cp 指定);attr 非 0 表示目录(FILE_ATTRIBUTE_DIRECTORY)。
Json::Value ParseFileList(const std::vector<BYTE>& data, int maxEntries, UINT cp) {
// 文件名为客户端 ANSI(编码由 cp 指定,见 DecodeListingName);attr 非 0 表示目录
// (FILE_ATTRIBUTE_DIRECTORY)。
// maxEntries 只限制构建出的条目数:超出时提前返回,并通过 truncated 告知数据里还有
// 更多记录(调用方据此区分「目录就这么大」和「服务端解析上限到了」)。
Json::Value ParseFileList(const std::vector<BYTE>& data, int maxEntries, UINT cp,
bool* truncated = nullptr) {
Json::Value arr(Json::arrayValue);
if (truncated) *truncated = false;
if (data.size() < 2) return arr;
const char* p = (const char*)data.data();
size_t len = data.size();
size_t off = 1;
int count = 0;
while (off + 1 <= len && count < maxEntries) {
while (off + 1 <= len) {
bool isDir = (p[off] & FILE_ATTRIBUTE_DIRECTORY) != 0;
off += 1;
@@ -563,6 +603,10 @@ Json::Value ParseFileList(const std::vector<BYTE>& data, int maxEntries, UINT cp
size_t nlen = BoundedStrlen(name, len - off);
if (nlen >= len - off) break;
if (nlen == 0) break; // 空记录 = 尾部零填充(LocalAlloc 对齐),停止解析
if (count >= maxEntries) { // 还有记录但已达上限:数据不完整
if (truncated) *truncated = true;
break;
}
off += nlen + 1;
if (off + 16 > len) break;
@@ -580,7 +624,7 @@ Json::Value ParseFileList(const std::vector<BYTE>& data, int maxEntries, UINT cp
Json::Int64 mtime = (Json::Int64)(ft / 10000000ULL) - 11644473600LL;
Json::Value item(Json::objectValue);
item["name"] = ToUtf8(name, cp);
item["name"] = DecodeListingName(name, cp);
item["isDir"] = isDir;
item["size"] = (Json::UInt64)size;
item["mtime"] = mtime;
@@ -1927,6 +1971,10 @@ Json::Value BuildGetScreenshotInputSchema() {
Json::Value required(Json::arrayValue);
required.append("id");
schema["required"] = required;
// region 需 width/height、window 需 hwnd(handler 会以 -32602 拒);monitor 有默认 0,
// 无需条件。x/y 在 region 下可省略(按 0),故不进 then。
AppendConditionalRequired(schema, "mode", { "region" }, { "width", "height" });
AppendConditionalRequired(schema, "mode", { "window" }, { "hwnd" });
return schema;
}
@@ -1959,7 +2007,9 @@ Json::Value BuildListFilesInputSchema() {
Json::Value pathProp(Json::objectValue);
pathProp["type"] = "string";
pathProp["description"] = u8"要列举的目录路径(如 C:\\Windows);省略或传空则返回驱动器列表";
pathProp["description"] = u8"要列举的目录路径(如 C:\\Windows 或 /etc)。省略或传空返回驱动器列表;"
u8"Windows 上 \".\"、\"/\"、\"\\\\\" 视同省略;Linux/macOS 上 \"/\" 是根目录,"
u8"按真实目录列举。";
props["path"] = pathProp;
AppendBatchIdsProp(props);
@@ -2017,6 +2067,13 @@ Json::Value BuildListFilesOutputSchema() {
fileItems["properties"] = fileProps;
filesProp["items"] = fileItems;
props["files"] = filesProp;
// 目录条目超过解析上限(10 万条)时为 true,此时 total 只是上限内的数量。
Json::Value truncatedProp(Json::objectValue);
truncatedProp["type"] = "boolean";
truncatedProp["description"] = u8"目录条目超过服务端解析上限(100000 条)时为 true;"
u8"仅在返回 files 时可能出现,此时 total 不是真实总数。";
props["truncated"] = truncatedProp;
AppendPageOutputProps(props);
Json::Value schema(Json::objectValue);
@@ -2197,7 +2254,7 @@ std::string BuildToolsListResult(const Json::Value& id) {
{
Json::Value tool(Json::objectValue);
tool["name"] = "get_screenshot";
tool["description"] = u8"截取指定在线主机的一帧画面,返回 base64 编码的 JPEG 图片(image 对象含 mimeType/data/width/height)。支持 Windows 与带 X11 桌面的 Linux 客户端(能力位 CLIENT_CAP_SCREEN_PREVIEW),主连接 RPC、一次性返回。Android 客户端用无障碍服务 takeScreenshot 抓屏(Android 11+ 且开启无障碍服务,此时登录会声明该能力位;只支持 mode=screen)。mode 可选 screen(默认,整虚拟桌面)/region(指定矩形)/window(指定 hwnd)/monitor(指定显示器);后三种默认按源尺寸 1:1 原生分辨率抓取(适合 OCR/视觉读字),需要较新的 Windows 客户端(CLIENT_CAP_SCREEN_REGION,否则 -32005),结果在 structuredContent.capture 里回报实际源矩形与缩放比例。";
tool["description"] = u8"截取指定在线主机的一帧画面,返回 base64 编码的 JPEG 图片:图片在 content 的 image 块(data 为 base64,mimeType=image/jpeg);structuredContent.image 只有 mimeType/width/height/bytes 元数据,不含图片数据。支持 Windows 与带 X11 桌面的 Linux 客户端(能力位 CLIENT_CAP_SCREEN_PREVIEW),主连接 RPC、一次性返回。Android 客户端用无障碍服务 takeScreenshot 抓屏(Android 11+ 且开启无障碍服务,此时登录会声明该能力位;只支持 mode=screen)。mode 可选 screen(默认,整虚拟桌面)/region(指定矩形)/window(指定 hwnd)/monitor(指定显示器);后三种默认按源尺寸 1:1 原生分辨率抓取(适合 OCR/视觉读字),需要较新的 Windows 客户端(CLIENT_CAP_SCREEN_REGION,否则 -32005),结果在 structuredContent.capture 里回报实际源矩形与缩放比例。";
tool["inputSchema"] = BuildGetScreenshotInputSchema(); // { id } 必填 + max_width 可选
tool["outputSchema"] = BuildScreenshotOutputSchema();
@@ -2221,7 +2278,7 @@ std::string BuildToolsListResult(const Json::Value& id) {
{
Json::Value tool(Json::objectValue);
tool["name"] = "list_files";
tool["description"] = u8"列举指定在线主机的目录。省略或空 path 返回驱动器列表(drives);给定 path 返回该目录一层内的文件/子目录(files,最多 500 条,含 name/isDir/size/mtime)。只读。";
tool["description"] = u8"列举指定在线主机的目录。省略或空 path 返回驱动器列表(drives);给定 path 返回该目录一层内的文件/子目录(files,含 name/isDir/size/mtime),整目录解析后按 limit/offset 分页(默认 100 条、上限 1000 条,total/hasMore 是真实的目录条目数;目录超过 10 万条时按上限截断并返回 truncated=true)。Windows 上 \".\"/\"/\"/\"\\\\\" 视同省略 path;Linux/macOS 上 \"/\" 是根目录。只读。";
tool["inputSchema"] = BuildListFilesInputSchema();
tool["outputSchema"] = BuildListFilesOutputSchema();
@@ -2405,7 +2462,7 @@ std::string BuildToolsListResult(const Json::Value& id) {
{
Json::Value tool(Json::objectValue);
tool["name"] = "mcp_cancel_session";
tool["description"] = u8"取消在飞请求并尽快释放主机占用。给 request_id(tools/call 的 JSON-RPC id,类型要与调用时一致)精确取消一次调用,或按 id(主机)与 session_id 取消匹配的调用(两个都给则必须同时匹配)。工具层的等待在 ≤500ms 内退出并走既有清理路径;本工具最多等 2s,返回 cancelled(取消个数)、released(是否已释放占用)、waited_ms 与 matched(匹配到的会话)。被取消的请求以 -32800 结束。等价于对 SSE 流发 notifications/cancelled。";
tool["description"] = u8"取消在飞请求并尽快释放主机占用。只能取消 kind=call 的在飞调用:给 request_id(tools/call 的 JSON-RPC id,类型要与调用时一致)精确取消一次,或按 id(主机,必须非 0)/ session_id 取消匹配的调用(两个都给则必须同时匹配)。取消一次卡住的调用会连带释放它持有的 pending / file_transfer 等待;持久会话本身不会被关闭,terminal / remote_control / chat 分别用 terminal_close / remote_close / chat_close(两者都要同时给 id 与 session_id)。工具层的等待在 ≤500ms 内退出并走既有清理路径;本工具最多等 2s,返回 cancelled(真正取消的调用个数,不含本工具自身)、released(这些调用是否已释放占用)、waited_ms 与 matched(匹配到的所有会话,每项带 cancellable)。被取消的请求以 -32800 结束。等价于对 SSE 流发 notifications/cancelled。";
Json::Value inputSchema(Json::objectValue);
inputSchema["type"] = "object";
@@ -2426,6 +2483,17 @@ std::string BuildToolsListResult(const Json::Value& id) {
sidProp["description"] = u8"会话 id(terminal/remote_control/chat 的 session_id):只取消该会话上的在飞请求";
props["session_id"] = sidProp;
inputSchema["properties"] = props;
// 三个选择器至少给一个:原 schema 是 required:[],模型发 {} 才会在 handler 里被 -32602 打回。
Json::Value anyOf(Json::arrayValue);
const char* selectors[] = { "request_id", "id", "session_id" };
for (const char* sel : selectors) {
Json::Value alt(Json::objectValue);
Json::Value req(Json::arrayValue);
req.append(sel);
alt["required"] = req;
anyOf.append(alt);
}
inputSchema["anyOf"] = anyOf;
inputSchema["required"] = Json::Value(Json::arrayValue);
tool["inputSchema"] = inputSchema;
@@ -2436,7 +2504,7 @@ std::string BuildToolsListResult(const Json::Value& id) {
outProps["cancelled"] = cancelledProp;
Json::Value releasedProp(Json::objectValue);
releasedProp["type"] = "boolean";
releasedProp["description"] = u8"2s 内匹配的会话是否已从服务端表中消失(主机已松开)";
releasedProp["description"] = u8"2s 内被取消的在飞调用(kind=call,不含本工具自身)是否已从服务端表中消失(主机已松开)";
outProps["released"] = releasedProp;
Json::Value waitedProp(Json::objectValue);
waitedProp["type"] = "integer";
@@ -2515,7 +2583,7 @@ std::string BuildToolsListResult(const Json::Value& id) {
{
Json::Value tool(Json::objectValue);
tool["name"] = "remote_open";
tool["description"] = u8"在指定在线 Windows、Linux 或 Android 主机上建立远程控制会话(隐藏屏幕子连接)并返回 session_id、抓屏帧尺寸(screen_w/screen_h)与目标(target)。默认推整屏/整虚拟桌面(可能等比缩放);可用 window_hwnd 只推一个窗口,或用 region 只推一个矩形区域,带宽、延迟和点击精度都更好,此时归一化坐标 0..1 相对该目标帧。后续 remote_mouse/remote_keyboard 用归一化坐标(0..1)注入输入,用毕须 remote_close。Linux 需要 X11/Xorg(或 XWayland)桌面,纯 Wayland 会话无法抓屏/注入;window_hwnd/region 仅支持声明 CLIENT_CAP_WINDOW_INFO 的新 Windows 客户端。Windows 多显示器下整屏目标需要新版客户端(整虚拟桌面抓屏),老客户端会被拒绝;window 目标不依赖虚拟桌面抓屏,不受此限。Android 主机只支持整屏目标,输入被翻译成触摸手势与全局动作(见 remote_mouse / remote_keyboard);抓屏依赖客户端已授权录屏(MediaProjection),未授权时 remote_open 会一直等不到屏幕子连接,注入还依赖无障碍服务在跑(未开启时命令照样下发但不生效,且没有回执)。";
tool["description"] = u8"在指定在线 Windows、Linux 或 Android 主机上建立远程控制会话(隐藏屏幕子连接)并返回 session_id、抓屏帧尺寸(screen_w/screen_h)与目标(target)。默认推整屏/整虚拟桌面(可能等比缩放);可用 window_hwnd 只推一个窗口,或用 region 只推一个矩形区域,带宽、延迟和点击精度都更好,此时归一化坐标 0..1 相对该目标帧。后续 remote_mouse/remote_keyboard 用归一化坐标(0..1)注入输入,用毕须 remote_close。Linux 需要 X11/Xorg(或 XWayland)桌面,纯 Wayland 会话无法抓屏/注入(这类主机直接返回 -32005);window_hwnd/region 仅支持声明 CLIENT_CAP_WINDOW_INFO 的新 Windows 客户端。Windows 多显示器下整屏目标需要新版客户端(整虚拟桌面抓屏),老客户端会被拒绝;window 目标不依赖虚拟桌面抓屏,不受此限。Android 主机只支持整屏目标,输入被翻译成触摸手势与全局动作(见 remote_mouse / remote_keyboard);抓屏依赖客户端已授权录屏(MediaProjection),未授权时 remote_open 会一直等不到屏幕子连接,注入还依赖无障碍服务在跑(未开启时命令照样下发但不生效,且没有回执)。";
tool["inputSchema"] = BuildRemoteOpenInputSchema();
tool["outputSchema"] = BuildRemoteOpenOutputSchema();
tools.append(tool);
@@ -3589,6 +3657,7 @@ static std::string BuildRemoteWin32Error(const Json::Value& id, DWORD win32err,
// tools/call:list_files(列盘走 COMMAND_LIST_DRIVE→TOKEN_DRIVE_LIST;
// 列目录走 COMMAND_LIST_DRIVE 开子链接后,再下发 COMMAND_LIST_FILES→TOKEN_FILE_LIST)
static const int kListFilesMaxEntries = 100000; // 解析上限,仅为兜住病态目录
std::string BuildListFiles(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) {
uint64_t devId = 0;
std::string err;
@@ -3600,16 +3669,32 @@ std::string BuildListFiles(const Json::Value& id, const Json::Value& args, CMy20
return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId));
std::string path = GetStringArg(args, "path");
bool listDrives = path.empty() || path == "." || path == "/" || path == "\\";
// 目录路径/文件名编码按 clientType 判定:Windows 走 A 接口(FindFirstFileA 等)= 客户端
// ANSI(GBK/936),不随 CLIENT_CAP_UTF8 转 UTF-8;LNX/MAC 文件系统天然 UTF-8。不能用
// GetClientEncoding——它按能力位返回 CP_UTF8,会误解 Windows 客户端的 GBK 文件名。
// 编码:文件管理通道在线上是客户端 ANSI/GBK —— Windows 客户端走 A 接口
// (FindFirstFileA);Linux/macOS 客户端在 common/FileManager.h 里对收到的路径做
// gbkToUtf8、对发出的名字做 utf8ToGbk,与 download_file/upload_file 的 936 约定
// 一致。不能用 GetClientEncoding——它按能力位返回 CP_UTF8,会误解线上的 GBK 字节。
// 名字解析对 POSIX 用 CP_UTF8 作「先按 GBK 严格解、解不开再当 UTF-8」的开关
// (客户端 utf8ToGbk 遇到 GBK 无法表示的字符会原样透传 UTF-8),见 DecodeListingName。
CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE);
UINT cp = (clientType == "LNX" || clientType == "MAC") ? CP_UTF8 : 936;
const bool posixFs = (clientType == "LNX" || clientType == "MAC");
const UINT nameCp = posixFs ? CP_UTF8 : 936;
// 下发前把 UTF-8 path 转成客户端 ANSI(空/./\/\\ 为 ASCII,转换后不变),OnDriveList 直接用。
std::string ansiPath = ToAnsi(path, cp);
// Windows 上 "."、"/"、"\\" 是「列盘」的历史写法;POSIX 上 "/" 是真实目录
// (根目录),不能当列盘。列盘统一用空 path 下发给 OnDriveList。
const bool listDrives = path.empty() ||
(!posixFs && (path == "." || path == "/" || path == "\\"));
std::string ansiPath;
if (!listDrives) {
if (posixFs) {
// 客户端对收到的路径先做 gbkToUtf8:能转 GBK 就发 GBK;含 GBK 表示不了的
// 字符(韩文等)时客户端 iconv 会失败并原样使用输入,所以这里直接发 UTF-8,
// 两边才能对上(ToAnsi 在这里会静默替换成 '?')。
if (!Utf8ToCpExact(path, 936, ansiPath)) ansiPath = path;
} else {
ansiPath = ToAnsi(path, 936);
}
}
CMcpServer& mcp = CMcpServer::Instance();
if (!mcp.BeginPending(devId, "list_files", ansiPath))
@@ -3632,11 +3717,13 @@ std::string BuildListFiles(const Json::Value& id, const Json::Value& args, CMy20
Json::Value drives(Json::arrayValue);
Json::Value files(Json::arrayValue);
bool truncated = false;
if (listDrives) {
drives = ParseDriveList(data, cp);
drives = ParseDriveList(data, nameCp);
} else {
// 服务端按 500 条截断(避免子连接/JSON 过大),再按 limit/offset 取窗口。
files = ParseFileList(data, 500, cp);
// 整目录解析后再分页:先按 500 条截断会让 total/hasMore 说谎(超过 500 条的
// 目录永远翻不到后面的条目)。上限 100000 条只为兜住病态目录。
files = ParseFileList(data, kListFilesMaxEntries, nameCp, &truncated);
}
PageWindow page = ResolvePageWindow(args);
@@ -3645,8 +3732,12 @@ std::string BuildListFiles(const Json::Value& id, const Json::Value& args, CMy20
Json::Value result(Json::objectValue);
Json::Value structuredContent(Json::objectValue);
if (listDrives) structuredContent["drives"] = pageItems;
else structuredContent["files"] = pageItems;
if (listDrives) {
structuredContent["drives"] = pageItems;
} else {
structuredContent["files"] = pageItems;
structuredContent["truncated"] = truncated; // 一律带出,便于按 schema 校验
}
WritePageFields(structuredContent, page);
result["structuredContent"] = structuredContent;
@@ -3654,6 +3745,13 @@ std::string BuildListFiles(const Json::Value& id, const Json::Value& args, CMy20
Json::Value item(Json::objectValue);
item["type"] = "text";
item["text"] = listDrives ? PageSummary(page, u8"个驱动器") : PageSummary(page, u8"个条目");
if (truncated)
item["text"] = item["text"].asString() +
std::string(u8"目录条目超过服务端解析上限 ") +
std::to_string(kListFilesMaxEntries) +
std::string(u8" 条,total 只是上限内的数量;请缩小目录范围") +
(posixFs ? std::string(u8"。")
: std::string(u8"或改用 search_file。"));
content.append(item);
result["content"] = content;
result["isError"] = false;
@@ -4059,6 +4157,34 @@ static bool HasPosixBackgroundAmpersand(const std::string& s) {
return false;
}
static const int kTermIdleTimeoutSec = 300; // 持久终端 idle 回收超时(秒)
// 终端会话的简短标签(-32003 与 mcp_list_sessions 共用同一写法,避免两处漂移)。
static std::string TerminalLabel(const std::string& sessionId) {
return sessionId.empty() ? std::string("exec_command")
: std::string("terminal session_id=") + sessionId;
}
// exec_command 被终端挡住时的完整报错:带会话名/session_id 与闲置/已跑时长,并给出正确出路。
// 不复用 BusyMessage:那边的描述顺序会优先报 pending/文件传输,可能把别的占用者算到终端头上。
static std::string TerminalBusyMessage(uint64_t devId) {
for (const auto& s : CMcpServer::Instance().ListSessions()) {
if (s.kind != "terminal" || s.device != devId) continue;
std::string detail = " (" + TerminalLabel(s.sessionId);
if (s.idleMs >= 0) detail += ", idle=" + std::to_string(s.idleMs / 1000) + "s";
if (s.elapsedMs >= 0) detail += ", elapsed=" + std::to_string(s.elapsedMs / 1000) + "s";
detail += ")";
if (s.tool == "exec_command") {
return "Device busy: another exec_command is still running for this host" + detail +
"; wait for it to finish, or cancel that call with mcp_cancel_session(request_id)";
}
return "Device busy: a persistent terminal session is already open for this host" + detail +
"; reuse it with terminal_exec, or close it with terminal_close(id, session_id); "
"idle sessions are reclaimed after 300s";
}
return "Device busy: a terminal session is already active for this host";
}
// tools/call:exec_command(Windows/Linux 一次性远程命令:主连接 COMMAND_SHELL → 子连接终端 →
// 哨兵命令行 → 收集 stdout + exit_code → 关子链接)。安全门:只读默认 + 白名单 + 审计。
std::string BuildExecCommand(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) {
@@ -4112,8 +4238,12 @@ std::string BuildExecCommand(const Json::Value& id, const Json::Value& args, CMy
std::string nonce = GenerateRandomToken().substr(0, 8);
// 持久终端闲置回收原先只在 terminal_open/exec/close/http_probe 入口触发;exec_command
// 不走这些入口,于是「开过一次 terminal_exec → 之后 exec_command 永远 -32003」。
// 这里补一次 sweep,并让报错带上 session_id 与替代路径。
mcp.SweepIdleTerminals(kTermIdleTimeoutSec);
if (!mcp.BeginTermPending(devId, command, nonce))
return BuildError(id, -32003, "Device busy: a terminal session is already active for this host");
return BuildError(id, -32003, TerminalBusyMessage(devId));
// 主连接下发 COMMAND_SHELL,客户端建立 shell 子连接并回 TOKEN_*_START。
BYTE cmd = COMMAND_SHELL;
@@ -4474,9 +4604,9 @@ std::string BuildGetServerStatus(const Json::Value& id, CMy2015RemoteDlg* parent
status["blocked_auth_ips"] = blockedIps;
Json::Value result(Json::objectValue);
Json::Value structuredContent(Json::objectValue);
structuredContent["status"] = status;
result["structuredContent"] = structuredContent;
// outputSchema 声明的就是顶层字段;不要再套一层 "status",否则按 schema 取字段
// (structuredContent.version 等)的客户端拿不到任何东西。
result["structuredContent"] = status;
std::string text = std::string(BRAND_APP_NAME) + " v" + VERSION_STR +
std::string(u8",已运行 ") + std::to_string((long long)status["uptime_sec"].asInt64()) +
@@ -4587,6 +4717,10 @@ static std::string BuildMcpCancelSession(const Json::Value& id, const Json::Valu
const bool hasDev = args.isObject() && args.isMember("id");
if (hasDev && !ReadUInt64Arg(args, "id", devId))
return BuildError(id, -32602, "id must be a decimal host id string");
// "0" 能通过整数校验,但会让设备过滤失效(matches 里 devId!=0 才比),
// 变成「取消全服所有在飞调用」——宁可拒绝。
if (hasDev && devId == 0)
return BuildError(id, -32602, "id must be a non-zero host id string");
const std::string sessionId = GetStringArg(args, "session_id");
if (reqIdKey.empty() && !hasDev && sessionId.empty())
@@ -4603,8 +4737,10 @@ static std::string BuildMcpCancelSession(const Json::Value& id, const Json::Valu
};
CMcpServer& srv = CMcpServer::Instance();
const auto self = CurrentMcpCall(); // 取消工具自身也在这张表里,不算「匹配到」也不取消
Json::Value matched(Json::arrayValue);
for (const auto& s : srv.ListSessions()) {
if (self && s.kind == "call" && s.idKey == self->idKey) continue;
if (!matches(s)) continue;
Json::Value o(Json::objectValue);
if (s.device != 0) o["host_id"] = std::to_string(s.device);
@@ -4612,6 +4748,7 @@ static std::string BuildMcpCancelSession(const Json::Value& id, const Json::Valu
o["tool"] = s.tool;
if (!s.sessionId.empty()) o["session_id"] = s.sessionId;
if (!s.requestId.empty()) o["request_id"] = s.requestId;
o["cancellable"] = (s.kind == "call"); // 本工具只能打断在飞调用
matched.append(o);
}
@@ -4626,6 +4763,10 @@ static std::string BuildMcpCancelSession(const Json::Value& id, const Json::Valu
while (waitedMs < kCancelWaitMs) {
bool stillThere = false;
for (const auto& s : srv.ListSessions()) {
// 只轮询 kind=call:取消动不到持久会话,它们赖在表里不代表「在收尾」。
// 也要跳过取消工具自身——它一直在表里,否则 released 永远等不到 true。
if (s.kind != "call") continue;
if (self && s.idKey == self->idKey) continue;
if (matches(s)) { stillThere = true; break; }
}
if (!stillThere) { released = true; break; }
@@ -4642,7 +4783,23 @@ static std::string BuildMcpCancelSession(const Json::Value& id, const Json::Valu
std::string text;
if (cancelled == 0) {
text = u8"没有匹配的在飞请求:可能已经结束,或 request_id 与列表里的值不一致。";
if (matched.empty()) {
text = u8"没有匹配的在飞请求:可能已经结束,或 request_id 与列表里的值不一致。";
} else {
// 只匹配到持久会话/挂起表项:本工具只能取消 kind=call,说清楚下一步该用哪个工具。
std::string kinds;
for (const auto& m : matched) {
const std::string k = m["kind"].asString();
if (kinds.find(k) == std::string::npos) {
if (!kinds.empty()) kinds += "/";
kinds += k;
}
}
text = u8"匹配到 " + std::to_string((int)matched.size()) + u8" 个会话(kind=" + kinds +
u8"),但都不是可取消的在飞调用(kind=call)。持久会话请按类型关闭(id 与 session_id 都要给):"
u8"terminal → terminal_close,remote_control → remote_close,chat → chat_close;"
u8"pending / file_transfer 是所属在飞调用的等待态,取消那次调用即可一并释放。";
}
} else if (released) {
text = std::string(u8"已取消 ") + std::to_string(cancelled) + u8" 个在飞请求," +
std::to_string(waitedMs) + u8" ms 内已释放占用;被取消的请求会收到 -32800。";
@@ -4666,7 +4823,6 @@ static std::string BuildMcpCancelSession(const Json::Value& id, const Json::Valu
// ===== P4:持久远程终端(terminal_open / terminal_exec / terminal_close)=====
static const int kTermIdleTimeoutSec = 300; // 持久终端 idle 回收超时(秒)
static const int kTermTombstoneSec = 600; // 「终端被销毁」墓碑保留时长(秒),供后续报错文案用
// 超时轮询(P0-2):超时不再销毁会话,改为返回部分输出 + 可继续轮询,因此需要三个上限。
static const int kTermMaxDataBytes = 8 * 1024 * 1024; // 单条命令原始输出硬上限(超出丢最旧字节)
@@ -4811,6 +4967,17 @@ Json::Value BuildTerminalExecInputSchema() {
Json::Value required(Json::arrayValue);
required.append("id");
schema["required"] = required;
// 执行(带 command)可省略 session_id,轮询(不带 command)必须带 session_id;
// 两者都没有时 handler 直接 -32602。用 anyOf 把这条只写在描述里的约束落到 schema。
Json::Value anyOf(Json::arrayValue);
for (const char* key : { "command", "session_id" }) {
Json::Value alt(Json::objectValue);
Json::Value req(Json::arrayValue);
req.append(key);
alt["required"] = req;
anyOf.append(alt);
}
schema["anyOf"] = anyOf;
return schema;
}
@@ -5426,6 +5593,21 @@ std::string BuildRemoteOpen(const Json::Value& id, const Json::Value& args, CMy2
if (!ResolveScreenCtrlSessionHost(id, args, parent, devId, ctx, errJson))
return errJson;
// 能力位前置:Linux 的抓屏与注入都走 X11(Xorg/XWayland),客户端只在 DISPLAY 可用时
// 才在登录里声明 CLIENT_CAP_SCREEN_PREVIEW;声明了能力位(非空 caps)却没有这一位,
// 说明是纯 Wayland/无 X11 的会话,抓不到帧也注入不了——提前返回 -32005,免得白等
// timeout_ms 再报「子连接超时」,还留下一次 web-triggered 标记的清理。老客户端
// (caps 为空)无从判定,与多显示器门一样按放行处理(老的 COMMAND_SCREEN_SPY 链路仍可用)。
// Android 不能套这个门:APK 的 SCREEN_PREVIEW 位只代表 API 30+ 且无障碍在运行(用于
// get_screenshot 的 takeScreenshot),而远程控制抓屏走 MediaProjection、注入走
// dispatchGesture——没有这一位的主机远程控制仍可能可用。
CString hostClientType = ctx->GetAdditionalData(RES_CLIENT_TYPE);
const bool declaresCaps = !ctx->GetClientData(ONLINELIST_CAPABILITIES).IsEmpty();
if (declaresCaps && hostClientType == "LNX" && !ctx->SupportsScreenPreview())
return BuildError(id, -32005,
"Remote control requires screen preview capability (X11/Xorg desktop on Linux); "
"this host does not declare it");
// ---- 帧目标(可选):window_hwnd 只推窗口,region 只推矩形;缺省推整屏/整虚拟桌面 ----
uint32_t windowHwnd = 0;
bool hasWindow = false;
@@ -5523,7 +5705,8 @@ std::string BuildRemoteOpen(const Json::Value& id, const Json::Value& args, CMy2
// 与人类远程桌面观看互斥:已有屏幕子连接(web 观看)→ 拒绝,避免向人类正在看的画面注入。
if (WebService().HasActiveSession(devId))
return BuildError(id, -32003, "Device busy: a remote desktop session is already active for this host");
return BuildError(id, -32003, BusyMessage(
"Device busy: a remote desktop session is already active for this host", devId));
int timeoutMs = CMcpServer::Instance().ToolTimeoutMs();
int v = 0;
@@ -5531,7 +5714,8 @@ std::string BuildRemoteOpen(const Json::Value& id, const Json::Value& args, CMy2
std::string sessionId = GenerateRandomToken();
if (!mcp.BeginScreenCtrlOpen(devId, sessionId))
return BuildError(id, -32003, "Device busy: a remote control session is already active for this host");
return BuildError(id, -32003, BusyMessage(
"Device busy: a remote control session is already active for this host", devId));
// 失败清理:会话 + 隐藏对话框 + web-triggered 标记(StartRemoteDesktop 先置标记再发送)。
auto abortOpen = [&]() {
@@ -5898,6 +6082,10 @@ Json::Value BuildRemoteKeyboardInputSchema() {
required.append("session_id");
required.append("action");
schema["required"] = required;
// 描述里写明「type 用 text、按键动作用 key」,但 schema 只要求 id/session_id/action,
// 漏字段要到 handler 才报错。条件必填让模型在发参数前就看到。
AppendConditionalRequired(schema, "action", { "type" }, { "text" });
AppendConditionalRequired(schema, "action", { "key_down", "key_up", "key_press" }, { "key" });
return schema;
}
@@ -6372,6 +6560,8 @@ Json::Value BuildRemoteMouseInputSchema() {
required.append("x");
required.append("y");
schema["required"] = required;
// drag 的终点坐标 x2/y2 在描述里标了「仅 drag」,schema 里补成条件必填。
AppendConditionalRequired(schema, "action", { "drag" }, { "x2", "y2" });
return schema;
}
@@ -8710,9 +8900,32 @@ std::string BuildHttpProbe(const Json::Value& id, const Json::Value& args, CMy20
+ " | " + std::to_string(rawBody.size()) + " bytes"
+ (p.truncated ? " (truncated)" : "")
+ " | " + std::to_string(p.elapsedMs) + " ms";
// 响应头也写进 text:只读 content 文本的客户端看不到 structuredContent.headers,
// 而 Location/Set-Cookie/Content-Type 正是判断重定向与鉴权状态要用的。整体限长
// (单个值也限长),完整响应头仍在 structuredContent.headers 里。
const size_t kMaxHeaderTextBytes = 4096;
const size_t kMaxHeaderLineBytes = 1200;
std::string headerText;
for (const std::string& key : hdrs.getMemberNames()) {
if (headerText.size() >= kMaxHeaderTextBytes) {
headerText += "(truncated; full response headers are in structuredContent.headers)\n";
break;
}
std::string line = key + ": " + hdrs[key].asString();
if (line.size() > kMaxHeaderLineBytes) {
// 按字节截断可能切在多字节 UTF-8 字符中间:回退到该字符的首字节。
size_t cut = kMaxHeaderLineBytes;
while (cut > 0 && ((unsigned char)line[cut] & 0xC0) == 0x80)
--cut;
line = line.substr(0, cut) + "...";
}
headerText += line + "\n";
}
std::string text = head;
if (!headerText.empty())
text += "\nheaders:\n" + headerText;
if (!rawBody.empty())
text += "\n" + (bodyUtf8 ? rawBody : std::string("(base64) ") + sc["body_base64"].asString());
text += "\nbody:\n" + (bodyUtf8 ? rawBody : std::string("(base64) ") + sc["body_base64"].asString());
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
@@ -10801,6 +11014,19 @@ Json::Value BuildSearchFileOutputSchema() {
filesProp["type"] = "array";
Json::Value items(Json::objectValue);
items["type"] = "object";
Json::Value itemProps(Json::objectValue);
for (const char* f : { "path", "name", "modified" }) {
Json::Value s(Json::objectValue);
s["type"] = "string";
itemProps[f] = s;
}
Json::Value dirProp(Json::objectValue);
dirProp["type"] = "boolean";
itemProps["dir"] = dirProp;
Json::Value sizeProp(Json::objectValue);
sizeProp["type"] = "integer";
itemProps["size"] = sizeProp;
items["properties"] = itemProps;
filesProp["items"] = items;
props["files"] = filesProp;
Json::Value finProp(Json::objectValue);
@@ -10809,6 +11035,9 @@ Json::Value BuildSearchFileOutputSchema() {
Json::Value truncProp(Json::objectValue);
truncProp["type"] = "boolean";
props["truncated"] = truncProp;
// 分页字段:BuildSearchFile 一直会带 total/totalAll/offset/limit/hasMore,
// schema 补齐后客户端按输出契约取值才不会扑空。
AppendPageOutputProps(props);
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
@@ -11238,7 +11467,7 @@ ListingLookup LookupInListing(const std::vector<BYTE>& data, const std::string&
return ListingLookup::Unknown;
}
if (data[0] != TOKEN_FILE_LIST) return ListingLookup::Unknown;
// 不在服务端截断:默认那 500 条是给界面用的窗口,这里要扫全(大小仍由客户端单包上限约束)。
// 复核要扫全整个列表(list_files 自己也已整目录解析;这里上限只为兜底)。
const Json::Value items = ParseFileList(data, 1000000, 936);
for (unsigned int i = 0; i < items.size(); ++i) {
const std::string name = JsonStrField(items[i], "name");
@@ -12715,7 +12944,9 @@ int CMcpServer::SweepIdleTerminals(time_t idleTimeoutSec) {
const auto steadyNow = std::chrono::steady_clock::now();
for (auto it = m_TermSessions.begin(); it != m_TermSessions.end(); ) {
TermSession& s = it->second;
const bool idle = s.persistent && !s.busy &&
// started 条件不能省:尚未 START 的会话可能正被 WaitTerminalReady 等着,
// 回收它会把自己的新会话暴露给等待线程(抢到/被误删),等它自己的超时分支清理。
const bool idle = s.persistent && s.started && !s.busy &&
difftime(now, s.lastActiveAt) > (double)idleTimeoutSec;
// busy 兜底(P0-2):超时轮询下会话一直 busy,调用方若再也不回来,该主机的终端槽
// 会永远返回 -32003。跑满 1 小时强制回收(等待函数会重新查表,不会悬空)。
@@ -13169,14 +13400,18 @@ void CMcpServer::EndCall(const std::shared_ptr<McpCallContext>& call) {
bool CMcpServer::CancelCallById(const std::string& idKey, const std::string& idText) {
std::lock_guard<std::mutex> lk(m_CallMutex);
// 取消工具自己也是一次在飞调用;request_id 指到自己时不能把自己算成「被取消」。
const McpCallContext* self = CurrentMcpCall().get();
// 先按精确写法找:"41"(字符串)与 41(数字)是两个不同的 id,不能混。
for (const auto& c : m_Calls) {
if (c.get() == self) continue;
if (c->idKey == idKey) { c->cancelled.store(true); return true; }
}
// 再退回展示文本:调用方常把列表里的 request_id 当字符串原样传回来,
// 而原调用用的是数字 id —— 这是同一意图,容忍。
if (!idText.empty()) {
for (const auto& c : m_Calls) {
if (c.get() == self) continue;
if (c->idText == idText) { c->cancelled.store(true); return true; }
}
}
@@ -13186,7 +13421,9 @@ bool CMcpServer::CancelCallById(const std::string& idKey, const std::string& idT
int CMcpServer::CancelCalls(uint64_t device, const std::string& sessionId) {
int n = 0;
std::lock_guard<std::mutex> lk(m_CallMutex);
const McpCallContext* self = CurrentMcpCall().get();
for (const auto& c : m_Calls) {
if (c.get() == self) continue; // 不把取消工具自身计入 cancelled
if (device != 0 && c->device != device) continue;
if (!sessionId.empty() && c->sessionId != sessionId) continue;
c->cancelled.store(true);
@@ -13318,8 +13555,7 @@ std::string CMcpServer::DescribeBusy(uint64_t device_id) {
std::lock_guard<std::mutex> lk(m_TermMutex);
auto it = m_TermSessions.find(device_id);
if (it != m_TermSessions.end() && it->second.busy)
return describe(it->second.sessionId.empty() ? "exec_command" : "terminal",
ElapsedMsSince(it->second.startedAt));
return describe(TerminalLabel(it->second.sessionId), ElapsedMsSince(it->second.startedAt));
}
{
std::lock_guard<std::mutex> lk(m_ScreenCtrlMutex);
@@ -13926,7 +14162,10 @@ bool CMcpServer::OnDriveList(uint64_t device_id, context* subCtx, const BYTE* bu
searchFile = true;
it->second.subCtx = subCtx; // 超时停搜 / 收尾要用
} else {
listDrives = path.empty() || path == "." || path == "/" || path == "\\";
// 列盘一律用空 path 表示:Windows 的 "."、"/"、"\\" 已在 BuildListFiles 归一化成
// 空串;POSIX 上 "/" 与 "." 是真实目录,必须按目录下发。这里不再自行判魔法路径,
// 免得两个地方口径不一致。
listDrives = path.empty();
if (listDrives) {
it->second.data.assign(buf, buf + len);
it->second.done = true;
+9 -2
View File
@@ -10,8 +10,15 @@ BUILD_DIR=build
# Main package path
MAIN_PACKAGE=./cmd
# Go build flags (strip debug info for smaller binary)
LDFLAGS=-ldflags "-s -w"
# Version metadata injected at link time (see buildinfo package). Both are
# empty outside a git checkout; the server then reports no version rather than
# a fabricated one.
VERSION := $(shell git describe --tags --always --dirty 2>nul)
COMMIT := $(shell git rev-parse --short HEAD 2>nul)
BUILDINFO_PKG = github.com/yuanyuanxiang/SimpleRemoter/server/go/buildinfo
# Go build flags (strip debug info for smaller binary; version always injected)
LDFLAGS=-ldflags "-s -w -X $(BUILDINFO_PKG).Version=$(VERSION) -X $(BUILDINFO_PKG).Commit=$(COMMIT)"
# Windows commands
MKDIR=if not exist $(BUILD_DIR) mkdir $(BUILD_DIR)
+287
View File
@@ -0,0 +1,287 @@
// Package auditquery scans the server's JSON-lines audit file.
//
// The server writes its own audit records to logs/audit.log (see
// logger.AuditAt); records are already redacted at write time, so returning
// raw fields to an authenticated viewer is safe as long as we never widen what
// is written.
//
// Only the CURRENT audit file is searched. Rotated files (audit-*.log[.gz])
// are deliberately out of scope: they need gzip support and a separate index,
// and both the web UI and the MCP tool exist for recent-window triage ("what
// happened just now").
//
// The package is shared by web/audit_query.go (admin audit page) and the MCP
// get_audit_log tool, which is why it has no dependency on either.
package auditquery
import (
"bufio"
"encoding/json"
"os"
"strings"
"time"
)
const (
// DefaultLimit is used when the caller asks for no limit (0 or negative).
DefaultLimit = 100
// MaxLimit caps how many records one query may return.
MaxLimit = 1000
// MaxOffset caps how far a query may page into the result set.
MaxOffset = 10000
// scanBudget bounds how much of the audit file a single query reads. The
// tail is read when the file is larger, so the newest records (what
// operators actually triage) are always covered and a multi-GB log cannot
// stall the query goroutine.
scanBudget = 32 << 20 // 32 MB
)
// Query is one audit-log search. All filters are optional and combined with
// AND. Limit/Offset are clamped by Scan; callers that report the effective
// values back should clamp first with ClampLimit/ClampOffset.
type Query struct {
From string `json:"from"` // RFC3339 ("2026-10-18T10:00:00Z"), optional
To string `json:"to"` // RFC3339, optional
Event string `json:"event"` // exact ("web.login.failure"), prefix ("web." / "web.*"), or ""
Actor string `json:"actor"` // exact, case-insensitive
IP string `json:"ip"` // exact
DeviceID string `json:"device_id"`
Keyword string `json:"keyword"` // case-insensitive substring of the raw record
WarnOnly bool `json:"warn_only"` // only level=warn records
// EventContains is a case-insensitive substring match on the event column.
// The web UI uses Event's exact/prefix forms; the MCP get_audit_log tool
// exposes a "type contains" filter, which maps here.
EventContains string `json:"event_contains"`
Limit int `json:"limit"`
Offset int `json:"offset"` // skip the newest N matching records
}
// Result is the outcome of scanning the audit file.
type Result struct {
Events []map[string]any // newest-first
Total int // matching records in the scanned window
TotalAll int // audit records in the scanned window before filters
FileExists bool
FileSize int64
ScannedBytes int64
Truncated bool // the file was larger than the scan budget
}
// ClampLimit bounds n to [1, max]. A non-positive n means DefaultLimit; a
// non-positive max means MaxLimit. Callers with a tighter UI cap (the web
// audit page uses 500) pass it as max.
func ClampLimit(n, max int) int {
if max <= 0 {
max = MaxLimit
}
if n <= 0 {
return DefaultLimit
}
if n > max {
return max
}
return n
}
// ClampOffset bounds n to [0, MaxOffset].
func ClampOffset(n int) int {
if n < 0 {
return 0
}
if n > MaxOffset {
return MaxOffset
}
return n
}
// Scan scans path for audit records matching q. The returned events are the
// newest Limit records after skipping Offset, in newest-first order. A missing
// file is not an error: no audit record has been written yet (the logger
// creates the file lazily), so the result is empty with FileExists=false.
func Scan(path string, q Query) (Result, error) {
q.Limit = ClampLimit(q.Limit, MaxLimit)
q.Offset = ClampOffset(q.Offset)
res := Result{Events: []map[string]any{}}
f, err := os.Open(path)
if err != nil {
if os.IsNotExist(err) {
return res, nil
}
return res, err
}
defer f.Close()
info, err := f.Stat()
if err != nil {
return res, err
}
res.FileExists = true
res.FileSize = info.Size()
// For very large files, scan only the tail; the newest matches live there.
start := int64(0)
if info.Size() > scanBudget {
start = info.Size() - scanBudget
if _, err := f.Seek(start, 0); err != nil {
return res, err
}
res.Truncated = true
}
from, hasFrom := parseTime(q.From)
to, hasTo := parseTime(q.To)
keep := q.Offset + q.Limit
ring := make([]map[string]any, keep)
filled := 0
sc := bufio.NewScanner(f)
// Sanitized values are capped at 4096 bytes each; a record with many
// fields stays well under 1 MB. Allow headroom rather than aborting the
// whole query on one long line.
sc.Buffer(make([]byte, 64*1024), 4*1024*1024)
first := true
for sc.Scan() {
line := sc.Text()
if start > 0 && first {
// Seeking into the middle of the file lands mid-line. Drop that
// partial record.
first = false
continue
}
first = false
res.ScannedBytes += int64(len(line)) + 1
line = strings.TrimSpace(line)
if line == "" {
continue
}
var rec map[string]any
if err := json.Unmarshal([]byte(line), &rec); err != nil {
continue // tolerate a torn line instead of failing the page
}
if _, ok := rec["event"].(string); !ok {
continue
}
// Only audit records belong in the result. The dedicated file contains
// nothing else, but a hand-edited or mixed file must not surface
// ordinary operational lines here.
if rec["audit"] != true {
continue
}
res.TotalAll++
if !recordMatches(rec, line, q, from, hasFrom, to, hasTo) {
continue
}
// Ring buffer of the last `keep` matches (file order is chronological).
ring[res.Total%keep] = rec
if filled < keep {
filled++
}
res.Total++
}
if err := sc.Err(); err != nil {
return res, err
}
// Newest first, skipping Offset. The match with 0-based index i lives at
// ring[i%keep] as long as i >= Total-filled.
for i := res.Total - 1 - q.Offset; i >= 0 && i >= res.Total-filled; i-- {
res.Events = append(res.Events, ring[i%keep])
if len(res.Events) >= q.Limit {
break
}
}
return res, nil
}
// recordMatches applies the non-time and time filters to one record. line is
// the raw JSON line, used for the keyword substring search.
func recordMatches(rec map[string]any, line string, q Query, from time.Time, hasFrom bool, to time.Time, hasTo bool) bool {
if q.Event != "" && !eventFilterMatches(q.Event, StringField(rec, "event")) {
return false
}
if q.EventContains != "" && !strings.Contains(strings.ToLower(StringField(rec, "event")), strings.ToLower(q.EventContains)) {
return false
}
if q.Actor != "" && !strings.EqualFold(StringField(rec, "actor"), q.Actor) {
return false
}
if q.IP != "" && StringField(rec, "ip") != q.IP {
return false
}
if q.DeviceID != "" && StringField(rec, "device_id") != q.DeviceID {
return false
}
if q.WarnOnly && StringField(rec, "level") != "warn" {
return false
}
if q.Keyword != "" && !strings.Contains(strings.ToLower(line), strings.ToLower(q.Keyword)) {
return false
}
if hasFrom || hasTo {
t, ok := parseTime(StringField(rec, "time"))
if !ok {
return false // cannot prove it is in range
}
if hasFrom && t.Before(from) {
return false
}
if hasTo && t.After(to) {
return false
}
}
return true
}
// eventFilterMatches supports three forms so the UI stays simple:
//
// "web.login.failure" exact
// "web.*" prefix (trailing "*")
// "web." prefix (trailing ".")
func eventFilterMatches(filter, event string) bool {
switch {
case strings.HasSuffix(filter, "*"):
return strings.HasPrefix(event, strings.TrimSuffix(filter, "*"))
case strings.HasSuffix(filter, "."):
return strings.HasPrefix(event, filter)
default:
return event == filter
}
}
// StringField returns rec[key] when it is a string, else "".
func StringField(rec map[string]any, key string) string {
s, _ := rec[key].(string)
return s
}
// parseTime accepts the formats operators and browsers realistically send.
// Layouts without an explicit zone are parsed as UTC; the frontend always sends
// Date.toISOString(), so the RFC3339 path is what production uses.
func parseTime(s string) (time.Time, bool) {
s = strings.TrimSpace(s)
if s == "" {
return time.Time{}, false
}
layouts := []string{
time.RFC3339Nano,
time.RFC3339,
"2006-01-02T15:04:05",
"2006-01-02T15:04",
"2006-01-02 15:04:05",
"2006-01-02",
}
for _, layout := range layouts {
if t, err := time.Parse(layout, s); err == nil {
return t, true
}
}
return time.Time{}, false
}
+248
View File
@@ -0,0 +1,248 @@
package auditquery
import (
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
// writeAuditFixture writes JSON-lines audit records (oldest first) and returns
// the file path. Times are UTC RFC3339 so the tests are timezone-independent.
func writeAuditFixture(t *testing.T, records []map[string]any) string {
t.Helper()
path := filepath.Join(t.TempDir(), "audit.log")
var b strings.Builder
for _, rec := range records {
line, err := json.Marshal(rec)
if err != nil {
t.Fatalf("marshal fixture: %v", err)
}
b.Write(line)
b.WriteByte('\n')
}
if err := os.WriteFile(path, []byte(b.String()), 0o644); err != nil {
t.Fatalf("write fixture: %v", err)
}
return path
}
func auditFixtureRecords() []map[string]any {
at := func(hhmm string) string {
tm, err := time.Parse("2006-01-02T15:04", "2026-10-18T"+hhmm)
if err != nil {
panic(err)
}
return tm.Format(time.RFC3339)
}
return []map[string]any{
{"level": "info", "time": at("10:00"), "audit": true, "event": "web.login.success", "actor": "admin", "ip": "203.0.113.1"},
{"level": "warn", "time": at("10:01"), "audit": true, "event": "web.login.failure", "actor": "alice", "ip": "203.0.113.2", "reason": "invalid_credentials"},
{"level": "info", "time": at("10:02"), "audit": true, "event": "remote.screen.start", "actor": "admin", "role": "admin", "ip": "203.0.113.1", "device_id": "dev1"},
{"level": "info", "time": at("10:03"), "audit": true, "event": "admin.user.delete", "actor": "admin", "ip": "203.0.113.1", "target": "bob"},
}
}
func runAuditQuery(t *testing.T, path string, q Query) Result {
t.Helper()
q.Limit = ClampLimit(q.Limit, MaxLimit)
q.Offset = ClampOffset(q.Offset)
res, err := Scan(path, q)
if err != nil {
t.Fatalf("Scan: %v", err)
}
return res
}
func eventNames(res Result) []string {
out := make([]string, 0, len(res.Events))
for _, e := range res.Events {
out = append(out, StringField(e, "event"))
}
return out
}
func TestNoFilterNewestFirst(t *testing.T) {
path := writeAuditFixture(t, auditFixtureRecords())
res := runAuditQuery(t, path, Query{Limit: 100})
if res.Total != 4 || len(res.Events) != 4 {
t.Fatalf("total=%d events=%d, want 4/4", res.Total, len(res.Events))
}
if res.TotalAll != 4 {
t.Fatalf("totalAll=%d, want 4", res.TotalAll)
}
got := eventNames(res)
want := []string{"admin.user.delete", "remote.screen.start", "web.login.failure", "web.login.success"}
if strings.Join(got, ",") != strings.Join(want, ",") {
t.Fatalf("events = %v, want %v", got, want)
}
}
func TestEventFilters(t *testing.T) {
path := writeAuditFixture(t, auditFixtureRecords())
cases := []struct {
filter string
want []string
}{
{"web.", []string{"web.login.failure", "web.login.success"}},
{"web.*", []string{"web.login.failure", "web.login.success"}},
{"web.login.failure", []string{"web.login.failure"}},
{"remote.*", []string{"remote.screen.start"}},
}
for _, tc := range cases {
res := runAuditQuery(t, path, Query{Event: tc.filter, Limit: 100})
got := eventNames(res)
if strings.Join(got, ",") != strings.Join(tc.want, ",") {
t.Errorf("filter %q → %v, want %v", tc.filter, got, tc.want)
}
}
}
func TestEventContainsFilter(t *testing.T) {
path := writeAuditFixture(t, auditFixtureRecords())
res := runAuditQuery(t, path, Query{EventContains: "LOGIN", Limit: 100})
got := eventNames(res)
want := []string{"web.login.failure", "web.login.success"}
if strings.Join(got, ",") != strings.Join(want, ",") {
t.Fatalf("events = %v, want %v", got, want)
}
// Filters run before paging: total reflects matches, totalAll the window.
if res.Total != 2 || res.TotalAll != 4 {
t.Fatalf("total=%d totalAll=%d, want 2/4", res.Total, res.TotalAll)
}
}
func TestFieldFilters(t *testing.T) {
path := writeAuditFixture(t, auditFixtureRecords())
from, _ := time.Parse(time.RFC3339, "2026-10-18T10:01:00Z")
to, _ := time.Parse(time.RFC3339, "2026-10-18T10:02:00Z")
cases := []struct {
name string
q Query
want []string
}{
{"actor case-insensitive", Query{Actor: "ALICE", Limit: 100}, []string{"web.login.failure"}},
{"ip", Query{IP: "203.0.113.2", Limit: 100}, []string{"web.login.failure"}},
{"device", Query{DeviceID: "dev1", Limit: 100}, []string{"remote.screen.start"}},
{"warn only", Query{WarnOnly: true, Limit: 100}, []string{"web.login.failure"}},
{"keyword target", Query{Keyword: "BOB", Limit: 100}, []string{"admin.user.delete"}},
{"time range", Query{
From: from.Format(time.RFC3339), To: to.Format(time.RFC3339), Limit: 100,
}, []string{"remote.screen.start", "web.login.failure"}},
}
for _, tc := range cases {
res := runAuditQuery(t, path, tc.q)
got := eventNames(res)
if strings.Join(got, ",") != strings.Join(tc.want, ",") {
t.Errorf("%s → %v, want %v", tc.name, got, tc.want)
}
}
}
func TestOffsetAndLimit(t *testing.T) {
path := writeAuditFixture(t, auditFixtureRecords())
res := runAuditQuery(t, path, Query{Limit: 2, Offset: 1})
if res.Total != 4 {
t.Fatalf("total = %d, want 4", res.Total)
}
got := eventNames(res)
want := []string{"remote.screen.start", "web.login.failure"}
if strings.Join(got, ",") != strings.Join(want, ",") {
t.Fatalf("events = %v, want %v", got, want)
}
// Offsetting past the end yields no events but keeps the total.
res = runAuditQuery(t, path, Query{Limit: 2, Offset: 4})
if res.Total != 4 || len(res.Events) != 0 {
t.Fatalf("offset past end: total=%d events=%v", res.Total, eventNames(res))
}
}
func TestSkipsNonAuditAndTornLines(t *testing.T) {
path := filepath.Join(t.TempDir(), "audit.log")
content := `{"event":"device.online","actor":"x"}
not json at all
{"level":"info","time":"2026-10-18T10:00:00Z","audit":true,"event":"web.login.success","actor":"admin"}`
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
t.Fatal(err)
}
res := runAuditQuery(t, path, Query{Limit: 100})
if res.Total != 1 || len(res.Events) != 1 {
t.Fatalf("total=%d events=%v, want the single valid record", res.Total, eventNames(res))
}
// Non-audit and torn lines do not count toward totalAll either.
if res.TotalAll != 1 {
t.Fatalf("totalAll=%d, want 1", res.TotalAll)
}
}
func TestMissingFile(t *testing.T) {
res := runAuditQuery(t, filepath.Join(t.TempDir(), "does-not-exist.log"), Query{Limit: 10})
if res.FileExists {
t.Error("FileExists = true for a missing file")
}
if res.Total != 0 || len(res.Events) != 0 {
t.Errorf("total=%d events=%v, want empty", res.Total, eventNames(res))
}
if res.Events == nil {
t.Error("Events is nil; JSON would encode null instead of []")
}
}
func TestClampsPaging(t *testing.T) {
if got := ClampLimit(0, MaxLimit); got != DefaultLimit {
t.Errorf("limit(0) = %d, want default %d", got, DefaultLimit)
}
if got := ClampLimit(-3, MaxLimit); got != DefaultLimit {
t.Errorf("limit(-3) = %d, want default %d", got, DefaultLimit)
}
if got := ClampLimit(9999, MaxLimit); got != MaxLimit {
t.Errorf("limit(9999) = %d, want max %d", got, MaxLimit)
}
if got := ClampLimit(9999, 500); got != 500 {
t.Errorf("limit(9999, max 500) = %d, want 500", got)
}
if got := ClampLimit(50, MaxLimit); got != 50 {
t.Errorf("limit(50) = %d, want 50", got)
}
if got := ClampLimit(0, 0); got != DefaultLimit {
t.Errorf("limit(0, max 0) = %d, want default %d", got, DefaultLimit)
}
if got := ClampOffset(-5); got != 0 {
t.Errorf("offset(-5) = %d, want 0", got)
}
if got := ClampOffset(1 << 30); got != MaxOffset {
t.Errorf("offset(huge) = %d, want max %d", got, MaxOffset)
}
}
// The web audit page sends snake_case keys. Query is decoded from that wire
// format in web/audit_query.go, so the tags must keep those names — otherwise
// device_id / warn_only silently stop filtering.
func TestQueryDecodesWebWireFormat(t *testing.T) {
body := `{"from":"2026-11-01T00:00:00Z","to":"2026-11-12T00:00:00Z",` +
`"event":"web.","actor":"admin","ip":"1.2.3.4","device_id":"1001",` +
`"keyword":"k","warn_only":true,"limit":5,"offset":2}`
var q Query
if err := json.Unmarshal([]byte(body), &q); err != nil {
t.Fatalf("unmarshal: %v", err)
}
if q.From != "2026-11-01T00:00:00Z" || q.To != "2026-11-12T00:00:00Z" {
t.Fatalf("time range = %q..%q", q.From, q.To)
}
if q.Event != "web." || q.Actor != "admin" || q.IP != "1.2.3.4" {
t.Fatalf("filters = %+v", q)
}
if q.DeviceID != "1001" {
t.Fatalf("device_id = %q, want 1001", q.DeviceID)
}
if q.Keyword != "k" || !q.WarnOnly {
t.Fatalf("keyword/warn_only = %q/%v", q.Keyword, q.WarnOnly)
}
if q.Limit != 5 || q.Offset != 2 {
t.Fatalf("limit/offset = %d/%d", q.Limit, q.Offset)
}
}
+31
View File
@@ -0,0 +1,31 @@
// Package buildinfo exposes the version metadata injected at link time.
//
// Version and Commit are set by the build scripts with
//
// go build -ldflags "-X github.com/yuanyuanxiang/SimpleRemoter/server/go/buildinfo.Version=... \
// -X github.com/yuanyuanxiang/SimpleRemoter/server/go/buildinfo.Commit=..."
//
// They stay empty when the binary is built without git (source tarball, IDE
// run). Callers must report the empty string rather than inventing a value;
// only the MCP initialize response substitutes a literal "dev" marker.
package buildinfo
var (
// Version is the full `git describe --tags --always --dirty` string, e.g.
// "v1.4.2-72-g425d737-dirty".
Version = ""
// Commit is the short commit hash, e.g. "425d737".
Commit = ""
)
// Info is a JSON-friendly snapshot of the injected metadata.
type Info struct {
Version string `json:"version"`
Commit string `json:"commit"`
}
// Snapshot returns the current build metadata. It is safe to call before the
// values are injected (both fields are empty).
func Snapshot() Info {
return Info{Version: Version, Commit: Commit}
}
+90 -3
View File
@@ -17,11 +17,13 @@ import (
"time"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/auth"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/buildinfo"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/connection"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/devicehistory"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/hub"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/licensing"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/logger"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/mcp"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/protocol"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/server"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/web"
@@ -37,6 +39,7 @@ type MyHandler struct {
signer licensing.Signer // CMD_MASTERSETTING signer (local / remote / noop)
loginLimit *wsauth.RateLimiter // per-IP TOKEN_AUTH throttle
connAuthKey []byte // nil = ConnAuth HMAC verification disabled (legacy always-OK)
mcp *mcp.Server // routes main-connection RPC replies (screen preview, file lists)
}
// OnConnect is called when a client connects
@@ -129,8 +132,11 @@ func (h *MyHandler) OnReceive(ctx *connection.Context, data []byte) {
h.handleTerminalStart(ctx, false)
case protocol.TokenTerminalClose:
// Pre-bind close (rare — device gives up before the server
// finished its half of the handshake). Best-effort cleanup.
if devID := h.deviceIDOfSubConn(ctx); devID != "" {
// finished its half of the handshake). Best-effort cleanup, but only
// of a pending lease: an unbound sub-conn carries no lease identity,
// and after a re-login it may be a stale orphan whose close would
// otherwise tear down a shell someone else has since opened.
if devID := h.deviceIDOfSubConn(ctx); devID != "" && h.hub.IsTerminalPending(devID) {
h.log.Info("pre-bind terminal close: device=%s conn=%d", devID, ctx.ID)
h.hub.CloseTerminalSession(devID)
}
@@ -160,6 +166,32 @@ func (h *MyHandler) OnReceive(ctx *connection.Context, data []byte) {
// overlay learns to render arbitrary BGRA images. Drop silently for
// now; the standard IDC_* index (data[10] of every frame header) is
// what we actually use right now.
case protocol.TokenScreenPreviewRsp:
// get_screenshot is a main-connection RPC: the reply carries only a
// reqId, so MCP matches it against the pending request for this device
// and drops a late or foreign one. No other component reads this token.
if h.mcp != nil && h.mcp.OnPacket(ctx, data) {
return
}
h.log.Info("Unhandled command %d from client %d", cmd, ctx.ID)
case protocol.TokenDriveList, protocol.TokenFileList, protocol.TokenFileListError:
// list_files replies arrive on the file-manager sub-connection, whose
// ClientID is pinned by its ConnAuth handshake. MCP matches them against
// the pending request for that device and retires the sub-conn when the
// request finishes or an orphan announces itself.
if h.mcp != nil && h.mcp.OnFilePacket(ctx, data) {
return
}
h.log.Info("Unhandled command %d from client %d", cmd, ctx.ID)
case protocol.CommandSendFileV2, protocol.CommandFileCompleteV2, protocol.TokenDownloadError:
// read_file's V2 transfer: chunks and the completion packet arrive on an
// authenticated sub-conn (a fresh one on Windows, the file-manager one on
// POSIX), the download error on the file-manager sub-conn. MCP routes
// them to the pending session for the device and writes the bytes itself.
if h.mcp != nil && h.mcp.OnTransferPacket(ctx, data) {
return
}
h.log.Info("Unhandled command %d from client %d", cmd, ctx.ID)
case protocol.CmdSockDllLoader:
// SOCKET_DLLLOADER (210): the shellcode / memory-DLL loader asks for the
// full DLL payload before it can load the client. Serving it is the MFC
@@ -880,6 +912,16 @@ func envInt(name string, def int) int {
return n
}
// envBool parses a boolean env var; accepts 1/true/yes/on (case-insensitive)
// as true and everything else — including unset — as false.
func envBool(name string) bool {
switch strings.ToLower(strings.TrimSpace(os.Getenv(name))) {
case "1", "true", "yes", "on":
return true
}
return false
}
// runIssueToken handles the "issue-token" subcommand. It mints a customer JWT
// signed with the operator's RSA private key and prints it to stdout.
//
@@ -1189,6 +1231,43 @@ func main() {
log.Info("Trusting forwarded client IPs from: %s", strings.Join(trustedProxies, ", "))
}
// MCP endpoint: a static bearer token independent of the web login. An
// empty YAMA_MCP_TOKEN leaves /mcp unregistered (404) — there is no
// auto-generated token, because a secret that only appears in a log is not
// a secret. Version/commit come from the link-time buildinfo injection.
//
// Built before the TCP servers so each handler can hand main-connection
// RPC replies (screen preview, file lists) to it. Starting its reaper a
// few statements early is harmless; the HTTP route is mounted later.
mcpReadonly := envBool("YAMA_MCP_READONLY")
var mcpUnsubscribe func()
bindAddr := ""
if *httpPort != 0 {
bindAddr = "0.0.0.0" // web server listens on :port (all interfaces)
}
mcpSrv := mcp.New(mcp.Config{
Token: strings.TrimSpace(os.Getenv("YAMA_MCP_TOKEN")),
Readonly: mcpReadonly,
TermIdle: time.Duration(envInt("YAMA_MCP_TERM_IDLE", 180)) * time.Second,
MaxConcurrency: envInt("YAMA_MCP_MAX_CONCURRENCY", 16),
ReadMax: int64(envInt("YAMA_MCP_READ_MAX", 2<<20)),
Version: buildinfo.Version,
StartedAt: time.Now(),
Log: log.WithPrefix("MCP"),
Hub: deviceHub,
History: deviceHistory,
AuditPath: auditFile,
Port: *httpPort,
Bind: bindAddr,
})
if mcpSrv.Enabled() {
// Terminal tools need the hub's shell events (ready/data/closed).
// Unsubscribed again at shutdown, before the TCP servers stop.
mcpUnsubscribe = deviceHub.Subscribe(mcpSrv)
log.Info("MCP endpoint enabled on /mcp (readonly=%v, commit=%s)",
mcpReadonly, buildinfo.Commit)
}
// Create servers for each port
var servers []*server.Server
for _, port := range ports {
@@ -1214,6 +1293,7 @@ func main() {
signer: signer,
loginLimit: authLoginLimit,
connAuthKey: connAuthKey,
mcp: mcpSrv,
}
srv.SetHandler(handler)
@@ -1292,7 +1372,8 @@ func main() {
// device registry; the authenticator owns user accounts and session tokens.
httpSrv := web.New(*httpPort, log.WithPrefix("Web"), deviceHub, webAuth).
WithDeviceHistory(deviceHistory).
WithConfig(webCfg)
WithConfig(webCfg).
WithMCP(mcpSrv)
if err := httpSrv.Start(); err != nil {
log.Fatal("Failed to start HTTP server: %v", err)
}
@@ -1362,6 +1443,12 @@ func main() {
log.Warn("signer Close: %v", err)
}
httpSrv.Stop()
// Detach from hub events first, then tear down the shells MCP opened while
// the TCP sender is still alive so the client gets a clean BYE.
if mcpUnsubscribe != nil {
mcpUnsubscribe()
}
mcpSrv.Close()
for _, srv := range servers {
srv.Stop()
}
+19
View File
@@ -33,6 +33,25 @@ YAMA_WEB_TRUST_PROXY=1
# WebSocket Origin 白名单(逗号分隔)。空 = 仅允许同源
#YAMA_WEB_ALLOWED_ORIGINS=https://你的域名
# ---------- MCP 端点(可选)----------
# 设计见 docs/Mcp_Go_Minimal_Design.md;启用后挂在同一个 Web 端口的 /mcp。
# 静态 Bearer Token(客户端填同一个值)。空 = 不注册 /mcp(404)。
# 不会自动生成:只出现在日志里的秘密不算秘密
#YAMA_MCP_TOKEN=
# "1" = 只读模式:隐藏并拒收 terminal_exec / terminal_close(会创建/关闭会话)
#YAMA_MCP_READONLY=1
# 终端会话空闲回收(秒,默认 180)
#YAMA_MCP_TERM_IDLE=180
# 全球在途 tools/call 上限(默认 16,超出返回 -32003)
#YAMA_MCP_MAX_CONCURRENCY=16
# read_file 单文件上限(字节,默认 2 MiB;超限提示改用 download_file)
#YAMA_MCP_READ_MAX=2097152
# ---------- SSO(单点登录,可选)----------
# 共享的 HS256 签名密钥。设置后启用 SSO:YAMA 校验父域名(如 FMS 网关)下发的
+69 -11
View File
@@ -94,9 +94,13 @@ type Device struct {
// and after teardown.
// terminalIsPTY: distinguishes Linux/macOS/ConPTY (true) from the legacy
// Windows cmd-pipe path. PTY mode supports resize; cmd-pipe ignores it.
// terminalGen: identifies one lease. Every successful open bumps it, so a
// viewer that lost the lease (a re-login drops a pending request, then
// someone else opens) cannot close the new owner's shell.
terminalPending bool
terminalConn *connection.Context
terminalIsPTY bool
terminalGen uint64
}
// ScreenCache is a read-only snapshot of a device's last-seen screen state,
@@ -275,6 +279,20 @@ func (h *Hub) SendToDevice(id string, data []byte) error {
return h.sender(d.conn, data)
}
// SendToConn forwards a payload to an arbitrary connection (typically a
// sub-conn the caller learned about from an inbound packet) through the same
// framing/compression path as SendToDevice. Raw conn.Write would bypass the
// per-connection encoder and the client could not parse it.
func (h *Hub) SendToConn(ctx *connection.Context, data []byte) error {
if ctx == nil || ctx.IsClosed() {
return ErrDeviceOffline
}
if h.sender == nil {
return ErrNoSender
}
return h.sender(ctx, data)
}
// SendToScreen routes a payload to the device's currently-bound screen
// sub-connection. Input events (COMMAND_SCREEN_CONTROL) MUST go through the
// screen sub-conn rather than the main conn — the C++ client only dispatches
@@ -496,6 +514,7 @@ func (h *Hub) Register(d *Device, conn *connection.Context) {
d.cursorSeen, d.lastCursorIndex = prev.cursorSeen, prev.lastCursorIndex
d.lastCursorX, d.lastCursorY, d.cursorPubAt = prev.lastCursorX, prev.lastCursorY, prev.cursorPubAt
d.terminalConn, d.terminalIsPTY = prev.terminalConn, prev.terminalIsPTY
d.terminalGen = prev.terminalGen
}
h.devices[d.ID] = d
info := deviceToInfo(d)
@@ -754,37 +773,57 @@ var ErrTerminalBusy = errors.New("terminal already open by another viewer")
// returns ErrTerminalBusy. Mirrors C++ CWebService::HandleTermOpen
// (server/2015Remote/WebService.cpp:1838).
func (h *Hub) OpenTerminalSession(deviceID string) error {
_, err := h.openTerminalSession(deviceID)
return err
}
// OpenTerminalSessionLease is OpenTerminalSession that also returns the lease
// generation. A caller that later closes via CloseTerminalSessionLease can
// only tear down the lease it opened: if the session was dropped (device
// re-login) and taken over by another viewer, the generation no longer matches
// and the close is a no-op.
func (h *Hub) OpenTerminalSessionLease(deviceID string) (uint64, error) {
return h.openTerminalSession(deviceID)
}
func (h *Hub) openTerminalSession(deviceID string) (uint64, error) {
if deviceID == "" {
return ErrDeviceOffline
return 0, ErrDeviceOffline
}
h.mu.Lock()
d, ok := h.devices[deviceID]
if !ok || d.conn == nil {
h.mu.Unlock()
return ErrDeviceOffline
return 0, ErrDeviceOffline
}
if d.terminalPending || d.terminalConn != nil {
h.mu.Unlock()
return ErrTerminalBusy
return 0, ErrTerminalBusy
}
d.terminalPending = true
// The generation is bumped with the pending flag, under the same lock: a
// later open can only start once this lease is gone, and it bumps again, so
// an older generation can never match a newer owner's lease.
d.terminalGen++
gen := d.terminalGen
mainConn := d.conn
h.mu.Unlock()
if h.sender == nil {
// Roll back so a retry isn't permanently blocked.
// Roll back so a retry isn't permanently blocked. The generation stays
// bumped; it is only an identity, not a resource.
h.mu.Lock()
d.terminalPending = false
h.mu.Unlock()
return ErrNoSender
return 0, ErrNoSender
}
if err := h.sender(mainConn, []byte{protocol.CommandShell}); err != nil {
h.mu.Lock()
d.terminalPending = false
h.mu.Unlock()
return err
return 0, err
}
return nil
return gen, nil
}
// IsTerminalPending tells the TCP layer whether the next-arriving shell
@@ -798,6 +837,16 @@ func (h *Hub) IsTerminalPending(deviceID string) bool {
return ok && d.terminalPending
}
// HasTerminalSession reports whether the device currently has a pending or
// active shell lease. MCP uses it to tell a genuine terminal close from a
// stale one that raced a fresh open (see mcp.sessionTable.closed).
func (h *Hub) HasTerminalSession(deviceID string) bool {
h.mu.RLock()
defer h.mu.RUnlock()
d, ok := h.devices[deviceID]
return ok && (d.terminalConn != nil || d.terminalPending)
}
// BindTerminalConn promotes the pending session to an active one by
// associating the device's freshly-arrived shell sub-conn. Returns false
// if no pending session exists — callers should drop the orphan ctx.
@@ -909,20 +958,29 @@ func (h *Hub) TerminalIsPTY(id string) bool {
// send COMMAND_BYE, then close after a short grace period so the client's
// IOCPClient reconnect logic doesn't fire.
func (h *Hub) CloseTerminalSession(deviceID string) {
h.closeTerminalPinned(deviceID, nil)
h.closeTerminalPinned(deviceID, nil, 0)
}
// CloseTerminalSessionLease tears down the session only if its lease
// generation still matches gen. False means the lease was already gone (or was
// renewed by another open) and nothing was touched.
func (h *Hub) CloseTerminalSessionLease(deviceID string, gen uint64) bool {
return h.closeTerminalPinned(deviceID, nil, gen)
}
// CloseTerminalSessionPinned is CloseTerminalSession restricted to a device
// still pinned to main; see CloseScreenPinned for why the disconnect path
// needs the ownership check.
func (h *Hub) CloseTerminalSessionPinned(deviceID string, main *connection.Context) bool {
return h.closeTerminalPinned(deviceID, main)
return h.closeTerminalPinned(deviceID, main, 0)
}
func (h *Hub) closeTerminalPinned(deviceID string, main *connection.Context) bool {
// closeTerminalPinned tears down the session. gen==0 closes whatever lease the
// device holds; a non-zero gen closes only that lease.
func (h *Hub) closeTerminalPinned(deviceID string, main *connection.Context, gen uint64) bool {
h.mu.Lock()
d, ok := h.devices[deviceID]
if !ok || (main != nil && d.conn != main) {
if !ok || (main != nil && d.conn != main) || (gen != 0 && d.terminalGen != gen) {
h.mu.Unlock()
return false
}
+35
View File
@@ -188,3 +188,38 @@ func TestRegisterDoesNotCarryPendingTerminal(t *testing.T) {
t.Fatalf("retry after re-register: %v, want nil", err)
}
}
// A lease generation is an ownership proof: a stale opener whose pending
// request a re-login dropped cannot close the lease someone else acquired
// afterwards, while the current owner can still close its own.
func TestCloseTerminalSessionLeaseIgnoresRenewedLease(t *testing.T) {
h := New()
h.SetSender(func(ctx *connection.Context, data []byte) error { return nil })
h.Register(&Device{ID: "dev", PeerIP: "10.0.0.1"},
&connection.Context{RemoteAddr: "10.0.0.1:1000"})
stale, err := h.OpenTerminalSessionLease("dev")
if err != nil {
t.Fatalf("first open: %v", err)
}
// Re-login drops the pending request without an OnTerminalClosed event.
h.Register(&Device{ID: "dev", PeerIP: "10.0.0.1"},
&connection.Context{RemoteAddr: "10.0.0.1:1002"})
current, err := h.OpenTerminalSessionLease("dev")
if err != nil {
t.Fatalf("second open: %v", err)
}
if h.CloseTerminalSessionLease("dev", stale) {
t.Fatal("a stale generation closed the renewed lease")
}
if !h.HasTerminalSession("dev") {
t.Fatal("renewed lease was torn down by the stale close")
}
if !h.CloseTerminalSessionLease("dev", current) {
t.Fatal("the owning generation could not close its lease")
}
if h.HasTerminalSession("dev") {
t.Fatal("lease still held after the owner closed it")
}
}
+123
View File
@@ -0,0 +1,123 @@
package mcp
import (
"encoding/json"
"fmt"
"strings"
"time"
"unicode/utf8"
)
// auditArgsMaxBytes bounds the argument digest written to the audit file. The
// full payload never goes there: commands can contain passwords and request
// bodies can be large.
const auditArgsMaxBytes = 512
// auditCall writes one mcp.tool.call record per tools/call, matching the Win32
// server's fields (design §4.4). actor/role/source distinguish it from browser
// sessions, which audit as the logged-in username.
func (s *Server) auditCall(tool, deviceID string, args json.RawMessage, result any, rerr *rpcError, elapsed time.Duration) {
fields := map[string]any{
"actor": "mcp",
"role": "admin",
"source": "mcp",
"tool": tool,
"device": "-",
"ok": rerr == nil,
"code": 0,
"ms": elapsed.Milliseconds(),
"args": summarizeArgs(args),
}
if deviceID != "" {
fields["device"] = deviceID
}
if rerr != nil {
fields["code"] = rerr.Code
fields["result"] = rerr.Message
} else {
fields["result"] = resultSize(result)
}
s.log.Audit("mcp.tool.call", fields)
}
// redactedArgKeys name top-level arguments whose value is user content or a
// credential. They are replaced by their size so the audit trail records that
// something was sent, without copying it: terminal commands, chat text, HTTP
// bodies and headers routinely carry passwords.
var redactedArgKeys = map[string]bool{
"text": true,
"message": true,
"body": true,
"headers": true,
"password": true,
"token": true,
}
// summarizeArgs renders a compact, truncated argument digest. A "command"
// value is reduced to its first word and length so terminal passwords never
// reach the audit file; other sensitive values are replaced by their size. The
// full payload stays out of the audit file entirely.
func summarizeArgs(raw json.RawMessage) string {
if len(raw) == 0 || string(raw) == "null" {
return "{}"
}
var obj map[string]any
if err := json.Unmarshal(raw, &obj); err != nil {
return fmt.Sprintf("<unparsed %d bytes>", len(raw))
}
for key, value := range obj {
if key == "command" {
if command, ok := value.(string); ok {
obj[key] = commandDigest(command)
}
continue
}
if redactedArgKeys[key] {
obj[key] = redactedDigest(value)
}
}
b, err := json.Marshal(obj)
if err != nil {
return "{}"
}
return truncateUTF8(string(b), auditArgsMaxBytes)
}
// redactedDigest replaces a sensitive value with its serialized size. The
// marker avoids angle brackets so encoding/json does not escape it.
func redactedDigest(value any) string {
b, err := json.Marshal(value)
if err != nil {
return "redacted"
}
return fmt.Sprintf("redacted(%d bytes)", len(b))
}
func commandDigest(command string) string {
first := command
if i := strings.IndexAny(command, " \t"); i >= 0 {
first = command[:i]
}
return fmt.Sprintf("%s (len=%d)", first, len(command))
}
func resultSize(result any) string {
b, err := json.Marshal(result)
if err != nil {
return "?"
}
return fmt.Sprintf("%d bytes", len(b))
}
// truncateUTF8 cuts s to at most max bytes, including the ellipsis, without
// splitting a rune.
func truncateUTF8(s string, max int) string {
if len(s) <= max {
return s
}
cut := max - len("…")
for cut > 0 && !utf8.RuneStart(s[cut]) {
cut--
}
return s[:cut] + "…"
}
+320
View File
@@ -0,0 +1,320 @@
package mcp
import "strings"
// Terminal output cleaning, ported byte-for-byte from the Win32 server
// (server/2015Remote/McpServer.cpp:3875-4060). The stage order is load-bearing
// — ConPTY is a screen-rendering stream, not a byte stream, so echoed input,
// ANSI repaints and sentinel remnants all interact. clean_test.go locks the
// behaviour against samples captured from the MFC implementation; do not
// "simplify" the matchers.
//
// MFC's CleanTerminalOutput runs: StripAnsi → CRLF normalize → StripEchoedInput
// (which itself ends with StripSentinelText) → TrimRight. We keep that order.
// stripAnsi drops CSI/OSC and other single-byte ESC sequences so terminal
// colour codes never reach the model.
func stripAnsi(s string) string {
var b strings.Builder
b.Grow(len(s))
for i := 0; i < len(s); i++ {
if s[i] != 0x1b {
b.WriteByte(s[i])
continue
}
i++ // swallow ESC
if i < len(s) && s[i] == '[' { // CSI ... ends at @..~
i++
for i < len(s) && !(s[i] >= '@' && s[i] <= '~') {
i++
}
} else if i < len(s) && s[i] == ']' { // OSC ... ends at BEL or ST
i++
for i < len(s) && s[i] != 0x07 && s[i] != 0x1b {
i++
}
// ST is the two-byte sequence ESC '\'; consume both.
if i+1 < len(s) && s[i] == 0x1b && s[i+1] == '\\' {
i++
}
}
// Any other one-byte ESC sequence: the byte after ESC is swallowed by
// the loop increment.
}
return b.String()
}
// stripEchoedLine removes the first occurrence of line, ignoring CR/LF inside
// the match because ConPTY wraps a long echo at 80 columns. The echoed line's
// trailing newlines are removed with it.
func stripEchoedLine(s, line string) string {
if line == "" || s == "" {
return s
}
for i := 0; i < len(s); i++ {
j, k := 0, i
for j < len(line) && k < len(s) {
c := s[k]
if c == '\r' || c == '\n' {
k++
continue
}
if c != line[j] {
break
}
j++
k++
}
if j != len(line) {
continue
}
for k < len(s) && (s[k] == '\r' || s[k] == '\n') {
k++
}
return s[:i] + s[k:]
}
return s
}
// cutThroughEchoedLine deletes everything up to and including the echoed input
// line. ConPTY replays the boot screen and prompt just before our input echo,
// so the echo marks where real output starts. ok=false means the client did
// not echo; the caller then falls back to stripEchoedLine.
func cutThroughEchoedLine(s, line string) (string, bool) {
if line == "" || s == "" {
return s, false
}
for i := 0; i < len(s); i++ {
j, k := 0, i
for j < len(line) && k < len(s) {
c := s[k]
if c == '\r' || c == '\n' {
k++
continue
}
if c != line[j] {
break
}
j++
k++
}
if j != len(line) {
continue
}
for k < len(s) && (s[k] == '\r' || s[k] == '\n') {
k++
}
return s[k:], true
}
return s, false
}
// trimLeadingNewlines drops the blank lines left by the boot screen or the
// previous command's trailing newline.
func trimLeadingNewlines(s string) string {
i := 0
for i < len(s) && (s[i] == '\r' || s[i] == '\n') {
i++
}
return s[i:]
}
// stripSentinelText erases sentinel remnants that a ConPTY repaint duplicated
// into the output (e.g. `cmd /c echo abc` renders as "abc__MCP_DONE_x__0").
// The nonce is random per command, so real output cannot contain the marker;
// matching skips CR/LF (wrapped echoes) and also eats a trailing
// "%errorlevel%" echo template. A preceding "echo " is removed with it.
func stripSentinelText(s, nonce string) string {
if nonce == "" || s == "" {
return s
}
marker := "__MCP_DONE_" + nonce + "__"
i := 0
for i < len(s) {
j, k := 0, i
for j < len(marker) && k < len(s) {
c := s[k]
if c == '\r' || c == '\n' {
k++
continue
}
if c != marker[j] {
break
}
j++
k++
}
if j != len(marker) {
i++
continue
}
end := k
if end < len(s) && s[end] == '-' {
end++
}
for end < len(s) && s[end] >= '0' && s[end] <= '9' {
end++
}
if end < len(s) && s[end] == '%' { // echoed template ...__%errorlevel%
for end < len(s) && s[end] != '\r' && s[end] != '\n' {
end++
}
}
begin := i // also remove a stray "echo " left in front of it
if begin >= 5 && strings.EqualFold(s[begin-5:begin], "echo ") {
begin -= 5
}
s = s[:begin] + s[end:]
i = begin
}
return s
}
// stripEchoedInput removes the PTY's echo of the command line and sentinel
// line. Non-PTY sessions only remove the sentinel line: the legacy shell
// manager skips the echo by written length, so deleting the command echo could
// eat real output (e.g. `echo echo hello`).
func stripEchoedInput(s string, isPTY bool, cmdLine, sentLine, nonce string) string {
out := s
cut := false
if isPTY {
out, cut = cutThroughEchoedLine(out, cmdLine)
}
if isPTY && !cut {
out = stripEchoedLine(out, cmdLine)
}
out = stripEchoedLine(out, sentLine)
out = stripSentinelText(out, nonce)
return trimLeadingNewlines(out)
}
// buildSentinelLines builds the command line and sentinel line for one
// platform. PTY platforms send them as two lines so line-swallowing commands
// (rem / cmd / exit / if / for) cannot eat the sentinel; the legacy non-PTY
// path keeps the single-line &&/|| form.
func buildSentinelLines(isPTY, posix bool, command, nonce string) (cmdLine, sentLine string) {
if posix {
return command, "echo __MCP_DONE_" + nonce + "__$?"
}
if !isPTY {
return command + " 2>&1 && echo __MCP_DONE_" + nonce + "__0 || echo __MCP_DONE_" + nonce + "__1", ""
}
return "@echo off & " + command, "echo __MCP_DONE_" + nonce + "__%errorlevel%"
}
// buildTerminalWire assembles what goes to the shell. POSIX shells print PS1
// on every read, which would pollute stdout, so it is cleared first; that
// line's echo is cut together with the boot noise.
func buildTerminalWire(posix bool, cmdLine, sentLine string) []byte {
var b strings.Builder
if posix {
b.WriteString("PS1=\r\n")
}
b.WriteString(cmdLine)
b.WriteString("\r\n")
if sentLine != "" {
b.WriteString(sentLine)
b.WriteString("\r\n")
}
return []byte(b.String())
}
// containsControlChar reports a byte < 0x20, including CR/LF. A newline would
// split the command into extra lines, only the last of which carries the
// sentinel, so the exit code would be wrong.
func containsControlChar(s string) bool {
for i := 0; i < len(s); i++ {
if s[i] < 0x20 {
return true
}
}
return false
}
// hasPosixBackgroundAmpersand reports an unquoted, unescaped '&' that is not
// part of &&, &> or >&. A background command's output and exit code cannot be
// attributed to the sentinel, so it is refused.
func hasPosixBackgroundAmpersand(s string) bool {
var inSingle, inDouble, esc bool
for i := 0; i < len(s); i++ {
c := s[i]
if esc {
esc = false
continue
}
if c == '\\' && !inSingle {
esc = true
continue
}
if inSingle {
if c == '\'' {
inSingle = false
}
continue
}
if inDouble {
if c == '"' {
inDouble = false
}
continue
}
if c == '\'' {
inSingle = true
continue
}
if c == '"' {
inDouble = true
continue
}
if c != '&' {
continue
}
if i+1 < len(s) && (s[i+1] == '&' || s[i+1] == '>') {
i++
continue
}
if i > 0 && s[i-1] == '>' { // 2>&1 / >&2
continue
}
return true
}
return false
}
// normalizeCRLF drops the '\r' of every CRLF pair, as MFC does.
func normalizeCRLF(s string) string {
if !strings.Contains(s, "\r\n") {
return s
}
var b strings.Builder
b.Grow(len(s))
for i := 0; i < len(s); i++ {
if s[i] == '\r' && i+1 < len(s) && s[i+1] == '\n' {
continue
}
b.WriteByte(s[i])
}
return b.String()
}
// cleanTerminalOutput is one delivery window's worth of cleaning. first is
// true only for the command-issuing call's first window (echo exists only
// there); trimTrailing stays false for a partial window so the next window's
// first line does not get glued onto this one.
func cleanTerminalOutput(raw []byte, isPTY, first bool, cmdLine, sentLine, nonce string, trimTrailing bool) string {
if len(raw) == 0 {
return ""
}
s := stripAnsi(string(raw))
s = normalizeCRLF(s)
if first {
s = stripEchoedInput(s, isPTY, cmdLine, sentLine, nonce)
} else {
s = stripSentinelText(s, nonce)
s = trimLeadingNewlines(s)
}
if trimTrailing {
s = strings.TrimRight(s, " \t\r\n")
}
return s
}
+170
View File
@@ -0,0 +1,170 @@
package mcp
import (
"strings"
"testing"
)
func TestStripAnsi(t *testing.T) {
cases := []struct{ in, want string }{
{"plain", "plain"},
{"\x1b[31mred\x1b[0m text", "red text"},
{"a\x1b[?25hb", "ab"},
{"\x1b]0;title\x07after", "after"},
{"\x1b]0;title\x1b\\after", "after"},
{"\x1b]8;;http://x\x07link\x1b]8;;\x07", "link"},
{"\x1b(Bcharset", "Bcharset"}, // ESC ( is a two-byte sequence; only '(' is swallowed
{"\x1b", ""},
{"tail\x1b[", "tail"},
}
for _, tc := range cases {
if got := stripAnsi(tc.in); got != tc.want {
t.Errorf("stripAnsi(%q) = %q, want %q", tc.in, got, tc.want)
}
}
}
func TestBuildSentinelLines(t *testing.T) {
const cmd, nonce = "echo hi", "ab12cd34"
var cmdLine, sentLine string
cmdLine, sentLine = buildSentinelLines(true, true, cmd, nonce)
if cmdLine != cmd || sentLine != "echo __MCP_DONE_ab12cd34__$?" {
t.Fatalf("posix: %q / %q", cmdLine, sentLine)
}
wire := string(buildTerminalWire(true, cmdLine, sentLine))
if want := "PS1=\r\necho hi\r\necho __MCP_DONE_ab12cd34__$?\r\n"; wire != want {
t.Fatalf("posix wire = %q, want %q", wire, want)
}
cmdLine, sentLine = buildSentinelLines(true, false, cmd, nonce)
if cmdLine != "@echo off & echo hi" || sentLine != "echo __MCP_DONE_ab12cd34__%errorlevel%" {
t.Fatalf("conpty: %q / %q", cmdLine, sentLine)
}
if wire := string(buildTerminalWire(false, cmdLine, sentLine)); !strings.HasPrefix(wire, "@echo off & echo hi\r\necho ") {
t.Fatalf("conpty wire = %q", wire)
}
cmdLine, sentLine = buildSentinelLines(false, false, cmd, nonce)
if cmdLine != "echo hi 2>&1 && echo __MCP_DONE_ab12cd34__0 || echo __MCP_DONE_ab12cd34__1" || sentLine != "" {
t.Fatalf("legacy: %q / %q", cmdLine, sentLine)
}
}
// Samples follow the ConPTY repaint behaviour documented in
// McpServer.cpp:3946-3989: the boot prompt and echoed input precede the real
// output, and a repaint can glue the sentinel onto the last output line.
func TestStripEchoedInputWindows(t *testing.T) {
const nonce = "ab12cd34"
cmdLine, sentLine := buildSentinelLines(true, false, "rem hello", nonce)
got := cleanTerminalOutput([]byte(
"\x1b[?25l@echo off & rem hello\r\n\r\n__MCP_DONE_ab12cd34__%errorlevel%\r\n__MCP_DONE_ab12cd34__0\r\n"),
true, true, cmdLine, sentLine, nonce, true)
if got != "" {
t.Fatalf("rem hello output = %q, want empty", got)
}
cmdLine, sentLine = buildSentinelLines(true, false, "cmd /c echo abc", nonce)
got = cleanTerminalOutput([]byte(
"@echo off & cmd /c echo abc\r\nabc__MCP_DONE_ab12cd34__0\r\n"),
true, true, cmdLine, sentLine, nonce, true)
if got != "abc" {
t.Fatalf("cmd /c echo abc output = %q, want %q", got, "abc")
}
cmdLine, sentLine = buildSentinelLines(true, false, "type .env", nonce)
got = cleanTerminalOutput([]byte(
"@echo off & type .env\r\nKEY=value\r\nSECOND=line\r\n__MCP_DONE_ab12cd34__1\r\n"),
true, true, cmdLine, sentLine, nonce, true)
if got != "KEY=value\nSECOND=line" {
t.Fatalf("type .env output = %q", got)
}
// A long command line is wrapped at 80 columns by ConPTY; the echo matcher
// skips the inserted newlines. "cmd /\c" is a literal path, not an escape.
long := "cmd /c " + strings.Repeat("x", 100)
cmdLine, sentLine = buildSentinelLines(true, false, long, nonce)
wrapped := "@echo off & cmd /c " + strings.Repeat("x", 60) + "\r\n" + strings.Repeat("x", 40) +
"\r\nwrapped-ok\r\n__MCP_DONE_ab12cd34__0\r\n"
got = cleanTerminalOutput([]byte(wrapped), true, true, cmdLine, sentLine, nonce, true)
if got != "wrapped-ok" {
t.Fatalf("wrapped echo output = %q, want %q", got, "wrapped-ok")
}
}
// The legacy non-PTY shell skips the echo by written length, so the command
// echo must not be removed (it could be real output, e.g. `echo echo hello`).
func TestCleanNonPTYKeepsCommandEcho(t *testing.T) {
const nonce = "ab12cd34"
cmdLine, sentLine := buildSentinelLines(false, false, "echo echo hello", nonce)
raw := []byte("echo echo hello\r\nhello\r\n__MCP_DONE_ab12cd34__0\r\n")
got := cleanTerminalOutput(raw, false, true, cmdLine, sentLine, nonce, true)
if got != "echo echo hello\nhello" {
t.Fatalf("non-PTY output = %q", got)
}
}
func TestCleanTerminalOutputTrimOnlyOnFinalChunk(t *testing.T) {
const nonce = "ab12cd34"
if got := cleanTerminalOutput([]byte("LINE-17\r\n"), true, false, "", "", nonce, false); got != "LINE-17\n" {
t.Fatalf("partial window = %q, want trailing newline kept", got)
}
if got := cleanTerminalOutput([]byte("LINE-17\r\n"), true, false, "", "", nonce, true); got != "LINE-17" {
t.Fatalf("final window = %q, want trimmed", got)
}
}
func TestStripSentinelTextEchoTemplate(t *testing.T) {
got := stripSentinelText("before\necho __MCP_DONE_ab12cd34__%errorlevel%\nafter\n", "ab12cd34")
// The template line's own newline stays: stripEchoedLine removes the
// echoed sentinel line first in the real pipeline; this is the fallback.
if got != "before\n\nafter\n" {
t.Fatalf("template removal = %q", got)
}
// A negative exit code (%errorlevel% of a crashed process) is removed too.
got = stripSentinelText("out\n__MCP_DONE_ab12cd34__-1073741510\n", "ab12cd34")
if got != "out\n" {
t.Fatalf("negative removal = %q", got)
}
}
func TestContainsControlChar(t *testing.T) {
for _, s := range []string{"a\nb", "a\rb", "a\tb", "\x01"} {
if !containsControlChar(s) {
t.Errorf("containsControlChar(%q) = false", s)
}
}
for _, s := range []string{"", "echo ok", "中文", "a|b&&c"} {
if containsControlChar(s) {
t.Errorf("containsControlChar(%q) = true", s)
}
}
}
func TestHasPosixBackgroundAmpersand(t *testing.T) {
cases := []struct {
in string
want bool
}{
{"sleep 1 &", true},
{"echo a & echo b", true},
{"a && b", false},
{"a &> /dev/null", false},
{"a 2>&1", false},
{"echo 'a & b'", false},
{`echo a\&b`, false},
{`echo "a & b"`, false},
{"grep -v '^#' /etc/hosts", false},
}
for _, tc := range cases {
if got := hasPosixBackgroundAmpersand(tc.in); got != tc.want {
t.Errorf("hasPosixBackgroundAmpersand(%q) = %v, want %v", tc.in, got, tc.want)
}
}
}
func TestNormalizeCRLF(t *testing.T) {
if got := normalizeCRLF("a\r\nb\rc"); got != "a\nb\rc" {
t.Fatalf("normalizeCRLF = %q", got)
}
}
+41
View File
@@ -0,0 +1,41 @@
package mcp
import "fmt"
// JSON-RPC 2.0 error codes used by the MCP endpoint. The -320xx range mirrors
// the Win32 server (McpServer.cpp:296-312) so a model sees the same numbers
// regardless of which backend it talks to; reusing them matters more than
// inventing Go-specific ones.
const (
CodeInternal = -32000 // unexpected server-side failure
CodeTimeout = -32001 // sub-connection or device reply did not arrive
CodeOffline = -32002 // host unknown or offline
CodeBusy = -32003 // per-device lock / terminal slot occupied
CodeSendFailed = -32004 // command could not be delivered to the host
CodeUnsupported = -32005 // host lacks the required capability
CodeDenied = -32006 // policy refusal (readonly mode, disabled tool)
CodeNotFound = -32009 // target file/directory does not exist
CodePermission = -32010 // target rejected the operation (access denied)
CodeParseError = -32700 // invalid JSON
CodeInvalidRequest = -32600 // not a valid JSON-RPC request
CodeMethodNotFound = -32601 // unknown method or tool name
CodeInvalidParams = -32602 // schema/argument validation failed
)
// rpcError is the JSON-RPC "error" object. It is returned as a Go error from
// tool handlers, which lets call sites use plain returns instead of carrying
// a response object through every layer.
type rpcError struct {
Code int `json:"code"`
Message string `json:"message"`
Data any `json:"data,omitempty"`
}
func (e *rpcError) Error() string {
return fmt.Sprintf("mcp error %d: %s", e.Code, e.Message)
}
// errf builds an rpcError with a formatted message.
func errf(code int, format string, args ...any) *rpcError {
return &rpcError{Code: code, Message: fmt.Sprintf(format, args...)}
}
+768
View File
@@ -0,0 +1,768 @@
package mcp
import (
"context"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"strconv"
"strings"
"sync"
"time"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/connection"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/hub"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/protocol"
)
// list_files drives the client's file-manager sub-connection (design §5.3).
// With ids it fans out one call per host under a shared deadline, matching the
// Win32 batch contract (see listFilesBatch):
//
// main conn : COMMAND_LIST_DRIVE(1)
// └─ client opens a sub-conn, sends TOKEN_CONN_AUTH then
// TOKEN_DRIVE_LIST(103) — the sub-conn stays open
// that sub : COMMAND_LIST_FILES(2) [path\0]
// └─ TOKEN_FILE_LIST(104) or TOKEN_FILE_LIST_ERROR(171)
// then the server closes the sub-conn (COMMAND_BYE + 500 ms)
//
// The sub-conn carries ConnAuth, so handleConnAuth has already pinned the
// device's ClientID on its ctx and no pending-connection bookkeeping is needed
// (design §5.3); the pending request is keyed by device and remembers which
// ctx answered, which is also how late packets from a previous sub-conn are
// told apart from the current one.
const (
// fileListMaxEntries is the parse cap shared with the Win32 server: the
// directory is parsed in full and paged afterwards, so total/hasMore stay
// true; only a pathological directory is cut here, and structuredContent
// then carries truncated=true and the summary says so.
fileListMaxEntries = 100000
// fileRecordFixedLen is attr(1) + size(8) + FILETIME(8).
fileRecordFixedLen = 17
// driveRecordFixedLen is letter(1) + type(1) + totalMB(4) + freeMB(4).
driveRecordFixedLen = 10
// filetimeEpochDiff converts FILETIME (100 ns ticks since 1601-01-01) to
// Unix seconds once divided by filetimeTicksPerSec.
filetimeTicksPerSec = 10000000
filetimeEpochDiffSec = 11644473600
errorAccessDenied = 5
errorFileNotFound = 2
errorPathNotFound = 3
// listFilesBatchMaxIDs is the ids[] cap, matching the Win32 batch wrapper.
listFilesBatchMaxIDs = 50
)
// listFilesBatchDeadline bounds one ids[] call: every host must be answered
// before it, and hosts not attempted afterwards are reported as skipped. A
// variable only so tests can shorten it.
var listFilesBatchDeadline = 50 * time.Second
// fileListTimeout bounds one list_files round trip, including the sub-conn
// handshake. A variable only so tests can shorten it.
var fileListTimeout = 10 * time.Second
// fileRetireDelay is how long the sub-conn stays open after COMMAND_BYE, so the
// client's read loop sees the goodbye before FIN (the hub uses the same 500 ms
// for screen sub-conns).
var fileRetireDelay = 500 * time.Millisecond
// fileEventKind distinguishes the three packets a list_files call can receive.
type fileEventKind byte
const (
fileEventDriveList fileEventKind = iota + 1 // TOKEN_DRIVE_LIST
fileEventFileList // TOKEN_FILE_LIST
fileEventError // TOKEN_FILE_LIST_ERROR
)
// fileEvent is one packet handed from the TCP read loop to the waiting call.
// ctx identifies the sub-conn it arrived on; payload bytes are copied because
// the read buffer is not ours to keep.
type fileEvent struct {
kind fileEventKind
ctx *connection.Context
payload []byte // drive records or file records (token byte removed)
win32err uint32 // fileEventError only
}
// fileRequest is one in-flight list_files call. ch is buffered so the read loop
// never blocks; sub records which sub-conn answered the drive-list phase and
// rejects packets from any other connection for the same device. abandoned is
// set by cancel so a packet that loses the race with the call's own return is
// not queued into a channel nobody reads.
type fileRequest struct {
ch chan fileEvent
mu sync.Mutex
sub *connection.Context
abandoned bool
}
func (r *fileRequest) subConn() *connection.Context {
r.mu.Lock()
defer r.mu.Unlock()
return r.sub
}
// fileTable holds the single pending list_files per device. The per-device
// call lock already serialises tools, so more than one entry cannot normally
// exist; the table rejects it anyway rather than mis-routing replies.
type fileTable struct {
mu sync.Mutex
byDevice map[string]*fileRequest
}
func newFileTable() *fileTable {
return &fileTable{byDevice: make(map[string]*fileRequest)}
}
func (t *fileTable) begin(deviceID string) (*fileRequest, bool) {
t.mu.Lock()
defer t.mu.Unlock()
if _, ok := t.byDevice[deviceID]; ok {
return nil, false
}
r := &fileRequest{ch: make(chan fileEvent, 2)}
t.byDevice[deviceID] = r
return r, true
}
// cancel ends the request and returns the sub-conn it learned about, if any.
// The caller retires that sub-conn: this is the single retirement point, so a
// call that gives up while its drive-list packet is already queued (the timer
// and the channel being ready at the same time, or the MCP request cancelled)
// still closes the client's file-manager thread instead of leaking it.
func (t *fileTable) cancel(deviceID string, r *fileRequest) *connection.Context {
t.mu.Lock()
if t.byDevice[deviceID] == r {
delete(t.byDevice, deviceID)
}
t.mu.Unlock()
r.mu.Lock()
r.abandoned = true
sub := r.sub
r.mu.Unlock()
return sub
}
// deliver routes one event to the pending call. It reports whether the event
// was accepted; a packet from a connection other than the one that answered
// the drive-list phase is a late packet from an earlier sub-conn and must be
// ignored (the client sends a legacy one-byte TOKEN_FILE_LIST right after
// TOKEN_FILE_LIST_ERROR, and back-to-back calls can overlap with it).
func (t *fileTable) deliver(deviceID string, ev fileEvent) bool {
t.mu.Lock()
r := t.byDevice[deviceID]
t.mu.Unlock()
if r == nil {
return false
}
r.mu.Lock()
if r.abandoned {
// The call already returned; let OnFilePacket treat the packet as an
// orphan (a drive list) instead of queueing it for nobody.
r.mu.Unlock()
return false
}
switch ev.kind {
case fileEventDriveList:
if r.sub != nil && r.sub != ev.ctx {
r.mu.Unlock()
return false
}
if r.sub == nil {
r.sub = ev.ctx
}
case fileEventError:
// No client answers COMMAND_LIST_DRIVE with an error, but if one ever
// does, adopt the connection and let the call translate the code
// instead of dropping the packet and timing out.
if r.sub == nil {
r.sub = ev.ctx
}
if r.sub != ev.ctx {
r.mu.Unlock()
return false
}
default:
if r.sub != ev.ctx {
r.mu.Unlock()
return false
}
}
r.mu.Unlock()
select {
case r.ch <- ev:
default:
// The current phase already has an event queued; a duplicate is only
// noise (the legacy empty TOKEN_FILE_LIST after an error packet).
}
return true
}
func (s *Server) registerFileTools() {
s.handlers["list_files"] = s.callListFiles
s.handlers["read_file"] = s.callReadFile
}
// OnFilePacket feeds one file-manager packet from a sub-connection to the
// pending list_files call. It reports whether the packet belongs to this
// protocol at all; cmd/main.go forwards only the three file-manager tokens.
func (s *Server) OnFilePacket(ctx *connection.Context, data []byte) bool {
if s == nil || len(data) == 0 {
return false
}
switch data[0] {
case protocol.TokenDriveList, protocol.TokenFileList, protocol.TokenFileListError:
default:
return false
}
deviceID := ctx.GetInfo().ClientID
if deviceID == "" {
return true
}
if s.cfg.Hub != nil {
if main := s.cfg.Hub.MainConn(deviceID); main == ctx {
// File-manager packets only ever arrive on the dedicated sub-conn;
// a token that looks like one on the main connection is not ours.
return true
}
}
ev := fileEvent{ctx: ctx}
switch data[0] {
case protocol.TokenDriveList:
ev.kind = fileEventDriveList
ev.payload = append([]byte(nil), data[1:]...)
case protocol.TokenFileList:
ev.kind = fileEventFileList
ev.payload = append([]byte(nil), data[1:]...)
case protocol.TokenFileListError:
ev.kind = fileEventError
if len(data) >= 5 {
ev.win32err = binary.LittleEndian.Uint32(data[1:5])
}
}
if s.files.deliver(deviceID, ev) {
return true
}
// Nothing is waiting for this sub-conn: the call it belonged to already
// timed out or finished. Retire it so the client does not leak its
// file-manager thread, but only once the sub-conn has announced itself.
// A live read_file keeps its file-manager sub-conn registered in the
// transfer table (POSIX clients stream on it), so never close that one.
if ev.kind == fileEventDriveList && !s.transfers.owns(ctx) {
s.retireFileConn(ctx)
}
return true
}
// retireFileConn closes a file-manager sub-conn the way the hub retires screen
// sub-conns: COMMAND_BYE so the client's IOCP loop exits through its clean
// path, then a delayed Close so the goodbye is not overtaken by FIN.
func (s *Server) retireFileConn(ctx *connection.Context) {
if ctx == nil {
return
}
if s.cfg.Hub != nil {
_ = s.cfg.Hub.SendToConn(ctx, []byte{protocol.CommandBye})
}
// Read the delay before spawning: tests shorten it between calls.
delay := fileRetireDelay
go func(c *connection.Context) {
time.Sleep(delay)
_ = c.Close()
}(ctx)
}
// ----- get_screenshot-style argument / result shapes -------------------------
// listFilesArgs is the published inputSchema as Go. ids selects the batch path;
// path/limit/offset then apply to every host.
type listFilesArgs struct {
ID string `json:"id"`
IDs []string `json:"ids"`
Path string `json:"path"`
Limit int `json:"limit"`
Offset int `json:"offset"`
}
type driveEntry struct {
Drive string `json:"drive"`
Type uint64 `json:"type"`
TypeName string `json:"typeName"`
FileSystem string `json:"fileSystem"`
TotalMB uint64 `json:"totalMB"`
FreeMB uint64 `json:"freeMB"`
}
type fileEntry struct {
Name string `json:"name"`
IsDir bool `json:"isDir"`
Size uint64 `json:"size"`
Mtime int64 `json:"mtime"`
}
// openFileManagerConn asks the device for its file-manager sub-connection
// (COMMAND_LIST_DRIVE on the main connection) and waits for the drive list.
// On success it returns the sub-connection, the still-pending request (later
// packets are matched against it) and the parsed drives; the caller owns both
// and must call closeFileManagerConn when done. Every failure path retires the
// sub-connection here, so a timed-out or rejected handshake leaves no orphan
// file-manager thread on the client.
func (s *Server) openFileManagerConn(ctx context.Context, deviceID string) (*connection.Context, *fileRequest, []driveEntry, *rpcError) {
req, ok := s.files.begin(deviceID)
if !ok {
return nil, nil, nil, errf(CodeBusy, "Device busy: another file request is already pending for host %s", deviceID)
}
keep := false
defer func() {
if !keep {
if sub := s.files.cancel(deviceID, req); sub != nil {
s.retireFileConn(sub)
}
}
}()
if err := s.cfg.Hub.SendToDevice(deviceID, []byte{protocol.CommandListDrive}); err != nil {
if errors.Is(err, hub.ErrDeviceOffline) {
return nil, nil, nil, errf(CodeOffline, "Host not found or offline: %s", deviceID)
}
return nil, nil, nil, errf(CodeSendFailed, "Failed to ask the host for its file-manager channel: %v", err)
}
timer := time.NewTimer(fileListTimeout)
defer timer.Stop()
select {
case ev := <-req.ch:
switch ev.kind {
case fileEventDriveList:
keep = true
return ev.ctx, req, parseDriveList(ev.payload), nil
case fileEventError:
return nil, nil, nil, errf(win32ErrorCode(ev.win32err),
"Failed to open the file-manager channel on host %s (win32=%d)", deviceID, ev.win32err)
default:
return nil, nil, nil, errf(CodeInternal, "Unexpected file-manager reply while listing drives")
}
case <-timer.C:
return nil, nil, nil, errf(CodeTimeout,
"Timeout waiting for the host to open a file-manager channel (%s). Older clients that do not implement file browsing stay silent; retrying will not help.",
fileListTimeout)
case <-ctx.Done():
return nil, nil, nil, errf(CodeTimeout, "Request cancelled while waiting for the host's file-manager channel")
}
}
// closeFileManagerConn ends the request and retires the sub-connection it
// learned about. It is the single retirement point for that sub-conn: the
// cancel below also covers a call that gave up while its drive-list packet was
// already queued (the select taking the timer branch with both ready).
func (s *Server) closeFileManagerConn(deviceID string, req *fileRequest) {
if sub := s.files.cancel(deviceID, req); sub != nil {
s.retireFileConn(sub)
}
}
// callListFiles lists drives (no path) or one directory level. With ids it
// answers the batch before any per-host work.
func (s *Server) callListFiles(ctx context.Context, raw json.RawMessage) (any, *rpcError) {
if s.cfg.Hub == nil {
return nil, errf(CodeInternal, "server device registry is not configured")
}
var args listFilesArgs
if rerr := decodeArgs(raw, &args); rerr != nil {
return nil, rerr
}
// ids 出现即走批量,空数组也算:Win32 的 isMember("ids") && isArray 同样接受,
// 返回 total=0;只看 len>0 会把一个 schema 合法的空批量误报成缺少 id。
if batchIDsPresent(raw) {
if args.ID != "" {
return nil, errf(CodeInvalidParams, "Pass either id or ids, not both")
}
return s.listFilesBatch(ctx, args)
}
if args.ID == "" {
return nil, errf(CodeInvalidParams, "Missing required parameter: id")
}
res, rerr := s.listFilesOne(ctx, args)
if rerr != nil {
return nil, rerr
}
return res, nil
}
// batchIDsPresent reports whether the call spelled ids[] at all. It looks at
// the raw JSON because an empty array decodes to the same empty slice as a
// missing one, yet the two mean different things (empty batch vs. no target).
func batchIDsPresent(raw json.RawMessage) bool {
var probe struct {
IDs json.RawMessage `json:"ids"`
}
if err := json.Unmarshal(raw, &probe); err != nil || len(probe.IDs) == 0 {
return false
}
return string(probe.IDs) != "null"
}
// listFilesBatch answers list_files with ids[] by calling listFilesOne once per
// host, matching the Win32 batch contract: at most 50 hosts, and ids not
// attempted after the 50 s deadline are reported as skipped (not as failures).
// The deadline only gates starting a host: one already running gets its own
// per-host timeout and its result is recorded normally, exactly like Win32.
// Results keep the input order.
func (s *Server) listFilesBatch(ctx context.Context, args listFilesArgs) (any, *rpcError) {
if len(args.IDs) > listFilesBatchMaxIDs {
return nil, errf(CodeInvalidParams,
"Too many ids: %d (max %d per batch)", len(args.IDs), listFilesBatchMaxIDs)
}
deadline := time.Now().Add(listFilesBatchDeadline)
results := make([]map[string]any, 0, len(args.IDs))
failLines := make([]string, 0, len(args.IDs))
succeeded, failed, skipped := 0, 0, 0
for _, id := range args.IDs {
if !isDecimalID(id) {
msg := "Invalid id: expected a decimal host id string"
results = append(results, batchListError(id, CodeInvalidParams, msg))
failLines = append(failLines, id+": "+msg)
failed++
continue
}
if !time.Now().Before(deadline) {
entry := batchListError(id, CodeTimeout,
fmt.Sprintf("Batch deadline exceeded (%s): not attempted", listFilesBatchDeadline))
entry["skipped"] = true
results = append(results, entry)
skipped++
continue
}
one := args
one.ID = id
one.IDs = nil
// Win32's batch calls the same per-host entry as a single-host call, so
// an entry loses to an operation already in flight on that host
// (-32003) instead of running beside it. listFilesOne cannot take the
// lock itself: the single-host path already holds it (callTool).
if held, acquired := s.locks.tryAcquire(id, "list_files"); !acquired {
msg := busyMessage(held)
results = append(results, batchListError(id, CodeBusy, msg))
failLines = append(failLines, id+": "+msg)
failed++
continue
}
res, rerr := func() (toolResult, *rpcError) {
defer s.locks.release(id)
return s.listFilesOne(ctx, one)
}()
if rerr != nil {
results = append(results, batchListError(id, rerr.Code, rerr.Message))
failLines = append(failLines, id+": "+rerr.Message)
failed++
continue
}
entry := map[string]any{"id": id, "ok": true, "data": res.StructuredContent}
if len(res.Content) > 0 {
entry["text"] = res.Content[0].Text
}
results = append(results, entry)
succeeded++
}
structured := map[string]any{
"tool": "list_files",
"total": len(args.IDs),
"succeeded": succeeded,
"failed": failed,
"skipped": skipped,
"results": results,
}
text := fmt.Sprintf("批量调用 list_files:共 %d 台,成功 %d 台,失败 %d 台", len(args.IDs), succeeded, failed)
if skipped > 0 {
text += fmt.Sprintf(",超时跳过 %d 台", skipped)
}
text += "。"
for _, line := range failLines {
text += "\n - " + line
}
return newToolResult(text, structured), nil
}
// batchListError is one failed batch entry in the shape the outputSchema
// declares: id, ok=false, error{code,message} and the message as text.
func batchListError(id string, code int, msg string) map[string]any {
return map[string]any{
"id": id,
"ok": false,
"text": msg,
"error": map[string]any{"code": code, "message": msg},
}
}
// listFilesOne lists drives or one directory of a single host.
func (s *Server) listFilesOne(ctx context.Context, args listFilesArgs) (toolResult, *rpcError) {
if !isDecimalID(args.ID) {
return toolResult{}, errf(CodeInvalidParams, "Invalid id: expected a decimal host id string")
}
// NUL and newlines would truncate or split the client's C string field.
if strings.ContainsAny(args.Path, "\x00\r\n") {
return toolResult{}, errf(CodeInvalidParams, "Invalid path: NUL and line breaks are not allowed")
}
if s.cfg.Hub.MainConn(args.ID) == nil {
return toolResult{}, errf(CodeOffline, "Host not found or offline: %s", args.ID)
}
path := args.Path
// The published contract (tools.json) is: no path lists drives, any path
// lists that directory. MFC also folds "." and "/" into the drive list,
// but that makes a POSIX root listing unreachable, so this server follows
// the documented rule instead.
listDrives := path == ""
pathGBK := protocol.UTF8ToGBK(path)
if len(pathGBK) >= 250 {
// The client copies the path into a MAX_PATH buffer and appends "\\*.*".
return toolResult{}, errf(CodeInvalidParams,
"Path too long: %d bytes after conversion to the client's GBK encoding (limit 249)", len(pathGBK))
}
sub, req, drives, rerr := s.openFileManagerConn(ctx, args.ID)
if rerr != nil {
return toolResult{}, rerr
}
defer s.closeFileManagerConn(args.ID, req)
if listDrives {
return listFilesResult(args, drives, nil, false), nil
}
// Phase 2: reuse the same sub-conn for the directory itself.
pkt := make([]byte, 0, 2+len(pathGBK))
pkt = append(pkt, protocol.CommandListFiles)
pkt = append(pkt, pathGBK...)
pkt = append(pkt, 0)
if err := s.cfg.Hub.SendToConn(sub, pkt); err != nil {
return toolResult{}, errf(CodeSendFailed, "Failed to send the directory request on the file-manager channel: %v", err)
}
timer := time.NewTimer(fileListTimeout)
defer timer.Stop()
select {
case ev := <-req.ch:
switch ev.kind {
case fileEventFileList:
files, truncated := parseFileList(ev.payload)
return listFilesResult(args, nil, files, truncated), nil
case fileEventError:
return toolResult{}, fileWin32Error(ev.win32err, path)
default:
return toolResult{}, errf(CodeInternal, "Unexpected file-manager reply while listing a directory")
}
case <-timer.C:
return toolResult{}, errf(CodeTimeout,
"Timeout waiting for the directory listing of %q (%s). If the path does not exist, an older client stays silent instead of reporting an error — list the parent directory first.",
path, fileListTimeout)
case <-ctx.Done():
return toolResult{}, errf(CodeTimeout, "Request cancelled while waiting for the directory listing")
}
}
// win32ErrorCode maps a client-reported Win32 error onto an MCP code the same
// way the Win32 server does: 5 is a permission problem, 2/3 mean "no such
// target", everything else is an internal failure carrying the raw code.
func win32ErrorCode(win32err uint32) int {
switch win32err {
case errorAccessDenied:
return CodePermission
case errorFileNotFound, errorPathNotFound:
return CodeNotFound
default:
return CodeInternal
}
}
// fileWin32Error maps the client's win32 error onto MCP codes the same way the
// Win32 server does: 5 is a permission problem, 2/3 mean "no such target",
// everything else is an internal failure carrying the raw code.
func fileWin32Error(win32err uint32, path string) *rpcError {
subject := fmt.Sprintf("Failed to list %q", path)
switch win32err {
case errorAccessDenied:
return errf(CodePermission, "%s: access denied (win32=%d)", subject, win32err)
case errorFileNotFound, errorPathNotFound:
return errf(CodeNotFound, "%s: target not found (win32=%d)", subject, win32err)
default:
return errf(CodeInternal, "%s: the host reported a failure (win32=%d)", subject, win32err)
}
}
// parseDriveList decodes [letter][type][totalMB:4 LE][freeMB:4 LE][typeName\0][fs\0]
// records until a zero letter (the client's end marker) or a truncated record.
// Names are GBK on the wire for every platform.
func parseDriveList(p []byte) []driveEntry {
out := make([]driveEntry, 0, 8)
off := 0
for off+driveRecordFixedLen <= len(p) && p[off] != 0 {
letter := p[off]
dtype := uint64(p[off+1])
total := uint64(binary.LittleEndian.Uint32(p[off+2:]))
free := uint64(binary.LittleEndian.Uint32(p[off+6:]))
off += driveRecordFixedLen
typeName, n, ok := cString(p[off:])
if !ok {
break
}
off += n + 1
fs, n, ok := cString(p[off:])
if !ok {
break
}
off += n + 1
// Windows letters become "C:\". The POSIX clients report '/' as their
// single root "drive"; return it as "/" so it can be passed straight
// back as a path (MFC renders "/:\", which also works after the
// client's path conversion, but "/" is the friendlier form).
drive := string(letter) + ":\\"
if letter == '/' {
drive = "/"
}
out = append(out, driveEntry{
Drive: drive,
Type: dtype,
TypeName: protocol.GbkToUTF8(typeName),
FileSystem: protocol.GbkToUTF8(fs),
TotalMB: total,
FreeMB: free,
})
}
return out
}
// parseFileList decodes [attr][name\0][sizeHi:4][sizeLo:4][ftLo:4][ftHi:4]
// records. An empty name is the client's trailing zero padding; reaching the
// entry cap stops the parse and reports truncation.
func parseFileList(p []byte) ([]fileEntry, bool) {
out := make([]fileEntry, 0, 64)
off := 0
for off < len(p) {
attr := p[off]
off++
name, n, ok := cString(p[off:])
if !ok || n == 0 {
break
}
// Cap check after a real record is seen: trailing zero padding (an empty
// name) must not report truncation when the listing is exactly at the cap.
if len(out) >= fileListMaxEntries {
return out, true
}
off += n + 1
if off+fileRecordFixedLen-1 > len(p) {
break
}
sizeHigh := uint64(binary.LittleEndian.Uint32(p[off:]))
sizeLow := uint64(binary.LittleEndian.Uint32(p[off+4:]))
ftLow := uint64(binary.LittleEndian.Uint32(p[off+8:]))
ftHigh := uint64(binary.LittleEndian.Uint32(p[off+12:]))
off += 16
ft := ftHigh<<32 | ftLow
var mtime int64
if ft != 0 {
mtime = int64(ft/filetimeTicksPerSec) - filetimeEpochDiffSec
if mtime < 0 {
mtime = 0
}
}
out = append(out, fileEntry{
Name: protocol.GbkToUTF8(name),
IsDir: attr&0x10 != 0,
Size: sizeHigh<<32 | sizeLow,
Mtime: mtime,
})
}
return out, false
}
// cString returns the NUL-terminated field at the start of p. ok is false when
// p runs out before the terminator (a truncated packet).
func cString(p []byte) (name []byte, n int, ok bool) {
for i, b := range p {
if b == 0 {
return p[:i], i, true
}
}
return nil, 0, false
}
// listFilesResult applies the limit/offset window and builds the MCP envelope.
// Only one of drives/files is non-nil; total/totalAll/hasMore describe the
// full listing, not the returned page. truncated reports that the directory
// held more entries than the parse cap, so the model is not told "that is all
// there is".
func listFilesResult(args listFilesArgs, drives []driveEntry, files []fileEntry, truncated bool) toolResult {
limit := clampPageLimit(args.Limit)
offset := max(args.Offset, 0)
var structured map[string]any
var text string
var header []string
var rows [][]string
if drives != nil {
total := len(drives)
begin := min(offset, total)
end := min(begin+limit, total)
structured = map[string]any{
"drives": drives[begin:end],
"total": total,
"totalAll": total,
"limit": limit,
"offset": offset,
"hasMore": end < total,
}
text = pageSummary(total, limit, offset, "个驱动器")
header = []string{"drive", "typeName", "fileSystem", "totalMB", "freeMB"}
rows = make([][]string, 0, end-begin)
for _, d := range drives[begin:end] {
rows = append(rows, []string{
d.Drive, d.TypeName, d.FileSystem,
strconv.FormatUint(d.TotalMB, 10), strconv.FormatUint(d.FreeMB, 10),
})
}
} else {
total := len(files)
begin := min(offset, total)
end := min(begin+limit, total)
structured = map[string]any{
"files": files[begin:end],
"total": total,
"totalAll": total,
"limit": limit,
"offset": offset,
"hasMore": end < total,
"truncated": truncated,
}
text = pageSummary(total, limit, offset, "个条目")
header = []string{"name", "isDir", "size", "mtime"}
rows = make([][]string, 0, end-begin)
for _, f := range files[begin:end] {
rows = append(rows, []string{
f.Name, strconv.FormatBool(f.IsDir),
strconv.FormatUint(f.Size, 10), strconv.FormatInt(f.Mtime, 10),
})
}
}
if truncated {
text += fmt.Sprintf("目录条目超过 %d 条,total 只是上限内的数量,请缩小目录范围。", fileListMaxEntries)
}
text = appendRows(text, header, rows)
return newToolResult(text, structured)
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+628
View File
@@ -0,0 +1,628 @@
package mcp
import (
"context"
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"os"
"strings"
"testing"
"time"
"unicode/utf8"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/connection"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/hub"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/protocol"
)
// shortenTransferTimeouts makes the read_file watchdogs test-sized. The poll
// interval stays well under the stall window so the stalled check is reached
// deterministically.
func shortenTransferTimeouts(t *testing.T, stall, total, poll time.Duration) {
t.Helper()
oldStall, oldTotal, oldPoll := fileTransferStallTimeout, fileTransferTotalTimeout, fileTransferPollInterval
fileTransferStallTimeout, fileTransferTotalTimeout, fileTransferPollInterval = stall, total, poll
t.Cleanup(func() {
fileTransferStallTimeout, fileTransferTotalTimeout, fileTransferPollInterval = oldStall, oldTotal, oldPoll
})
}
// ----- wire builders ---------------------------------------------------------
func chunkPacket(transferID uint64, fileIndex, totalFiles uint32, fileSize, offset uint64,
flags uint16, name string, payload []byte) []byte {
nameGBK := protocol.UTF8ToGBK(name)
buf := make([]byte, fileChunkHeaderLen+len(nameGBK)+len(payload))
buf[0] = protocol.CommandSendFileV2
binary.LittleEndian.PutUint64(buf[fileChunkOffTransferID:], transferID)
binary.LittleEndian.PutUint32(buf[fileChunkOffFileIndex:], fileIndex)
binary.LittleEndian.PutUint32(buf[fileChunkOffTotalFiles:], totalFiles)
binary.LittleEndian.PutUint64(buf[fileChunkOffFileSize:], fileSize)
binary.LittleEndian.PutUint64(buf[fileChunkOffOffset:], offset)
binary.LittleEndian.PutUint64(buf[fileChunkOffDataLength:], uint64(len(payload)))
binary.LittleEndian.PutUint64(buf[fileChunkOffNameLength:], uint64(len(nameGBK)))
binary.LittleEndian.PutUint16(buf[fileChunkOffFlags:], flags)
copy(buf[fileChunkHeaderLen:], nameGBK)
copy(buf[fileChunkHeaderLen+len(nameGBK):], payload)
return buf
}
func completePacket(transferID uint64, fileIndex uint32, fileSize uint64, sum []byte) []byte {
buf := make([]byte, fileCompleteHeaderLen)
buf[0] = protocol.CommandFileCompleteV2
binary.LittleEndian.PutUint64(buf[fileCompleteOffTransferID:], transferID)
binary.LittleEndian.PutUint32(buf[fileCompleteOffFileIndex:], fileIndex)
binary.LittleEndian.PutUint64(buf[fileCompleteOffFileSize:], fileSize)
copy(buf[fileCompleteOffSHA256:], sum)
return buf
}
func downloadErrorPacket(win32err uint32) []byte {
buf := make([]byte, 5)
buf[0] = protocol.TokenDownloadError
binary.LittleEndian.PutUint32(buf[1:], win32err)
return buf
}
// ----- harness ---------------------------------------------------------------
func (r *fileRig) callRead(args string) <-chan fileCall {
ch := make(chan fileCall, 1)
go func() {
res, rerr := r.s.callReadFile(context.Background(), []byte(args))
if rerr != nil {
ch <- fileCall{err: rerr}
return
}
tr, ok := res.(toolResult)
if !ok {
ch <- fileCall{err: errf(CodeInternal, "unexpected result type %T", res)}
return
}
ch <- fileCall{res: tr}
}()
return ch
}
// startReadCall runs one read_file call through the drive-list handshake and
// returns the waiting call, the file-manager sub-conn, and the target directory
// the server asked the client to write under (which is what real clients echo
// back as the packet name prefix).
func (r *fileRig) startReadCall(args string, drives ...driveRec) (<-chan fileCall, *connection.Context, string) {
r.t.Helper()
ch := r.callRead(args)
if got := r.next(r.main); len(got) != 1 || got[0] != protocol.CommandListDrive {
r.t.Fatalf("drive request wire = %v, want [%d]", got, protocol.CommandListDrive)
}
sub := r.newSub()
if drives == nil {
drives = []driveRec{{'C', 3, 500000, 123456, "本地磁盘", "NTFS"}}
}
if !r.s.OnFilePacket(sub, driveListPacket(drives...)) {
r.t.Fatal("drive-list packet was not consumed")
}
got := r.next(sub)
if got[0] != protocol.CmdDownFilesV2 {
r.t.Fatalf("download request wire = %v, want token %d first", got, protocol.CmdDownFilesV2)
}
rest := got[1:]
i := strings.IndexByte(string(rest), 0)
if i < 0 {
r.t.Fatal("download request has no NUL after targetDir")
}
targetDir := string(rest[:i])
if !strings.HasSuffix(targetDir, string(os.PathSeparator)) {
r.t.Fatalf("targetDir %q does not end with a path separator", targetDir)
}
return ch, sub, targetDir
}
// readOutput pulls the structured output out of a successful call.
func readOutput(t *testing.T, c fileCall) readFileOutput {
t.Helper()
if c.err != nil {
t.Fatalf("read_file failed: %d %s", c.err.Code, c.err.Message)
}
out, ok := c.res.StructuredContent.(readFileOutput)
if !ok {
t.Fatalf("structured content type = %T", c.res.StructuredContent)
}
return out
}
// ----- name validation -------------------------------------------------------
func TestTransferNameWithinDir(t *testing.T) {
const sep = `\`
target := "C:" + sep + "Users" + sep + "tmp" + sep + "yama-mcp-read-1" + sep
cases := []struct {
name string
want string // "" means rejected
}{
{target + "file.txt", "file.txt"},
{target + `sub\file.txt`, "sub/file.txt"},
{target + "a//b.txt", "a/b.txt"},
{"../x", ""},
{`..\..\x`, ""},
{`C:\Windows\x`, ""},
{"/etc/passwd", ""},
{`\\server\share\x`, ""},
{`a/../../b`, ""},
{target + `sub\..\..\..\x`, ""},
{target, ""},
{"", ""},
{"x\x00y", ""},
{"x\ny", ""},
}
for _, c := range cases {
got, ok := transferNameWithinDir(target, c.name)
if c.want == "" {
if ok {
t.Errorf("transferNameWithinDir(%q) = %q, want rejection", c.name, got)
}
continue
}
if !ok || got != c.want {
t.Errorf("transferNameWithinDir(%q) = %q,%v, want %q", c.name, got, ok, c.want)
}
}
}
// ----- end-to-end transfers --------------------------------------------------
func TestReadFileWindowsStreamSubConn(t *testing.T) {
shortenTransferTimeouts(t, time.Second, 5*time.Second, 5*time.Millisecond)
rig := newFileRig(t)
ch, fm, targetDir := rig.startReadCall(`{"id":"1001","path":"C:\\cfg\\app.ini"}`)
content := []byte("line1\r\nline2\r\nline3\r\n")
split := 8
stream := rig.newSub() // Windows clients open a fresh authenticated sub-conn
name := targetDir + "app.ini"
rig.s.OnTransferPacket(stream, chunkPacket(42, 0, 1, uint64(len(content)), 0, 0, name, content[:split]))
rig.s.OnTransferPacket(stream, chunkPacket(42, 0, 1, uint64(len(content)), uint64(split), ffV2LastChunk, name, content[split:]))
sum := sha256.Sum256(content)
rig.s.OnTransferPacket(stream, completePacket(42, 0, uint64(len(content)), sum[:]))
out := readOutput(t, rig.wait(ch))
if out.Size != len(content) || out.Text != "line1\nline2\nline3" {
t.Fatalf("text = %q size=%d", out.Text, out.Size)
}
if out.Encoding != "utf-8" || out.EOL != "crlf" {
t.Fatalf("encoding=%q eol=%q", out.Encoding, out.EOL)
}
if out.LinesTotal != 3 || out.LinesReturned != 3 || out.Truncated {
t.Fatalf("lines_total=%d lines_returned=%d truncated=%v", out.LinesTotal, out.LinesReturned, out.Truncated)
}
if want := hex.EncodeToString(sum[:]); out.SHA256 != want {
t.Fatalf("sha256 = %q, want %q", out.SHA256, want)
}
if !strings.Contains(out.Path, "app.ini") {
t.Fatalf("path = %q", out.Path)
}
// The file-manager sub-conn is retired once the call returns.
waitClosed(t, fm)
}
func TestReadFilePosixChunksOnFileManagerConn(t *testing.T) {
shortenTransferTimeouts(t, time.Second, 5*time.Second, 5*time.Millisecond)
rig := newFileRig(t)
ch, fm, targetDir := rig.startReadCall(`{"id":"1001","path":"/etc/app.conf"}`,
driveRec{'/', 4, 100000, 1000, "Linux", "ext4"})
content := []byte("a=1\nb=2\n")
name := targetDir + "app.conf"
rig.s.OnTransferPacket(fm, chunkPacket(7, 0, 1, uint64(len(content)), 0, ffV2LastChunk, name, content))
sum := sha256.Sum256(content)
rig.s.OnTransferPacket(fm, completePacket(7, 0, uint64(len(content)), sum[:]))
out := readOutput(t, rig.wait(ch))
if out.Text != "a=1\nb=2" || out.EOL != "lf" {
t.Fatalf("text=%q eol=%q", out.Text, out.EOL)
}
}
func TestReadFilePosixRejectsWindowsPath(t *testing.T) {
rig := newFileRig(t)
ch := rig.callRead(`{"id":"1001","path":"C:\\cfg\\app.ini"}`)
if got := rig.next(rig.main); len(got) != 1 || got[0] != protocol.CommandListDrive {
t.Fatalf("drive request wire = %v", got)
}
fm := rig.newSub()
if !rig.s.OnFilePacket(fm, driveListPacket(driveRec{'/', 4, 100000, 1000, "Linux", "ext4"})) {
t.Fatal("drive-list packet was not consumed")
}
// The path is checked before anything goes out on the file-manager conn.
c := rig.wait(ch)
if c.err == nil || c.err.Code != CodeInvalidParams {
t.Fatalf("error = %+v, want -32602", c.err)
}
if !strings.Contains(c.err.Message, "absolute POSIX path") {
t.Fatalf("message = %q", c.err.Message)
}
waitClosed(t, fm)
}
func TestReadFileSizeGate(t *testing.T) {
shortenTransferTimeouts(t, time.Second, 5*time.Second, 5*time.Millisecond)
rig := newFileRig(t)
rig.s.cfg.ReadMax = 4096
ch, _, targetDir := rig.startReadCall(`{"id":"1001","path":"C:\\big.bin"}`)
stream := rig.newSub()
rig.s.OnTransferPacket(stream, chunkPacket(1, 0, 1, 5000, 0, 0, targetDir+"big.bin", make([]byte, 100)))
c := rig.wait(ch)
if c.err == nil || c.err.Code != CodeInvalidParams {
t.Fatalf("error = %+v, want -32602", c.err)
}
if !strings.Contains(c.err.Message, "no download_file") ||
!strings.Contains(c.err.Message, "terminal_exec") {
t.Fatalf("message = %q", c.err.Message)
}
}
func TestReadFileDirectoryRejected(t *testing.T) {
shortenTransferTimeouts(t, time.Second, 5*time.Second, 5*time.Millisecond)
rig := newFileRig(t)
ch, _, targetDir := rig.startReadCall(`{"id":"1001","path":"C:\\folder"}`)
stream := rig.newSub()
rig.s.OnTransferPacket(stream, chunkPacket(1, 0, 1, 0, 0, ffV2Directory, targetDir+"folder\\", nil))
c := rig.wait(ch)
if c.err == nil || c.err.Code != CodeInvalidParams {
t.Fatalf("error = %+v, want -32602", c.err)
}
if !strings.Contains(c.err.Message, "Not a single regular file") {
t.Fatalf("message = %q", c.err.Message)
}
}
// TestReadFileMultiFileBatchRejected pins the expanded-directory case: the
// client turns a directory path into a multi-file batch and stamps totalFiles on
// every chunk, so the very first chunk must fail the call. Waiting for a second
// fileIndex is not enough — file 0's completion packet would end the call and its
// content would be returned as if it were the requested path.
func TestReadFileMultiFileBatchRejected(t *testing.T) {
shortenTransferTimeouts(t, time.Second, 5*time.Second, 5*time.Millisecond)
rig := newFileRig(t)
ch, _, targetDir := rig.startReadCall(`{"id":"1001","path":"C:\\dir"}`)
stream := rig.newSub()
rig.s.OnTransferPacket(stream, chunkPacket(5, 0, 2, 3, 0, ffV2LastChunk, targetDir+`dir\a.txt`, []byte("aaa")))
sum := sha256.Sum256([]byte("aaa"))
// Even a matching completion must not rescue a multi-file batch.
rig.s.OnTransferPacket(stream, completePacket(5, 0, 3, sum[:]))
c := rig.wait(ch)
if c.err == nil || c.err.Code != CodeInvalidParams {
t.Fatalf("error = %+v, want -32602", c.err)
}
if !strings.Contains(c.err.Message, "single regular file") {
t.Fatalf("message = %q", c.err.Message)
}
}
func TestReadFileSecondFileIndexRejected(t *testing.T) {
shortenTransferTimeouts(t, time.Second, 5*time.Second, 5*time.Millisecond)
rig := newFileRig(t)
ch, _, targetDir := rig.startReadCall(`{"id":"1001","path":"C:\\dir"}`)
stream := rig.newSub()
rig.s.OnTransferPacket(stream, chunkPacket(9, 0, 2, 3, 0, 0, targetDir+"a.txt", []byte("abc")))
rig.s.OnTransferPacket(stream, chunkPacket(9, 1, 2, 3, 0, 0, targetDir+"b.txt", []byte("xyz")))
c := rig.wait(ch)
if c.err == nil || c.err.Code != CodeInvalidParams {
t.Fatalf("error = %+v, want -32602", c.err)
}
}
func TestReadFileSHA256Mismatch(t *testing.T) {
shortenTransferTimeouts(t, time.Second, 5*time.Second, 5*time.Millisecond)
rig := newFileRig(t)
ch, _, targetDir := rig.startReadCall(`{"id":"1001","path":"C:\\a.txt"}`)
content := []byte("hello")
stream := rig.newSub()
rig.s.OnTransferPacket(stream, chunkPacket(3, 0, 1, 5, 0, ffV2LastChunk, targetDir+"a.txt", content))
bad := make([]byte, sha256.Size)
rig.s.OnTransferPacket(stream, completePacket(3, 0, 5, bad))
c := rig.wait(ch)
if c.err == nil || c.err.Code != CodeInternal {
t.Fatalf("error = %+v, want -32000", c.err)
}
if !strings.Contains(c.err.Message, "SHA-256") {
t.Fatalf("message = %q", c.err.Message)
}
}
func TestReadFileEmptyFile(t *testing.T) {
shortenTransferTimeouts(t, time.Second, 5*time.Second, 5*time.Millisecond)
rig := newFileRig(t)
ch, _, _ := rig.startReadCall(`{"id":"1001","path":"C:\\empty.txt"}`)
// Windows clients send no chunk for an empty file, only the completion.
stream := rig.newSub()
sum := sha256.Sum256(nil)
rig.s.OnTransferPacket(stream, completePacket(5, 0, 0, sum[:]))
out := readOutput(t, rig.wait(ch))
if out.Size != 0 || out.Text != "" || out.LinesTotal != 0 || out.LinesReturned != 0 || out.Truncated {
t.Fatalf("empty file output = %+v", out)
}
if out.EOL != "none" {
t.Fatalf("eol = %q, want none", out.EOL)
}
if want := hex.EncodeToString(sum[:]); out.SHA256 != want {
t.Fatalf("sha256 = %q, want %q", out.SHA256, want)
}
}
func TestReadFileDropsForeignTransferIDChunks(t *testing.T) {
shortenTransferTimeouts(t, time.Second, 5*time.Second, 5*time.Millisecond)
rig := newFileRig(t)
ch, _, targetDir := rig.startReadCall(`{"id":"1001","path":"C:\\a.txt"}`)
content := []byte("payload")
name := targetDir + "a.txt"
stream := rig.newSub()
rig.s.OnTransferPacket(stream, chunkPacket(100, 0, 1, uint64(len(content)), 0, 0, name, content[:3]))
// A late chunk from another (older) transfer must not disturb this one.
rig.s.OnTransferPacket(stream, chunkPacket(99, 0, 1, 999, 0, 0, `C:\stale`, []byte("zzz")))
rig.s.OnTransferPacket(stream, chunkPacket(100, 0, 1, uint64(len(content)), 3, ffV2LastChunk, name, content[3:]))
sum := sha256.Sum256(content)
rig.s.OnTransferPacket(stream, completePacket(100, 0, uint64(len(content)), sum[:]))
out := readOutput(t, rig.wait(ch))
if out.Text != string(content) {
t.Fatalf("text = %q", out.Text)
}
}
// TestReadFileIgnoresStaleStreamFromEarlierCall covers the live race that
// surfaced as "Path traversal detected": once the server rejects a transfer (the
// size gate is the usual reason) the client keeps streaming the rest of its
// batch on the sub-connection it opened for that earlier call. Those late bytes
// must be dropped, not adopted as the new call's stream — adopting them failed
// the fresh call with a traversal error, and the stale connection closing would
// have failed it as "connection lost" too.
func TestReadFileIgnoresStaleStreamFromEarlierCall(t *testing.T) {
shortenTransferTimeouts(t, 500*time.Millisecond, 5*time.Second, 5*time.Millisecond)
rig := newFileRig(t)
stale := rig.newSub() // the rejected earlier call's data sub-conn
ch, _, targetDir := rig.startReadCall(`{"id":"1001","path":"C:\\b.txt"}`)
content := []byte("good")
name := targetDir + "b.txt"
rig.s.OnTransferPacket(stale, chunkPacket(7, 0, 1, 3<<20, 0, 0,
`C:\Users\tmp\yama-mcp-read-old\big.bin`, []byte("zz")))
empty := sha256.Sum256(nil)
rig.s.OnTransferPacket(stale, completePacket(7, 0, 0, empty[:]))
stream := rig.newSub() // opened after the download request, as Windows does
rig.s.OnTransferPacket(stream, chunkPacket(42, 0, 1, uint64(len(content)), 0, ffV2LastChunk, name, content))
sum := sha256.Sum256(content)
rig.s.OnTransferPacket(stream, completePacket(42, 0, uint64(len(content)), sum[:]))
out := readOutput(t, rig.wait(ch))
if out.Text != string(content) {
t.Fatalf("text = %q, want %q", out.Text, content)
}
if out.SHA256 != hex.EncodeToString(sum[:]) {
t.Fatalf("sha256 = %s, want %s", out.SHA256, hex.EncodeToString(sum[:]))
}
}
// TestReadFileClosesStreamSubConn checks that the call hangs up the client's
// data sub-connection when it ends, so a batch the server stopped reading does
// not keep streaming in the background.
func TestReadFileClosesStreamSubConn(t *testing.T) {
shortenTransferTimeouts(t, time.Second, 5*time.Second, 5*time.Millisecond)
rig := newFileRig(t)
ch, _, targetDir := rig.startReadCall(`{"id":"1001","path":"C:\\c.txt"}`)
content := []byte("bye")
stream := rig.newSub()
rig.s.OnTransferPacket(stream, chunkPacket(1, 0, 1, uint64(len(content)), 0, ffV2LastChunk,
targetDir+"c.txt", content))
sum := sha256.Sum256(content)
rig.s.OnTransferPacket(stream, completePacket(1, 0, uint64(len(content)), sum[:]))
readOutput(t, rig.wait(ch))
if !stream.IsClosed() {
t.Fatal("data sub-conn is still open after the call returned")
}
}
func TestReadFileDownloadErrorMapping(t *testing.T) {
cases := []struct {
win32 int
code int
frag string
}{
{2, CodeNotFound, "does not exist"},
{3, CodeNotFound, "does not exist"},
{5, CodePermission, "Access denied"},
{87, CodeInternal, "could not queue"},
}
for _, c := range cases {
shortenTransferTimeouts(t, time.Second, 5*time.Second, 5*time.Millisecond)
rig := newFileRig(t)
ch, fm, _ := rig.startReadCall(`{"id":"1001","path":"C:\\missing.txt"}`)
rig.s.OnTransferPacket(fm, downloadErrorPacket(uint32(c.win32)))
got := rig.wait(ch)
if got.err == nil || got.err.Code != c.code {
t.Fatalf("win32=%d error = %+v, want code %d", c.win32, got.err, c.code)
}
if !strings.Contains(got.err.Message, c.frag) {
t.Fatalf("win32=%d message = %q, want %q", c.win32, got.err.Message, c.frag)
}
}
}
func TestReadFileOutOfOrderChunkRejected(t *testing.T) {
shortenTransferTimeouts(t, time.Second, 5*time.Second, 5*time.Millisecond)
rig := newFileRig(t)
ch, _, targetDir := rig.startReadCall(`{"id":"1001","path":"C:\\a.txt"}`)
stream := rig.newSub()
rig.s.OnTransferPacket(stream, chunkPacket(1, 0, 1, 10, 4, 0, targetDir+"a.txt", []byte("4567")))
c := rig.wait(ch)
if c.err == nil || c.err.Code != CodeInternal {
t.Fatalf("error = %+v, want -32000", c.err)
}
if !strings.Contains(c.err.Message, "offset") {
t.Fatalf("message = %q", c.err.Message)
}
}
func TestReadFileTraversalChunkRejected(t *testing.T) {
shortenTransferTimeouts(t, time.Second, 5*time.Second, 5*time.Millisecond)
rig := newFileRig(t)
ch, _, _ := rig.startReadCall(`{"id":"1001","path":"C:\\a.txt"}`)
stream := rig.newSub()
rig.s.OnTransferPacket(stream, chunkPacket(1, 0, 1, 5, 0, ffV2LastChunk, `..\..\evil`, []byte("hello")))
c := rig.wait(ch)
if c.err == nil || c.err.Code != CodeInternal {
t.Fatalf("error = %+v, want -32000", c.err)
}
if !strings.Contains(c.err.Message, "Path traversal") {
t.Fatalf("message = %q", c.err.Message)
}
}
func TestReadFileStallTimesOut(t *testing.T) {
shortenTransferTimeouts(t, 150*time.Millisecond, 5*time.Second, 10*time.Millisecond)
rig := newFileRig(t)
ch, _, targetDir := rig.startReadCall(`{"id":"1001","path":"C:\\a.txt"}`)
stream := rig.newSub()
rig.s.OnTransferPacket(stream, chunkPacket(1, 0, 1, 10, 0, 0, targetDir+"a.txt", []byte("12345")))
c := rig.wait(ch)
if c.err == nil || c.err.Code != CodeTimeout {
t.Fatalf("error = %+v, want -32001", c.err)
}
if !strings.Contains(c.err.Message, "stalled") {
t.Fatalf("message = %q", c.err.Message)
}
}
func TestReadFileStreamClosedFailsFast(t *testing.T) {
shortenTransferTimeouts(t, 10*time.Second, 20*time.Second, 10*time.Millisecond)
rig := newFileRig(t)
ch, _, targetDir := rig.startReadCall(`{"id":"1001","path":"C:\\a.txt"}`)
stream := rig.newSub()
rig.s.OnTransferPacket(stream, chunkPacket(1, 0, 1, 10, 0, 0, targetDir+"a.txt", []byte("12345")))
_ = stream.Close()
c := rig.wait(ch)
if c.err == nil || c.err.Code != CodeTimeout {
t.Fatalf("error = %+v, want -32001", c.err)
}
if !strings.Contains(c.err.Message, "Connection lost") {
t.Fatalf("message = %q", c.err.Message)
}
}
func TestReadFileRequiresV2Capability(t *testing.T) {
rig := newFileRig(t)
rig.h.Register(&hub.Device{ID: "1001", PeerIP: "10.0.0.1"}, rig.main) // no capability
ch := rig.callRead(`{"id":"1001","path":"C:\\a.txt"}`)
c := rig.wait(ch)
if c.err == nil || c.err.Code != CodeUnsupported {
t.Fatalf("error = %+v, want -32005", c.err)
}
rig.expectNothing()
}
// ----- text decoding and windowing ------------------------------------------
func TestBuildReadFileResultGBK(t *testing.T) {
rawGBK := protocol.UTF8ToGBK("中文\r\nabc")
res := buildReadFileResult("/tmp/x.conf", rawGBK, "abc", "auto", 0, 2000, 262144)
out := res.StructuredContent.(readFileOutput)
if out.Encoding != "gbk" || out.EOL != "crlf" {
t.Fatalf("encoding=%q eol=%q", out.Encoding, out.EOL)
}
if out.Text != "中文\nabc" || out.LinesTotal != 2 {
t.Fatalf("text=%q lines_total=%d", out.Text, out.LinesTotal)
}
if !strings.Contains(res.Content[0].Text, "[read_file] /tmp/x.conf") {
t.Fatalf("head line = %q", res.Content[0].Text)
}
}
func TestBuildReadFileResultNegativeOffset(t *testing.T) {
res := buildReadFileResult("x", []byte("a\nb\nc\n"), "s", "auto", -2, 2000, 262144)
out := res.StructuredContent.(readFileOutput)
if out.Offset != 1 || out.Text != "b\nc" || out.LinesReturned != 2 || out.Truncated {
t.Fatalf("output = %+v", out)
}
}
func TestBuildReadFileResultLimit(t *testing.T) {
res := buildReadFileResult("x", []byte("a\nb\nc\n"), "s", "auto", 0, 1, 262144)
out := res.StructuredContent.(readFileOutput)
if out.Text != "a" || out.LinesReturned != 1 || !out.Truncated {
t.Fatalf("output = %+v", out)
}
}
func TestBuildReadFileResultMaxBytesCutOnCharBoundary(t *testing.T) {
line := strings.Repeat("中", 400) // 1200 UTF-8 bytes, one line
res := buildReadFileResult("x", []byte(line), "s", "auto", 0, 2000, 1024)
out := res.StructuredContent.(readFileOutput)
if !out.Truncated || out.LinesReturned != 1 {
t.Fatalf("truncated=%v lines_returned=%d", out.Truncated, out.LinesReturned)
}
if len(out.Text) != 1023 || !utf8.ValidString(out.Text) {
t.Fatalf("cut text is %d bytes and valid=%v, want 1023 valid bytes", len(out.Text), utf8.ValidString(out.Text))
}
}
func TestBuildReadFileResultEncodings(t *testing.T) {
// UTF-16LE with BOM.
le := []byte{0xFF, 0xFE, 'h', 0, 'i', 0}
if out := buildReadFileResult("x", le, "s", "auto", 0, 10, 1024).StructuredContent.(readFileOutput); out.Encoding != "utf-16le" || out.Text != "hi" {
t.Fatalf("utf-16le output = %+v", out)
}
// UTF-8 BOM is stripped.
bom := append([]byte{0xEF, 0xBB, 0xBF}, []byte("hi")...)
if out := buildReadFileResult("x", bom, "s", "auto", 0, 10, 1024).StructuredContent.(readFileOutput); out.Encoding != "utf-8" || out.Text != "hi" {
t.Fatalf("utf-8 bom output = %+v", out)
}
// Latin-1 is explicit only (byte 0xE9 would otherwise be invalid UTF-8 → GBK).
if out := buildReadFileResult("x", []byte{0xE9}, "s", "latin1", 0, 10, 1024).StructuredContent.(readFileOutput); out.Encoding != "latin1" || out.Text != "é" {
t.Fatalf("latin1 output = %+v", out)
}
}
func TestDetectEOLVariants(t *testing.T) {
cases := map[string]string{
"": "none",
"abc": "none",
"a\r\nb": "crlf",
"a\nb": "lf",
"a\rb": "cr",
"a\r\nb\n": "mixed",
}
for in, want := range cases {
if got := detectEOL(in); got != want {
t.Errorf("detectEOL(%q) = %q, want %q", in, got, want)
}
}
}
func TestSplitTextLines(t *testing.T) {
if got := splitTextLines(""); got != nil {
t.Fatalf("empty text = %v", got)
}
if got := splitTextLines("a\nb\n"); len(got) != 2 || got[1] != "b" {
t.Fatalf("a\\nb\\n = %v", got)
}
if got := splitTextLines("\n"); len(got) != 1 || got[0] != "" {
t.Fatalf("\\n = %v", got)
}
}
+48
View File
@@ -0,0 +1,48 @@
package mcp
import "encoding/json"
// request is one JSON-RPC 2.0 call. The MCP endpoint is stateless, so there is
// nothing else to track between requests.
type request struct {
JSONRPC string `json:"jsonrpc"`
ID json.RawMessage `json:"id"`
Method string `json:"method"`
Params json.RawMessage `json:"params"`
}
// isNotification reports whether the caller omitted "id". Such requests get
// no JSON-RPC response at all (MCP uses them for notifications/initialized).
func (r *request) isNotification() bool { return len(r.ID) == 0 }
// response is a single JSON-RPC 2.0 reply. Exactly one of Result/Error is set.
type response struct {
JSONRPC string `json:"jsonrpc"`
ID json.RawMessage `json:"id"`
Result any `json:"result,omitempty"`
Error *rpcError `json:"error,omitempty"`
}
// idOrNull keeps the reply valid when the request id is missing or malformed:
// JSON-RPC allows "id": null on errors that cannot be correlated.
func idOrNull(id json.RawMessage) json.RawMessage {
if len(id) == 0 {
return json.RawMessage("null")
}
return id
}
func resultResponse(id json.RawMessage, result any) *response {
return &response{JSONRPC: "2.0", ID: idOrNull(id), Result: result}
}
func errorResponse(id json.RawMessage, err *rpcError) *response {
return &response{JSONRPC: "2.0", ID: idOrNull(id), Error: err}
}
// toolCallParams is the tools/call payload. Arguments stay raw so each tool
// decodes only the fields it understands (and reports -32602 itself).
type toolCallParams struct {
Name string `json:"name"`
Arguments json.RawMessage `json:"arguments"`
}
+87
View File
@@ -0,0 +1,87 @@
package mcp
import (
"encoding/json"
"fmt"
"sync"
"time"
)
// localReadTools answer from the server's own state (device hub, history,
// audit file) and never open a channel to a client. Everything else is assumed
// to act on one host, so a call that names an id takes that host's lock.
var localReadTools = map[string]bool{
"list_hosts": true,
"get_host_detail": true,
"get_server_status": true,
"get_audit_log": true,
}
// deviceLocks enforces one in-flight device operation per host. The lock is
// per device, not per channel: the client can share state between the main
// connection and its sub-connections, so overlapping commands only make the
// situation harder to reason about (design §9).
type deviceLocks struct {
mu sync.Mutex
held map[string]deviceHold
}
// deviceHold describes the call currently owning a device, so a rejection can
// tell the caller who is in the way and for how long.
type deviceHold struct {
tool string
since time.Time
}
func newDeviceLocks() *deviceLocks {
return &deviceLocks{held: make(map[string]deviceHold)}
}
// tryAcquire takes the device lock without waiting. The second return value is
// false when another call holds it; held then describes that call.
func (l *deviceLocks) tryAcquire(deviceID, tool string) (held deviceHold, ok bool) {
l.mu.Lock()
defer l.mu.Unlock()
if h, busy := l.held[deviceID]; busy {
return h, false
}
l.held[deviceID] = deviceHold{tool: tool, since: time.Now()}
return deviceHold{}, true
}
func (l *deviceLocks) release(deviceID string) {
l.mu.Lock()
delete(l.held, deviceID)
l.mu.Unlock()
}
// deviceIDFromArgs extracts the one host a tool call targets. Tools with a
// batch `ids` array are handled by their handler one id at a time (matching the
// Win32 server); this function deliberately looks only at the single-host
// spellings.
func deviceIDFromArgs(raw json.RawMessage) string {
if len(raw) == 0 || string(raw) == "null" {
return ""
}
var args struct {
ID string `json:"id"`
DeviceID string `json:"device_id"`
}
if err := json.Unmarshal(raw, &args); err != nil {
// Malformed arguments are reported by the handler as -32602; there is
// no device to lock here.
return ""
}
if args.ID != "" {
return args.ID
}
return args.DeviceID
}
// busyMessage mirrors the Win32 server's -32003 text:
// "Device busy: another request is pending for this host (tool=..., elapsed=Ns)".
func busyMessage(held deviceHold) string {
return fmt.Sprintf(
"Device busy: another request is pending for this host (tool=%s, elapsed=%ds)",
held.tool, int(time.Since(held.since).Seconds()))
}
+310
View File
@@ -0,0 +1,310 @@
package mcp
import (
"context"
"encoding/json"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/logger"
)
// blockingListFiles installs a list_files handler that blocks while id ==
// blockID, so a second call for that host can be checked against the lock.
func blockingListFiles(t *testing.T, s *Server, blockID string) (entered chan struct{}, release func()) {
t.Helper()
entered = make(chan struct{})
done := make(chan struct{})
var once sync.Once
s.handlers["list_files"] = func(_ context.Context, args json.RawMessage) (any, *rpcError) {
var a struct {
ID string `json:"id"`
}
_ = json.Unmarshal(args, &a)
if a.ID == blockID {
once.Do(func() { close(entered) })
<-done
}
return newToolResult("ok", map[string]any{"id": a.ID}), nil
}
return entered, func() { close(done) }
}
func listFilesCall(t *testing.T, s *Server, id string) (any, *rpcError) {
t.Helper()
return s.callTool(context.Background(), json.RawMessage(
`{"name":"list_files","arguments":{"id":"`+id+`","path":"/"}}`))
}
func TestDeviceLockRejectsSecondCall(t *testing.T) {
s := testServer(t, false)
entered, release := blockingListFiles(t, s, "1001")
type outcome struct {
res any
err *rpcError
}
first := make(chan outcome, 1)
go func() {
res, rerr := listFilesCall(t, s, "1001")
first <- outcome{res, rerr}
}()
<-entered
_, rerr := listFilesCall(t, s, "1001")
if rerr == nil || rerr.Code != CodeBusy {
t.Fatalf("second same-host call error = %+v, want -32003", rerr)
}
if !strings.Contains(rerr.Message, "tool=list_files") || !strings.Contains(rerr.Message, "elapsed=") {
t.Fatalf("busy message = %q, want tool and elapsed", rerr.Message)
}
// A different host is a different lock and must not be blocked.
if _, rerr = listFilesCall(t, s, "2002"); rerr != nil {
t.Fatalf("other-host call error = %+v, want success", rerr)
}
release()
if got := <-first; got.err != nil {
t.Fatalf("first call error = %+v, want success", got.err)
}
// The lock is released once the call returns.
if _, rerr = listFilesCall(t, s, "1001"); rerr != nil {
t.Fatalf("call after release error = %+v, want success", rerr)
}
}
func TestDeviceLockReleasedOnContextCancel(t *testing.T) {
s := testServer(t, false)
entered := make(chan struct{})
var once sync.Once
s.handlers["list_files"] = func(ctx context.Context, _ json.RawMessage) (any, *rpcError) {
once.Do(func() { close(entered) })
<-ctx.Done()
return nil, errf(CodeTimeout, "request cancelled")
}
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
go func() {
defer close(done)
_, _ = s.callTool(ctx, json.RawMessage(
`{"name":"list_files","arguments":{"id":"1001"}}`))
}()
<-entered
cancel()
<-done
// Replace the cancelling handler before reusing the host: the lock must
// already be free, and this handler returns immediately.
s.handlers["list_files"] = func(_ context.Context, _ json.RawMessage) (any, *rpcError) {
return newToolResult("ok", map[string]any{"id": "1001"}), nil
}
if _, rerr := listFilesCall(t, s, "1001"); rerr != nil {
t.Fatalf("call after cancel error = %+v, want success (lock must be free)", rerr)
}
}
func TestGlobalConcurrencyGate(t *testing.T) {
log := logger.New(logger.Config{Level: logger.LevelError,
File: filepath.Join(t.TempDir(), "mcp-test.log")})
t.Cleanup(func() { _ = log.Close() })
s := New(Config{Token: testToken, MaxConcurrency: 1, Log: log})
entered, release := blockingListFiles(t, s, "1001")
type outcome struct {
res any
err *rpcError
}
first := make(chan outcome, 1)
go func() {
res, rerr := listFilesCall(t, s, "1001")
first <- outcome{res, rerr}
}()
<-entered
// A different host still needs a global slot, and there is only one.
_, rerr := listFilesCall(t, s, "2002")
if rerr == nil || rerr.Code != CodeBusy {
t.Fatalf("second call error = %+v, want -32003", rerr)
}
if !strings.Contains(rerr.Message, "concurrent") {
t.Fatalf("concurrency message = %q", rerr.Message)
}
release()
if got := <-first; got.err != nil {
t.Fatalf("first call error = %+v", got.err)
}
if _, rerr = listFilesCall(t, s, "2002"); rerr != nil {
t.Fatalf("call after slot freed error = %+v, want success", rerr)
}
}
// readAuditRecords returns the audit JSON lines written so far.
func readAuditRecords(t *testing.T, path string) []map[string]any {
t.Helper()
data, err := os.ReadFile(path)
if err != nil {
t.Fatalf("read audit file: %v", err)
}
var out []map[string]any
for line := range strings.SplitSeq(strings.TrimSpace(string(data)), "\n") {
if line == "" {
continue
}
var rec map[string]any
if err := json.Unmarshal([]byte(line), &rec); err != nil {
t.Fatalf("parse audit line %q: %v", line, err)
}
out = append(out, rec)
}
return out
}
func TestToolCallAudit(t *testing.T) {
dir := t.TempDir()
auditPath := filepath.Join(dir, "audit.log")
log := logger.New(logger.Config{
Level: logger.LevelError,
File: filepath.Join(dir, "server.log"),
AuditFile: auditPath,
})
t.Cleanup(func() { _ = log.Close() })
s := New(Config{Token: testToken, Log: log})
s.handlers["terminal_exec"] = func(_ context.Context, _ json.RawMessage) (any, *rpcError) {
return newToolResult("done", map[string]any{"output": "secret-output"}), nil
}
text, _, rerr := callLocal(t, s, "terminal_exec",
`{"id":"1001","command":"mysql -pTopSecret --batch"}`)
if rerr != nil {
t.Fatalf("terminal_exec error = %+v (text %q)", rerr, text)
}
if _, _, rerr = callLocal(t, s, "nope", `{}`); rerr == nil || rerr.Code != CodeMethodNotFound {
t.Fatalf("unknown tool error = %+v, want -32601", rerr)
}
// A local tool has no device and must audit device "-".
if _, _, rerr = callLocal(t, s, "get_server_status", `{}`); rerr != nil {
t.Fatalf("get_server_status error = %+v", rerr)
}
recs := readAuditRecords(t, auditPath)
if len(recs) != 3 {
t.Fatalf("audit records = %d, want 3", len(recs))
}
ok := recs[0]
if ok["event"] != "mcp.tool.call" || ok["actor"] != "mcp" || ok["role"] != "admin" || ok["source"] != "mcp" {
t.Fatalf("identity fields = %v", ok)
}
if ok["tool"] != "terminal_exec" || ok["device"] != "1001" {
t.Fatalf("tool/device = %v/%v", ok["tool"], ok["device"])
}
if ok["ok"] != true || ok["code"].(float64) != 0 {
t.Fatalf("ok/code = %v/%v", ok["ok"], ok["code"])
}
if _, hasMS := ok["ms"]; !hasMS {
t.Fatal("missing ms")
}
args, _ := ok["args"].(string)
if !strings.Contains(args, "mysql (len=") {
t.Fatalf("args = %q, want first word + length", args)
}
if strings.Contains(args, "TopSecret") {
t.Fatalf("args leaked the command body: %q", args)
}
if res, _ := ok["result"].(string); !strings.Contains(res, "bytes") {
t.Fatalf("result = %q, want byte summary", res)
}
bad := recs[1]
if bad["tool"] != "nope" || bad["ok"] != false || bad["code"].(float64) != CodeMethodNotFound {
t.Fatalf("failed call record = %v", bad)
}
if bad["device"] != "-" {
t.Fatalf("unknown tool device = %v, want -", bad["device"])
}
if res, _ := bad["result"].(string); !strings.Contains(res, "unknown tool") {
t.Fatalf("failure result = %q", res)
}
local := recs[2]
if local["tool"] != "get_server_status" || local["device"] != "-" || local["ok"] != true {
t.Fatalf("local tool record = %v", local)
}
}
// A panicking handler must not take the connection down and must not be
// audited as a success.
func TestToolCallPanicAuditedAsFailure(t *testing.T) {
dir := t.TempDir()
auditPath := filepath.Join(dir, "audit.log")
log := logger.New(logger.Config{
Level: logger.LevelError,
File: filepath.Join(dir, "server.log"),
AuditFile: auditPath,
})
t.Cleanup(func() { _ = log.Close() })
s := New(Config{Token: testToken, Log: log})
s.handlers["terminal_exec"] = func(_ context.Context, _ json.RawMessage) (any, *rpcError) {
panic("boom")
}
if _, rerr := s.callTool(context.Background(), json.RawMessage(
`{"name":"terminal_exec","arguments":{"id":"1001","command":"dir"}}`)); rerr == nil ||
rerr.Code != CodeInternal {
t.Fatalf("panic call error = %+v, want -32000", rerr)
}
recs := readAuditRecords(t, auditPath)
if len(recs) != 1 {
t.Fatalf("audit records = %d, want 1", len(recs))
}
if recs[0]["ok"] != false || recs[0]["code"].(float64) != CodeInternal {
t.Fatalf("panic record = %v, want ok=false code=-32000", recs[0])
}
// The host lock must be free again despite the panic.
s.handlers["terminal_exec"] = func(_ context.Context, _ json.RawMessage) (any, *rpcError) {
return newToolResult("ok", nil), nil
}
if _, rerr := s.callTool(context.Background(), json.RawMessage(
`{"name":"terminal_exec","arguments":{"id":"1001"}}`)); rerr != nil {
t.Fatalf("call after panic error = %+v, want success", rerr)
}
}
func TestSummarizeArgsRedactsSensitiveValues(t *testing.T) {
got := summarizeArgs(json.RawMessage(`{
"id": "1001",
"command": "mysql -pTopSecret --batch",
"text": "hello secret",
"message": "msg secret",
"body": "{\"key\":\"secret\"}",
"headers": {"Authorization": "Bearer tok"},
"password": "pw"
}`))
for _, leak := range []string{"TopSecret", "hello secret", "msg secret", "Bearer tok", "pw"} {
if strings.Contains(got, leak) {
t.Fatalf("args leaked %q: %s", leak, got)
}
}
if !strings.Contains(got, "mysql (len=") {
t.Fatalf("command digest missing: %s", got)
}
if !strings.Contains(got, "redacted(") {
t.Fatalf("redaction marker missing: %s", got)
}
if len(got) > auditArgsMaxBytes {
t.Fatalf("digest = %d bytes, want <= %d", len(got), auditArgsMaxBytes)
}
// The ellipsis counts toward the cap.
long := summarizeArgs(json.RawMessage(`{"note":"` + strings.Repeat("a", 800) + `"}`))
if len(long) > auditArgsMaxBytes || !strings.HasSuffix(long, "…") {
t.Fatalf("truncated digest = %d bytes, tail %q", len(long), long[len(long)-3:])
}
}
+424
View File
@@ -0,0 +1,424 @@
package mcp
import (
"bytes"
"context"
"encoding/base64"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"image"
"image/jpeg"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/connection"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/hub"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/protocol"
)
// get_screenshot uses the main-connection preview RPC
// (COMMAND_SCREEN_PREVIEW_REQ → TOKEN_SCREEN_PREVIEW_RSP): the client captures,
// scales and encodes the frame itself, so the request opens no sub-connection
// and competes with nobody for the per-device screen slot (design §7.1).
const (
screenPreviewDefaultWidth = 1024
screenPreviewMinWidth = 64
screenPreviewMaxWidth = 1920
screenPreviewJPEGQuality = 80
// screenPreviewRspHeaderLen is sizeof(ScreenPreviewRspHeader) with
// #pragma pack(1) (common/commands.h); the image bytes follow directly.
screenPreviewRspHeaderLen = 16
screenPreviewOffReqID = 1
screenPreviewOffStatus = 3
screenPreviewOffFormat = 4
screenPreviewOffWidth = 5
screenPreviewOffHeight = 7
screenPreviewOffBytes = 9
)
// ScreenPreviewStatus / ScreenPreviewFormat values (common/commands.h). Only
// two formats exist on the wire: Windows clients send JPEG, Linux clients send
// BGRX because they carry no JPEG encoder — the server encodes it here.
const (
screenPreviewStatusOK byte = 0
screenPreviewStatusCaptureFailed byte = 1
screenPreviewStatusEncodeFailed byte = 2
screenPreviewStatusNotSupported byte = 3
screenPreviewStatusBadTarget byte = 4
screenPreviewFmtJPEG byte = 0
screenPreviewFmtBGRX byte = 3
)
// screenPreviewTimeout bounds one round trip. It is a variable rather than a
// constant only so tests can shorten it; production code never changes it.
// There is deliberately no cancellation on timeout: the request rides the
// device's main connection, where MFC likewise refuses CancelIO (§7.4) — the
// pending entry is dropped and a late reply fails the reqId match.
var screenPreviewTimeout = 8 * time.Second
// screenshotArgs is the published inputSchema as Go. Pointer fields separate
// "absent" from an explicit value: mode=screen must still reject the
// region/window/monitor parameters instead of silently ignoring them.
type screenshotArgs struct {
ID string `json:"id"`
MaxWidth *int `json:"max_width"`
Mode string `json:"mode"`
HWND *json.RawMessage `json:"hwnd"`
X *int `json:"x"`
Y *int `json:"y"`
Width *int `json:"width"`
Height *int `json:"height"`
Monitor *int `json:"monitor"`
}
// screenshotImage / screenshotCapture are the structuredContent fields the
// shared outputSchema defines. Fields the v1 RPC cannot report are omitted
// rather than faked (design §3.2).
type screenshotImage struct {
MimeType string `json:"mimeType"`
Width int `json:"width"`
Height int `json:"height"`
Bytes int `json:"bytes"`
}
type screenshotCapture struct {
Mode string `json:"mode"`
}
type screenshotOutput struct {
Image screenshotImage `json:"image"`
Capture screenshotCapture `json:"capture"`
}
// previewReply is one decoded TOKEN_SCREEN_PREVIEW_RSP.
type previewReply struct {
status byte
format byte
width uint16
height uint16
payload []byte
}
// previewRequest is one in-flight screenshot. ch is buffered so delivery never
// blocks the TCP read loop.
type previewRequest struct {
reqID uint16
ch chan previewReply
}
// previewTable matches a client reply to the call waiting for it. The
// per-device call lock already serialises MCP screenshots, so at most one
// entry exists per device; responses are still keyed by device because the
// reply itself carries no device id — only the connection does.
type previewTable struct {
mu sync.Mutex
byDevice map[string]*previewRequest
nextID atomic.Uint32
}
func newPreviewTable() *previewTable {
return &previewTable{byDevice: make(map[string]*previewRequest)}
}
// nextReqID mirrors MFC's NextPreviewReqId: increment and skip 0, which would
// otherwise match an "unset" reqId on the client side.
func (t *previewTable) nextReqID() uint16 {
for {
if v := uint16(t.nextID.Add(1)); v != 0 {
return v
}
}
}
// begin reserves the device's single preview slot. nil means another request
// is already pending (only possible if the call lock was bypassed).
func (t *previewTable) begin(deviceID string) *previewRequest {
t.mu.Lock()
defer t.mu.Unlock()
if _, ok := t.byDevice[deviceID]; ok {
return nil
}
r := &previewRequest{reqID: t.nextReqID(), ch: make(chan previewReply, 1)}
t.byDevice[deviceID] = r
return r
}
// cancel drops a pending slot unless it was already delivered. The pointer
// check keeps a slow caller from deleting a newer request for the same device.
func (t *previewTable) cancel(deviceID string, r *previewRequest) {
t.mu.Lock()
defer t.mu.Unlock()
if t.byDevice[deviceID] == r {
delete(t.byDevice, deviceID)
}
}
// deliver hands a matching reply to its waiter. A reply whose reqId does not
// match — an expired request or one from another caller — is dropped, exactly
// like MFC's TakePreviewResponse.
func (t *previewTable) deliver(deviceID string, reqID uint16, reply previewReply) bool {
t.mu.Lock()
r, ok := t.byDevice[deviceID]
if !ok || r.reqID != reqID {
t.mu.Unlock()
return false
}
delete(t.byDevice, deviceID)
t.mu.Unlock()
r.ch <- reply // buffered, and the entry is gone: nobody else can send
return true
}
func (s *Server) registerScreenTools() {
s.handlers["get_screenshot"] = s.callGetScreenshot
}
// OnPacket feeds one packet from a device connection to the MCP layer. It
// reports whether MCP consumed the packet; anything MCP does not own returns
// false and falls through to cmd's normal command dispatch.
func (s *Server) OnPacket(ctx *connection.Context, data []byte) bool {
if s == nil || len(data) == 0 || data[0] != protocol.TokenScreenPreviewRsp {
return false
}
deviceID := ctx.GetInfo().ClientID
rsp, err := parseScreenPreviewRsp(data)
if err != nil {
s.log.Warn("malformed screen preview response from conn %d (device=%q): %v",
ctx.ID, deviceID, err)
return true
}
if deviceID != "" {
s.previews.deliver(deviceID, rsp.reqID, rsp.reply)
}
return true
}
// parseScreenPreviewRsp validates the 16-byte header and copies the image
// bytes out of the TCP read buffer. A declared length that overruns the packet
// marks the whole response malformed: the client would otherwise hand us an
// under-filled image.
func parseScreenPreviewRsp(data []byte) (struct {
reqID uint16
reply previewReply
}, error) {
var rsp struct {
reqID uint16
reply previewReply
}
if len(data) < screenPreviewRspHeaderLen {
return rsp, fmt.Errorf("packet is %d bytes, want at least %d",
len(data), screenPreviewRspHeaderLen)
}
if data[0] != protocol.TokenScreenPreviewRsp {
return rsp, fmt.Errorf("token %d, want %d", data[0], protocol.TokenScreenPreviewRsp)
}
rsp.reqID = binary.LittleEndian.Uint16(data[screenPreviewOffReqID:])
rsp.reply.status = data[screenPreviewOffStatus]
rsp.reply.format = data[screenPreviewOffFormat]
rsp.reply.width = binary.LittleEndian.Uint16(data[screenPreviewOffWidth:])
rsp.reply.height = binary.LittleEndian.Uint16(data[screenPreviewOffHeight:])
n := binary.LittleEndian.Uint32(data[screenPreviewOffBytes:])
if avail := len(data) - screenPreviewRspHeaderLen; n > uint32(avail) {
return rsp, fmt.Errorf("declares %d image bytes but only %d follow", n, avail)
}
rsp.reply.payload = append([]byte(nil), data[screenPreviewRspHeaderLen:screenPreviewRspHeaderLen+int(n)]...)
return rsp, nil
}
// buildScreenPreviewReq renders the 8-byte v1 request (whole virtual desktop).
// v2 (region/window/monitor) is gated behind CLIENT_CAP_SCREEN_REGION and is
// not implemented by this server build.
func buildScreenPreviewReq(reqID, maxWidth uint16, quality byte) []byte {
buf := make([]byte, 8)
buf[0] = protocol.CommandScreenPreviewReq
binary.LittleEndian.PutUint16(buf[1:3], reqID)
binary.LittleEndian.PutUint16(buf[3:5], maxWidth)
buf[5] = quality
return buf
}
// callGetScreenshot captures one frame through the main-connection RPC.
func (s *Server) callGetScreenshot(ctx context.Context, raw json.RawMessage) (any, *rpcError) {
if s.cfg.Hub == nil {
return nil, errf(CodeInternal, "server device registry is not configured")
}
var args screenshotArgs
if rerr := decodeArgs(raw, &args); rerr != nil {
return nil, rerr
}
if args.ID == "" {
return nil, errf(CodeInvalidParams, "Missing required parameter: id")
}
if !isDecimalID(args.ID) {
return nil, errf(CodeInvalidParams, "Invalid id: expected a decimal host id string")
}
if s.cfg.Hub.MainConn(args.ID) == nil {
return nil, errf(CodeOffline, "Host not found or offline: %s", args.ID)
}
if !protocol.SupportsCap(s.cfg.Hub.Capability(args.ID), protocol.ClientCapScreenPreview) {
return nil, errf(CodeUnsupported,
"Host does not support screen preview: the client does not declare CLIENT_CAP_SCREEN_PREVIEW (upgrade the client)")
}
mode := strings.TrimSpace(args.Mode)
if mode == "" {
mode = "screen"
}
if mode != "screen" {
switch mode {
case "region", "window", "monitor":
return nil, errf(CodeUnsupported,
"mode=%s needs the CLIENT_CAP_SCREEN_REGION extension, which this server build does not implement; use mode=screen", mode)
default:
return nil, errf(CodeInvalidParams,
"Invalid mode: %s (expect screen|region|window|monitor)", mode)
}
}
if name := firstRegionParam(&args); name != "" {
return nil, errf(CodeUnsupported,
"parameter %q needs the CLIENT_CAP_SCREEN_REGION extension, which this server build does not implement; use mode=screen with only id and max_width", name)
}
maxWidth := screenPreviewDefaultWidth
if args.MaxWidth != nil && *args.MaxWidth > 0 {
maxWidth = min(max(*args.MaxWidth, screenPreviewMinWidth), screenPreviewMaxWidth)
}
req := s.previews.begin(args.ID)
if req == nil {
return nil, errf(CodeBusy,
"Device busy: another screenshot request is already pending for host %s", args.ID)
}
defer s.previews.cancel(args.ID, req)
if err := s.cfg.Hub.SendToDevice(args.ID,
buildScreenPreviewReq(req.reqID, uint16(maxWidth), screenPreviewJPEGQuality)); err != nil {
if errors.Is(err, hub.ErrDeviceOffline) {
return nil, errf(CodeOffline, "Host not found or offline: %s", args.ID)
}
return nil, errf(CodeSendFailed, "Failed to send screenshot request to host: %v", err)
}
timer := time.NewTimer(screenPreviewTimeout)
defer timer.Stop()
select {
case reply := <-req.ch:
return screenshotResult(reply, mode)
case <-timer.C:
return nil, errf(CodeTimeout,
"Timeout waiting for the screenshot (the host did not answer in %s; a client without screen-preview support cannot be asked)", screenPreviewTimeout)
case <-ctx.Done():
return nil, errf(CodeTimeout, "Request cancelled while waiting for the screenshot")
}
}
// firstRegionParam names the first v2 capture parameter present in the call.
// Checked in schema order so the error message is deterministic.
func firstRegionParam(args *screenshotArgs) string {
switch {
case args.HWND != nil:
return "hwnd"
case args.X != nil:
return "x"
case args.Y != nil:
return "y"
case args.Width != nil:
return "width"
case args.Height != nil:
return "height"
case args.Monitor != nil:
return "monitor"
}
return ""
}
// screenshotResult maps the device status/format onto the MCP result. Status 4
// is a caller-visible parameter problem (target invalid), so it keeps -32602;
// capture/encode failures are -32000 because retrying the same call cannot fix
// them.
func screenshotResult(reply previewReply, mode string) (any, *rpcError) {
switch reply.status {
case screenPreviewStatusOK:
case screenPreviewStatusCaptureFailed:
return nil, errf(CodeInternal, "Screenshot capture failed on the host (status 1)")
case screenPreviewStatusEncodeFailed:
return nil, errf(CodeInternal, "Screenshot encoding failed on the host (status 2)")
case screenPreviewStatusNotSupported:
return nil, errf(CodeUnsupported, "Host does not support screen capture (status 3)")
case screenPreviewStatusBadTarget:
return nil, errf(CodeInvalidParams, "Screenshot target is invalid (status 4)")
default:
return nil, errf(CodeInternal, "Screenshot failed with unknown status %d", reply.status)
}
w, h := int(reply.width), int(reply.height)
switch reply.format {
case screenPreviewFmtJPEG:
if len(reply.payload) == 0 {
return nil, errf(CodeInternal, "Screenshot response carries no image data")
}
return imageResult(reply.payload, w, h, mode), nil
case screenPreviewFmtBGRX:
jpg, err := bgrxToJPEG(reply.payload, w, h)
if err != nil {
return nil, errf(CodeInternal, "Malformed BGRX screenshot from host: %v", err)
}
// The reported width/height describe the pixels, which do not change in
// the JPEG encode; bytes describes what is actually returned.
return imageResult(jpg, w, h, mode), nil
default:
return nil, errf(CodeInternal, "Unsupported screenshot format %d", reply.format)
}
}
// bgrxToJPEG converts a top-down 4-byte-per-pixel B,G,R,X frame (Linux
// clients) into a JPEG. There is no row padding, and X is forced opaque.
func bgrxToJPEG(src []byte, w, h int) ([]byte, error) {
if w <= 0 || h <= 0 {
return nil, fmt.Errorf("invalid dimensions %dx%d", w, h)
}
if len(src) != w*h*4 {
return nil, fmt.Errorf("got %d bytes, want %d for %dx%d BGRX", len(src), w*h*4, w, h)
}
img := image.NewRGBA(image.Rect(0, 0, w, h))
for i := 0; i < w*h; i++ {
img.Pix[i*4+0] = src[i*4+2] // R ← B
img.Pix[i*4+1] = src[i*4+1] // G
img.Pix[i*4+2] = src[i*4+0] // B ← R
img.Pix[i*4+3] = 0xFF
}
var buf bytes.Buffer
if err := jpeg.Encode(&buf, img, &jpeg.Options{Quality: screenPreviewJPEGQuality}); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
// imageResult wraps the encoded JPEG in the MCP envelope: one image content
// item plus the metadata the outputSchema declares.
func imageResult(jpg []byte, w, h int, mode string) toolResult {
return toolResult{
Content: []contentItem{{
Type: "image",
Data: base64.StdEncoding.EncodeToString(jpg),
MimeType: "image/jpeg",
}},
StructuredContent: screenshotOutput{
Image: screenshotImage{
MimeType: "image/jpeg",
Width: w,
Height: h,
Bytes: len(jpg),
},
// v1 sends no ScreenCaptureMeta, so the source rect and scale are
// unknown; report the mode only rather than inventing values.
Capture: screenshotCapture{Mode: mode},
},
}
}
+458
View File
@@ -0,0 +1,458 @@
package mcp
import (
"bytes"
"context"
"encoding/base64"
"encoding/binary"
"image"
"image/color"
"image/jpeg"
"testing"
"time"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/connection"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/hub"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/protocol"
)
// screenRig is a live MCP server plus a hub whose main connection records the
// outbound screenshot requests. Tests answer them through OnPacket, i.e.
// exactly what cmd/main.go does from the TCP read loop.
type screenRig struct {
t *testing.T
s *Server
h *hub.Hub
main *connection.Context
writes chan []byte
}
func newScreenRig(t *testing.T, capability string) *screenRig {
t.Helper()
h := hub.New()
main := &connection.Context{RemoteAddr: "10.0.0.1:4000"}
main.Info.ClientID = "1001"
main.Info.ClientType = "EXE"
rig := &screenRig{
t: t, h: h, main: main,
writes: make(chan []byte, 8),
}
h.SetSender(func(ctx *connection.Context, data []byte) error {
if ctx == main {
select {
case rig.writes <- append([]byte(nil), data...):
default:
}
}
return nil
})
h.Register(&hub.Device{ID: "1001", PeerIP: "10.0.0.1", Capability: capability}, main)
rig.s = New(Config{Token: testToken, Hub: h})
t.Cleanup(rig.s.Close)
return rig
}
type screenCall struct {
res toolResult
err *rpcError
}
func (r *screenRig) call(args string) <-chan screenCall {
ch := make(chan screenCall, 1)
go func() {
res, rerr := r.s.callGetScreenshot(context.Background(), []byte(args))
if rerr != nil {
ch <- screenCall{err: rerr}
return
}
tr, ok := res.(toolResult)
if !ok {
ch <- screenCall{err: errf(CodeInternal, "unexpected result type %T", res)}
return
}
ch <- screenCall{res: tr}
}()
return ch
}
func (r *screenRig) wait(ch <-chan screenCall) screenCall {
r.t.Helper()
select {
case c := <-ch:
return c
case <-time.After(5 * time.Second):
r.t.Fatal("timed out waiting for the tool call")
return screenCall{}
}
}
// nextRequest returns the reqId and maxWidth of the next outbound request.
func (r *screenRig) nextRequest() (reqID, maxWidth uint16) {
r.t.Helper()
select {
case b := <-r.writes:
if len(b) != 8 || b[0] != protocol.CommandScreenPreviewReq {
r.t.Fatalf("unexpected screenshot request wire %v", b)
}
if b[5] != screenPreviewJPEGQuality || b[6] != 0 || b[7] != 0 {
r.t.Fatalf("request tail = %v, want quality %d and zero reserved", b[5:], screenPreviewJPEGQuality)
}
return binary.LittleEndian.Uint16(b[1:3]), binary.LittleEndian.Uint16(b[3:5])
case <-time.After(5 * time.Second):
r.t.Fatal("no screenshot request was sent")
return 0, 0
}
}
func previewPacket(reqID uint16, status, format byte, w, h uint16, payload []byte) []byte {
buf := make([]byte, screenPreviewRspHeaderLen+len(payload))
buf[0] = protocol.TokenScreenPreviewRsp
binary.LittleEndian.PutUint16(buf[screenPreviewOffReqID:], reqID)
buf[screenPreviewOffStatus] = status
buf[screenPreviewOffFormat] = format
binary.LittleEndian.PutUint16(buf[screenPreviewOffWidth:], w)
binary.LittleEndian.PutUint16(buf[screenPreviewOffHeight:], h)
binary.LittleEndian.PutUint32(buf[screenPreviewOffBytes:], uint32(len(payload)))
copy(buf[screenPreviewRspHeaderLen:], payload)
return buf
}
func solidJPEG(t *testing.T, w, h int, c color.RGBA) []byte {
t.Helper()
img := image.NewRGBA(image.Rect(0, 0, w, h))
for i := 0; i < w*h; i++ {
img.Pix[i*4+0] = c.R
img.Pix[i*4+1] = c.G
img.Pix[i*4+2] = c.B
img.Pix[i*4+3] = 0xFF
}
var buf bytes.Buffer
if err := jpeg.Encode(&buf, img, &jpeg.Options{Quality: 90}); err != nil {
t.Fatalf("encode fixture: %v", err)
}
return buf.Bytes()
}
// solidBGRX builds a top-down B,G,R,X frame of one colour.
func solidBGRX(w, h int, b, g, r byte) []byte {
out := make([]byte, w*h*4)
for i := 0; i < w*h; i++ {
out[i*4+0] = b
out[i*4+1] = g
out[i*4+2] = r
out[i*4+3] = 0xFF
}
return out
}
func TestScreenshotReturnsJPEG(t *testing.T) {
rig := newScreenRig(t, "0004")
payload := solidJPEG(t, 4, 4, color.RGBA{255, 0, 0, 255})
ch := rig.call(`{"id":"1001"}`)
reqID, maxWidth := rig.nextRequest()
if maxWidth != screenPreviewDefaultWidth {
t.Fatalf("maxWidth = %d, want %d", maxWidth, screenPreviewDefaultWidth)
}
if !rig.s.OnPacket(rig.main, previewPacket(reqID, screenPreviewStatusOK, screenPreviewFmtJPEG, 4, 4, payload)) {
t.Fatal("OnPacket did not consume the preview response")
}
c := rig.wait(ch)
if c.err != nil {
t.Fatalf("call error: %+v", c.err)
}
if len(c.res.Content) != 1 || c.res.Content[0].Type != "image" {
t.Fatalf("content = %+v, want one image item", c.res.Content)
}
if c.res.Content[0].MimeType != "image/jpeg" {
t.Fatalf("mimeType = %q", c.res.Content[0].MimeType)
}
raw, err := base64.StdEncoding.DecodeString(c.res.Content[0].Data)
if err != nil {
t.Fatalf("base64: %v", err)
}
if !bytes.HasPrefix(raw, []byte{0xFF, 0xD8, 0xFF}) {
t.Fatalf("payload does not start with the JPEG magic: %x", raw[:3])
}
out, ok := c.res.StructuredContent.(screenshotOutput)
if !ok {
t.Fatalf("structured content %T", c.res.StructuredContent)
}
if out.Image.Width != 4 || out.Image.Height != 4 || out.Image.Bytes != len(raw) {
t.Fatalf("image metadata = %+v (raw %d bytes)", out.Image, len(raw))
}
if out.Image.MimeType != "image/jpeg" || out.Capture.Mode != "screen" {
t.Fatalf("structured content = %+v", out)
}
}
func TestScreenshotConvertsBGRX(t *testing.T) {
rig := newScreenRig(t, "0004")
// Pure red in B,G,R,X order.
frame := solidBGRX(8, 8, 0, 0, 255)
ch := rig.call(`{"id":"1001"}`)
reqID, _ := rig.nextRequest()
rig.s.OnPacket(rig.main, previewPacket(reqID, screenPreviewStatusOK, screenPreviewFmtBGRX, 8, 8, frame))
c := rig.wait(ch)
if c.err != nil {
t.Fatalf("call error: %+v", c.err)
}
raw, err := base64.StdEncoding.DecodeString(c.res.Content[0].Data)
if err != nil {
t.Fatalf("base64: %v", err)
}
if !bytes.HasPrefix(raw, []byte{0xFF, 0xD8, 0xFF}) {
t.Fatalf("payload does not start with the JPEG magic: %x", raw[:3])
}
img, err := jpeg.Decode(bytes.NewReader(raw))
if err != nil {
t.Fatalf("decode returned JPEG: %v", err)
}
if b := img.Bounds(); b.Dx() != 8 || b.Dy() != 8 {
t.Fatalf("image is %v, want 8x8", b)
}
r16, g16, b16, _ := img.At(4, 4).RGBA()
// JPEG is lossy; a solid frame should still be clearly red.
if r16>>8 < 200 || g16>>8 > 60 || b16>>8 > 60 {
t.Fatalf("pixel = (%d,%d,%d), want red", r16>>8, g16>>8, b16>>8)
}
}
func TestScreenshotStatusMapping(t *testing.T) {
cases := []struct {
name string
status byte
code int
}{
{"capture failed", screenPreviewStatusCaptureFailed, CodeInternal},
{"encode failed", screenPreviewStatusEncodeFailed, CodeInternal},
{"not supported", screenPreviewStatusNotSupported, CodeUnsupported},
{"bad target", screenPreviewStatusBadTarget, CodeInvalidParams},
{"unknown", 9, CodeInternal},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
rig := newScreenRig(t, "0004")
ch := rig.call(`{"id":"1001"}`)
reqID, _ := rig.nextRequest()
rig.s.OnPacket(rig.main, previewPacket(reqID, tc.status, screenPreviewFmtJPEG, 0, 0, nil))
c := rig.wait(ch)
if c.err == nil || c.err.Code != tc.code {
t.Fatalf("error = %+v, want code %d", c.err, tc.code)
}
})
}
}
func TestScreenshotDropsMismatchedReqID(t *testing.T) {
rig := newScreenRig(t, "0004")
payload := solidJPEG(t, 2, 2, color.RGBA{0, 255, 0, 255})
ch := rig.call(`{"id":"1001"}`)
reqID, _ := rig.nextRequest()
// A response for another request must be dropped, not handed to this one.
rig.s.OnPacket(rig.main, previewPacket(reqID+1, screenPreviewStatusOK, screenPreviewFmtJPEG, 2, 2, payload))
select {
case c := <-ch:
t.Fatalf("call finished on a foreign reqId: %+v", c)
case <-time.After(100 * time.Millisecond):
}
rig.s.OnPacket(rig.main, previewPacket(reqID, screenPreviewStatusOK, screenPreviewFmtJPEG, 2, 2, payload))
if c := rig.wait(ch); c.err != nil {
t.Fatalf("matching response still failed: %+v", c.err)
}
}
func TestScreenshotTimeoutDropsPending(t *testing.T) {
old := screenPreviewTimeout
screenPreviewTimeout = 50 * time.Millisecond
t.Cleanup(func() { screenPreviewTimeout = old })
rig := newScreenRig(t, "0004")
ch := rig.call(`{"id":"1001"}`)
reqID, _ := rig.nextRequest()
c := rig.wait(ch)
if c.err == nil || c.err.Code != CodeTimeout {
t.Fatalf("error = %+v, want -32001", c.err)
}
rig.s.previews.mu.Lock()
pending := len(rig.s.previews.byDevice)
rig.s.previews.mu.Unlock()
if pending != 0 {
t.Fatalf("%d preview entries left after the timeout", pending)
}
// A late reply is consumed and discarded; it must not resurrect the entry.
rig.s.OnPacket(rig.main, previewPacket(reqID, screenPreviewStatusOK, screenPreviewFmtJPEG, 1, 1, []byte{0xFF, 0xD8, 0xFF, 0xD9}))
rig.s.previews.mu.Lock()
pending = len(rig.s.previews.byDevice)
rig.s.previews.mu.Unlock()
if pending != 0 {
t.Fatalf("%d preview entries after a late reply", pending)
}
}
func TestScreenshotRequiresCapability(t *testing.T) {
rig := newScreenRig(t, "")
c := rig.wait(rig.call(`{"id":"1001"}`))
if c.err == nil || c.err.Code != CodeUnsupported {
t.Fatalf("error = %+v, want -32005 for a client without CLIENT_CAP_SCREEN_PREVIEW", c.err)
}
if len(rig.writes) != 0 {
t.Fatal("a request was sent to a host that cannot answer it")
}
}
func TestScreenshotClampsMaxWidth(t *testing.T) {
cases := []struct {
name string
args string
want uint16
}{
{"absent", `{"id":"1001"}`, screenPreviewDefaultWidth},
{"zero", `{"id":"1001","max_width":0}`, screenPreviewDefaultWidth},
{"negative", `{"id":"1001","max_width":-5}`, screenPreviewDefaultWidth},
{"below floor", `{"id":"1001","max_width":10}`, screenPreviewMinWidth},
{"in range", `{"id":"1001","max_width":800}`, 800},
{"above ceiling", `{"id":"1001","max_width":5000}`, screenPreviewMaxWidth},
}
rig := newScreenRig(t, "0004")
payload := solidJPEG(t, 2, 2, color.RGBA{0, 0, 255, 255})
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
ch := rig.call(tc.args)
reqID, got := rig.nextRequest()
if got != tc.want {
t.Fatalf("maxWidth = %d, want %d", got, tc.want)
}
rig.s.OnPacket(rig.main, previewPacket(reqID, screenPreviewStatusOK, screenPreviewFmtJPEG, 2, 2, payload))
if c := rig.wait(ch); c.err != nil {
t.Fatalf("call error: %+v", c.err)
}
})
}
}
func TestScreenshotRejectsRegionParams(t *testing.T) {
cases := []struct {
name string
args string
code int
}{
{"mode region", `{"id":"1001","mode":"region"}`, CodeUnsupported},
{"mode window", `{"id":"1001","mode":"window"}`, CodeUnsupported},
{"mode monitor", `{"id":"1001","mode":"monitor"}`, CodeUnsupported},
{"hwnd", `{"id":"1001","hwnd":123}`, CodeUnsupported},
{"hwnd string", `{"id":"1001","hwnd":"0x1F"}`, CodeUnsupported},
{"x", `{"id":"1001","x":5}`, CodeUnsupported},
{"y", `{"id":"1001","y":5}`, CodeUnsupported},
{"width", `{"id":"1001","width":100}`, CodeUnsupported},
{"height", `{"id":"1001","height":100}`, CodeUnsupported},
{"monitor", `{"id":"1001","monitor":0}`, CodeUnsupported},
{"invalid mode", `{"id":"1001","mode":"bogus"}`, CodeInvalidParams},
}
rig := newScreenRig(t, "0004")
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
c := rig.wait(rig.call(tc.args))
if c.err == nil || c.err.Code != tc.code {
t.Fatalf("error = %+v, want code %d", c.err, tc.code)
}
})
}
if len(rig.writes) != 0 {
t.Fatal("a request was sent for a rejected capture mode")
}
}
func TestScreenshotRejectsBadArgs(t *testing.T) {
rig := newScreenRig(t, "0004")
cases := []struct {
name string
args string
code int
}{
{"missing id", `{}`, CodeInvalidParams},
{"non-decimal id", `{"id":"abc"}`, CodeInvalidParams},
{"max_width type", `{"id":"1001","max_width":"wide"}`, CodeInvalidParams},
{"offline", `{"id":"9999"}`, CodeOffline},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
c := rig.wait(rig.call(tc.args))
if c.err == nil || c.err.Code != tc.code {
t.Fatalf("error = %+v, want code %d", c.err, tc.code)
}
})
}
}
func TestScreenshotWithoutHub(t *testing.T) {
s := New(Config{Token: testToken})
defer s.Close()
res, rerr := s.callGetScreenshot(context.Background(), []byte(`{"id":"1"}`))
if res != nil || rerr == nil || rerr.Code != CodeInternal {
t.Fatalf("res=%v err=%+v, want -32000 without a hub", res, rerr)
}
}
func TestParseScreenPreviewRsp(t *testing.T) {
valid := previewPacket(7, screenPreviewStatusOK, screenPreviewFmtJPEG, 2, 3, []byte{1, 2, 3, 4})
if rsp, err := parseScreenPreviewRsp(valid); err != nil || rsp.reqID != 7 || len(rsp.reply.payload) != 4 {
t.Fatalf("valid packet: rsp=%+v err=%v", rsp, err)
}
// A metadata tail after the declared payload is legal and ignored.
withMeta := append(append([]byte(nil), valid...), make([]byte, 24)...)
rsp, err := parseScreenPreviewRsp(withMeta)
if err != nil || len(rsp.reply.payload) != 4 {
t.Fatalf("packet with meta tail: rsp=%+v err=%v", rsp, err)
}
short := valid[:screenPreviewRspHeaderLen-1]
if _, err := parseScreenPreviewRsp(short); err == nil {
t.Fatal("accepted a packet shorter than the header")
}
wrongToken := append([]byte(nil), valid...)
wrongToken[0] = protocol.TokenNextScreen
if _, err := parseScreenPreviewRsp(wrongToken); err == nil {
t.Fatal("accepted a packet with the wrong token")
}
overrun := append([]byte(nil), valid...)
binary.LittleEndian.PutUint32(overrun[screenPreviewOffBytes:], 99)
if _, err := parseScreenPreviewRsp(overrun); err == nil {
t.Fatal("accepted a packet whose byte count overruns the packet")
}
}
func TestBGRXToJPEGRejectsMalformed(t *testing.T) {
cases := []struct {
name string
src []byte
w, h int
}{
{"zero width", make([]byte, 16), 0, 4},
{"short frame", make([]byte, 15), 2, 2},
{"long frame", make([]byte, 17), 2, 2},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if _, err := bgrxToJPEG(tc.src, tc.w, tc.h); err == nil {
t.Fatal("converted a malformed BGRX frame")
}
})
}
}
func TestOnPacketIgnoresOtherTokens(t *testing.T) {
rig := newScreenRig(t, "0004")
if rig.s.OnPacket(rig.main, nil) {
t.Fatal("consumed an empty packet")
}
if rig.s.OnPacket(rig.main, []byte{protocol.TokenNextScreen, 0}) {
t.Fatal("consumed a screen frame")
}
if !rig.s.OnPacket(rig.main, []byte{protocol.TokenScreenPreviewRsp}) {
t.Fatal("did not consume (and log) a truncated preview response")
}
}
+416
View File
@@ -0,0 +1,416 @@
package mcp
import (
"bytes"
"context"
"crypto/subtle"
"encoding/json"
"errors"
"io"
"net/http"
"runtime/debug"
"strings"
"sync"
"time"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/devicehistory"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/hub"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/logger"
)
const (
// protocolVersion is the MCP revision this endpoint speaks. It matches the
// Win32 server and mcp/tools.json.
protocolVersion = "2025-06-18"
// maxBodyBytes bounds a single JSON-RPC request. tools/call arguments can
// carry a file payload for uploads, so 8 MiB is generous but finite.
maxBodyBytes = 8 << 20
defaultTermIdle = 180 * time.Second
defaultMaxConcurrency = 16
defaultReadMax = 2 << 20
// termSweepInterval is how often the reaper looks for sessions a model
// forgot to close. The sweep itself is cheap: one mutex per session.
termSweepInterval = 30 * time.Second
)
// Config is filled by cmd/main.go from the YAMA_MCP_* environment variables;
// the package itself never reads the environment, so tests are deterministic.
type Config struct {
Token string // static bearer token; empty disables the endpoint
Readonly bool // hide (and refuse) write tools
TermIdle time.Duration // terminal session idle reaping
MaxConcurrency int // global in-flight tools/call cap
ReadMax int64 // read_file whole-file limit
Version string // serverInfo.version
StartedAt time.Time // reported by get_server_status
Log *logger.Logger
// Server-side state the local read tools answer from. A nil Hub means the
// endpoint was built without a device registry: the host tools then fail
// with -32000 instead of reporting an empty (and misleading) list.
Hub *hub.Hub
History *devicehistory.Store // nil: no offline history to merge
AuditPath string // "" = audit file disabled (YAMA_AUDIT_LOG=off)
Port int // web/MCP listening port, for get_server_status
Bind string // listening address, for get_server_status
}
// toolFunc implements one tools/call. It returns either a result value or a
// JSON-RPC error; the caller wraps whichever it gets.
type toolFunc func(ctx context.Context, args json.RawMessage) (any, *rpcError)
// Server is the stateless MCP endpoint. It owns the embedded tool definitions
// and the tool handler table; per-device sessions arrive in later milestones.
type Server struct {
cfg Config
log *logger.Logger
tools *toolSet
handlers map[string]toolFunc
// locks serialises device operations; sem bounds the global in-flight
// tools/call count. Both are non-blocking: contention is -32003, not a
// queue, so a slow call cannot pile up requests behind it (design §9).
locks *deviceLocks
sem chan struct{}
sessions *sessionTable
previews *previewTable // in-flight get_screenshot requests, keyed by device
files *fileTable // in-flight list_files requests, keyed by device
transfers *transferTable // in-flight read_file V2 transfers, keyed by device
// stop ends the idle reaper and reaperDone reports that it returned;
// closeOnce makes Close idempotent (tests call it both explicitly and from
// Cleanup). reaperDone is nil when no reaper was started (hub-less server).
stop chan struct{}
reaperDone chan struct{}
closeOnce sync.Once
}
// New builds the endpoint. Zero-valued knobs fall back to the documented
// defaults so a partially-filled Config from cmd is still safe.
func New(cfg Config) *Server {
if cfg.TermIdle <= 0 {
cfg.TermIdle = defaultTermIdle
}
if cfg.MaxConcurrency <= 0 {
cfg.MaxConcurrency = defaultMaxConcurrency
}
if cfg.ReadMax <= 0 {
cfg.ReadMax = defaultReadMax
}
if cfg.StartedAt.IsZero() {
cfg.StartedAt = time.Now()
}
// Version is left exactly as injected: it may be empty in a build without
// git/ldflags. The initialize response substitutes "dev" for such builds;
// get_server_status reports the empty string rather than inventing a
// version (design §3.2).
if cfg.Log == nil {
cfg.Log = logger.New(logger.Config{Level: logger.LevelError})
}
s := &Server{
cfg: cfg,
log: cfg.Log,
tools: buildToolSet(toolsJSON),
handlers: make(map[string]toolFunc),
locks: newDeviceLocks(),
sem: make(chan struct{}, cfg.MaxConcurrency),
previews: newPreviewTable(),
files: newFileTable(),
transfers: newTransferTable(),
stop: make(chan struct{}),
}
if cfg.Hub != nil {
s.sessions = newSessionTable(cfg.Hub)
} else {
s.sessions = newSessionTable(nil)
}
s.registerLocalTools()
s.registerScreenTools()
s.registerFileTools()
s.registerTerminalTools()
if cfg.Hub != nil {
// No hub means no shell can ever be opened, so there is nothing to
// reap; skipping the goroutine keeps hub-less servers inert.
s.reaperDone = make(chan struct{})
go s.sweepLoop()
}
return s
}
// Enabled reports whether /mcp should be registered. An empty token disables
// the endpoint entirely: the route is not mounted, so it 404s like any other
// unknown path.
func (s *Server) Enabled() bool { return s != nil && s.cfg.Token != "" }
// Close releases resources held by long-lived tool state: the reaper stops and
// every terminal session MCP owns is torn down and the shell told to exit.
func (s *Server) Close() {
s.closeOnce.Do(func() {
close(s.stop)
if s.reaperDone != nil {
<-s.reaperDone
}
s.sessions.closeAll()
})
}
// sweepLoop reclaims terminal sessions nobody closed. The interval shrinks to
// TermIdle when that is shorter, so a test (or a deliberately tiny idle knob)
// sees the sweep fire on schedule instead of up to 30 s late.
func (s *Server) sweepLoop() {
defer close(s.reaperDone)
ticker := time.NewTicker(min(termSweepInterval, s.cfg.TermIdle))
defer ticker.Stop()
for {
select {
case <-s.stop:
return
case now := <-ticker.C:
s.sessions.sweepIdle(now, s.cfg.TermIdle)
}
}
}
// Handle serves POST /mcp. Transport-level failures (405/401/413) are answered
// here; everything after a successfully parsed JSON-RPC request returns HTTP
// 200 and carries the error in the JSON-RPC body.
func (s *Server) Handle(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.Header().Set("Allow", http.MethodPost)
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
if !s.authorized(r) {
// The MCP transport spec expects a transport-level failure here, not a
// JSON-RPC error object, so the client can distinguish "bad credential"
// from "server rejected the call".
w.Header().Set("WWW-Authenticate", `Bearer realm="mcp"`)
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxBodyBytes))
if err != nil {
var tooLarge *http.MaxBytesError
if errors.As(err, &tooLarge) {
http.Error(w, "request body too large", http.StatusRequestEntityTooLarge)
return
}
http.Error(w, "failed to read request body", http.StatusBadRequest)
return
}
s.serveRPC(w, r, body)
}
// serveRPC parses and dispatches one JSON-RPC request, writing the response.
func (s *Server) serveRPC(w http.ResponseWriter, r *http.Request, body []byte) {
body = bytes.TrimSpace(body)
if len(body) == 0 {
writeRPC(w, errorResponse(nil, errf(CodeParseError, "Parse error")))
return
}
// Batch arrays are rejected rather than processed: gating, auditing and
// locking assume one call at a time (design §4.1).
if body[0] == '[' {
writeRPC(w, errorResponse(nil, errf(CodeInvalidRequest, "batch requests are not supported")))
return
}
var req request
if err := json.Unmarshal(body, &req); err != nil {
writeRPC(w, errorResponse(nil, errf(CodeParseError, "Parse error")))
return
}
if req.Method == "" {
writeRPC(w, errorResponse(req.ID, errf(CodeInvalidRequest, "Invalid Request")))
return
}
// Notifications (notifications/initialized, notifications/cancelled, …)
// get no body. The MCP spec allows 202; we use 204 so there is nothing to
// mistake for a result.
if req.isNotification() {
w.WriteHeader(http.StatusNoContent)
return
}
result, rerr := s.dispatch(r.Context(), &req)
if rerr != nil {
writeRPC(w, errorResponse(req.ID, rerr))
return
}
writeRPC(w, resultResponse(req.ID, result))
}
// dispatch routes one method. Unknown methods are -32601; the MCP client is
// expected to treat that as "this server does not support the feature".
func (s *Server) dispatch(ctx context.Context, req *request) (any, *rpcError) {
switch req.Method {
case "initialize":
return s.initializeResult(), nil
case "ping":
return struct{}{}, nil
case "tools/list":
return toolsListResult{Tools: s.tools.visible(s.cfg.Readonly)}, nil
case "tools/call":
return s.callTool(ctx, req.Params)
default:
return nil, errf(CodeMethodNotFound, "Method not found: %s", req.Method)
}
}
type serverInfo struct {
Name string `json:"name"`
Version string `json:"version"`
}
type toolsCapability struct {
ListChanged bool `json:"listChanged"`
}
type serverCapabilities struct {
Tools toolsCapability `json:"tools"`
}
type initializeResult struct {
ProtocolVersion string `json:"protocolVersion"`
Capabilities serverCapabilities `json:"capabilities"`
ServerInfo serverInfo `json:"serverInfo"`
Instructions string `json:"instructions"`
}
// initializeResult mirrors the Win32 server: same protocol version, same
// serverInfo.name ("yama") so clients do not special-case the Go backend.
// Differences are stated in instructions, which models read.
func (s *Server) initializeResult() initializeResult {
// "dev" is a serverInfo-only marker for an unversioned build; the status
// tool keeps the raw (empty) value.
version := s.cfg.Version
if version == "" {
version = "dev"
}
return initializeResult{
ProtocolVersion: protocolVersion,
Capabilities: serverCapabilities{Tools: toolsCapability{ListChanged: false}},
ServerInfo: serverInfo{Name: "yama", Version: version},
Instructions: serverInstructions,
}
}
// callTool parses tools/call, enforces visibility, takes the concurrency and
// device gates, then hands the raw arguments to the handler. Readonly mode
// refuses hidden write tools with -32006 rather than pretending they do not
// exist. Every call that names a tool is audited, including rejected ones.
func (s *Server) callTool(ctx context.Context, raw json.RawMessage) (result any, rerr *rpcError) {
if len(raw) == 0 || string(raw) == "null" {
return nil, errf(CodeInvalidParams, "tools/call requires params")
}
var params toolCallParams
if err := json.Unmarshal(raw, &params); err != nil {
return nil, errf(CodeInvalidParams, "invalid params: %v", err)
}
if params.Name == "" {
return nil, errf(CodeInvalidParams, "tool name is required")
}
start := time.Now()
deviceID := ""
if !localReadTools[params.Name] {
deviceID = deviceIDFromArgs(params.Arguments)
}
defer func() {
// Convert a handler panic into -32000 instead of letting net/http drop
// the connection, and make sure the audit record says the call failed:
// without this the zero-valued rerr would be logged as success.
if p := recover(); p != nil {
s.log.Error("panic in MCP tool %s: %v\n%s", params.Name, p, debug.Stack())
result = nil
rerr = errf(CodeInternal, "internal error in tool %s", params.Name)
}
s.auditCall(params.Name, deviceID, params.Arguments, result, rerr, time.Since(start))
}()
if !s.tools.known(params.Name) {
return nil, errf(CodeMethodNotFound, "unknown tool: %s", params.Name)
}
if s.cfg.Readonly && writeTools[params.Name] {
return nil, errf(CodeDenied, "tool %s is disabled in readonly mode", params.Name)
}
handler, ok := s.handlers[params.Name]
if !ok {
// The tool is listed but this build does not implement it yet. This is
// a temporary state between milestones, not a client mistake.
return nil, errf(CodeInternal, "tool %s is not implemented by this server build", params.Name)
}
// Global slot first: a call that would be rejected for concurrency must
// not squat on a device lock while it fails.
select {
case s.sem <- struct{}{}:
defer func() { <-s.sem }()
default:
return nil, errf(CodeBusy, "Server busy: too many concurrent MCP calls (limit %d)",
s.cfg.MaxConcurrency)
}
if deviceID != "" && !unlockedTools[params.Name] {
held, acquired := s.locks.tryAcquire(deviceID, params.Name)
if !acquired {
return nil, errf(CodeBusy, "%s", busyMessage(held))
}
defer s.locks.release(deviceID)
}
return handler(ctx, params.Arguments)
}
// authorized compares the bearer token without leaking its length or content
// through timing. A missing or different-length header fails immediately, but
// no branch reveals how much of the token matched.
func (s *Server) authorized(r *http.Request) bool {
const prefix = "Bearer "
// An empty configured token would otherwise match an empty credential;
// the route is not mounted in that case, but keep the check safe anyway.
if s.cfg.Token == "" {
return false
}
header := r.Header.Get("Authorization")
if !strings.HasPrefix(header, prefix) {
return false
}
got := header[len(prefix):]
if len(got) != len(s.cfg.Token) {
return false
}
return subtle.ConstantTimeCompare([]byte(got), []byte(s.cfg.Token)) == 1
}
// writeRPC writes a single JSON-RPC response. Marshal failures are impossible
// for the value types used here, but are reported rather than dropping the
// connection silently.
func writeRPC(w http.ResponseWriter, resp *response) {
body, err := json.Marshal(resp)
if err != nil {
http.Error(w, "failed to encode response", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, _ = w.Write(body)
}
// serverInstructions is the Go backend's initialization guide. The Win32 MCP
// server ships a much larger text covering its 54 tools; this one describes
// only what the minimal Go server exposes and where it behaves differently.
const serverInstructions = `这是 YAMA 服务端的 MCP 端点(Go 实现)。工具集比 Windows 主控端小,以下规则优先于各工具的描述。
1) 主机 id 是 64 位无符号十进制字符串,由服务端分配,无法从 IP 或计算机名推算。需要 id 时先用 list_hosts 取得,拿不到就向用户确认,不要猜。
2) tools/list 只返回当前模式允许的工具;只读模式隐藏 terminal_exec / terminal_close,直接调用被隐藏的工具返回 -32006。
3) 错误码与动作:-32002 主机离线或不存在(先刷新列表);-32003 主机忙(同一台主机同一时刻只允许一个操作,重试无效,等前一个结束);-32004 命令未送达(多为链路瞬断,可重试一次);-32005 主机不支持该能力(换主机或换工具,改参数无用;老客户端不声明 CLIENT_CAP_V2 时 read_file 也返回 -32005,需升级客户端);-32006 只读模式拒绝(terminal_exec / terminal_close;重试无效,需管理员关掉只读);-32001 多为超时,也可能是工具自身失败或已被取消:工具支持 timeout_ms 时先加大重试一次;子连接/会话没建立或同一主机反复超时通常重试无效(主机卡住、链路断或老客户端不认命令);message 写 Request cancelled 的表示客户端已中止,可直接重试;-32602 参数错误(按 message 修正)。
4) get_screenshot 只支持 mode=screen(按链路状况自适应缩放,max_width 省略时最大 1024);本实现没有 CLIENT_CAP_SCREEN_REGION 扩展,mode=region/window/monitor 与区域类参数一律返回 -32005。
5) list_files / read_file 走文件传输通道;list_files 支持 ids 批量(最多 50 台、整批 50 秒)。read_file 只接受单个普通文件且整文件不超过 2 MiB,目录用 list_files;本实现没有 download_file / search_file,超限文件只能改用 terminal_exec 分段查看,或连 Windows 主控端的完整服务端。
6) terminal_exec 需要客户端支持终端(CLIENT_CAP_TERMINAL),会在目标主机上创建持久会话;用完调用 terminal_close 释放,闲置会话由服务端回收。调用被取消时返回的 message 里带 session_id,可用它轮询或关闭。
7) 本实现不维护备注与授权状态:list_hosts / get_host_detail 不返回 remark/authStatus/tls;get_server_status 只报版本、在线台数与监听地址,没有 switches/sessions。
8) 列表与详情都是调用时刻的快照,主机可能在操作期间掉线;写操作前先读一次现状,动作后再复核。`
+395
View File
@@ -0,0 +1,395 @@
package mcp
import (
"encoding/json"
"net/http"
"net/http/httptest"
"path/filepath"
"reflect"
"strings"
"testing"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/logger"
)
const testToken = "0123456789abcdef0123456789abcdef"
func testServer(t *testing.T, readonly bool) *Server {
t.Helper()
log := logger.New(logger.Config{
Level: logger.LevelError,
File: filepath.Join(t.TempDir(), "mcp-test.log"),
})
return New(Config{
Token: testToken,
Readonly: readonly,
Version: "test-1.0",
Log: log,
})
}
// rpcEnvelope decodes a JSON-RPC response without committing to a result type.
type rpcEnvelope struct {
JSONRPC string `json:"jsonrpc"`
ID json.RawMessage `json:"id"`
Result json.RawMessage `json:"result"`
Error *rpcError `json:"error"`
}
func call(t *testing.T, s *Server, body string) *httptest.ResponseRecorder {
t.Helper()
req := httptest.NewRequest(http.MethodPost, "/mcp", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
s.Handle(rec, req)
return rec
}
func authedCall(t *testing.T, s *Server, body string) *httptest.ResponseRecorder {
t.Helper()
req := httptest.NewRequest(http.MethodPost, "/mcp", strings.NewReader(body))
req.Header.Set("Authorization", "Bearer "+testToken)
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
s.Handle(rec, req)
return rec
}
func decodeEnvelope(t *testing.T, rec *httptest.ResponseRecorder) rpcEnvelope {
t.Helper()
var env rpcEnvelope
if err := json.Unmarshal(rec.Body.Bytes(), &env); err != nil {
t.Fatalf("response is not JSON: %v\nbody: %s", err, rec.Body.String())
}
return env
}
func TestEnabledRequiresToken(t *testing.T) {
if New(Config{}).Enabled() {
t.Fatal("endpoint without a token must report disabled")
}
if !testServer(t, false).Enabled() {
t.Fatal("endpoint with a token must report enabled")
}
}
func TestAuth(t *testing.T) {
s := testServer(t, false)
body := `{"jsonrpc":"2.0","id":1,"method":"ping"}`
t.Run("missing", func(t *testing.T) {
rec := call(t, s, body)
if rec.Code != http.StatusUnauthorized {
t.Fatalf("status = %d, want 401", rec.Code)
}
if got := rec.Header().Get("WWW-Authenticate"); !strings.Contains(got, "Bearer") {
t.Fatalf("WWW-Authenticate = %q, want a Bearer challenge", got)
}
if strings.Contains(rec.Body.String(), "jsonrpc") {
t.Fatalf("401 must not carry a JSON-RPC body: %s", rec.Body.String())
}
})
t.Run("wrong same length", func(t *testing.T) {
req := httptest.NewRequest(http.MethodPost, "/mcp", strings.NewReader(body))
req.Header.Set("Authorization", "Bearer "+strings.Repeat("f", len(testToken)))
rec := httptest.NewRecorder()
s.Handle(rec, req)
if rec.Code != http.StatusUnauthorized {
t.Fatalf("status = %d, want 401", rec.Code)
}
})
t.Run("wrong different length", func(t *testing.T) {
req := httptest.NewRequest(http.MethodPost, "/mcp", strings.NewReader(body))
req.Header.Set("Authorization", "Bearer "+testToken+"x")
rec := httptest.NewRecorder()
s.Handle(rec, req)
if rec.Code != http.StatusUnauthorized {
t.Fatalf("status = %d, want 401", rec.Code)
}
})
t.Run("missing scheme", func(t *testing.T) {
req := httptest.NewRequest(http.MethodPost, "/mcp", strings.NewReader(body))
req.Header.Set("Authorization", testToken)
rec := httptest.NewRecorder()
s.Handle(rec, req)
if rec.Code != http.StatusUnauthorized {
t.Fatalf("status = %d, want 401", rec.Code)
}
})
t.Run("correct", func(t *testing.T) {
rec := authedCall(t, s, body)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200 (body: %s)", rec.Code, rec.Body.String())
}
if ct := rec.Header().Get("Content-Type"); !strings.HasPrefix(ct, "application/json") {
t.Fatalf("Content-Type = %q, want application/json", ct)
}
})
}
func TestInitialize(t *testing.T) {
s := testServer(t, false)
rec := authedCall(t, s, `{"jsonrpc":"2.0","id":7,"method":"initialize"}`)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200", rec.Code)
}
env := decodeEnvelope(t, rec)
if env.Error != nil {
t.Fatalf("unexpected error: %+v", env.Error)
}
if string(env.ID) != "7" {
t.Fatalf("id = %s, want 7", env.ID)
}
var result struct {
ProtocolVersion string `json:"protocolVersion"`
Capabilities struct {
Tools struct {
ListChanged bool `json:"listChanged"`
} `json:"tools"`
} `json:"capabilities"`
ServerInfo struct {
Name string `json:"name"`
Version string `json:"version"`
} `json:"serverInfo"`
Instructions string `json:"instructions"`
}
if err := json.Unmarshal(env.Result, &result); err != nil {
t.Fatalf("decode result: %v", err)
}
if result.ProtocolVersion != protocolVersion {
t.Fatalf("protocolVersion = %q, want %q", result.ProtocolVersion, protocolVersion)
}
if result.Capabilities.Tools.ListChanged {
t.Fatal("tools.listChanged must be false: the list is static")
}
if result.ServerInfo.Name != "yama" {
t.Fatalf("serverInfo.name = %q, want yama", result.ServerInfo.Name)
}
if result.ServerInfo.Version != "test-1.0" {
t.Fatalf("serverInfo.version = %q, want test-1.0", result.ServerInfo.Version)
}
if strings.TrimSpace(result.Instructions) == "" {
t.Fatal("instructions must not be empty")
}
}
func TestPing(t *testing.T) {
s := testServer(t, false)
env := decodeEnvelope(t, authedCall(t, s, `{"jsonrpc":"2.0","id":"abc","method":"ping"}`))
if env.Error != nil {
t.Fatalf("unexpected error: %+v", env.Error)
}
if string(env.ID) != `"abc"` {
t.Fatalf("id = %s, want \"abc\" (string ids echo unchanged)", env.ID)
}
var result map[string]any
if err := json.Unmarshal(env.Result, &result); err != nil {
t.Fatalf("decode result: %v", err)
}
if len(result) != 0 {
t.Fatalf("ping result = %v, want empty object", result)
}
}
func listTools(t *testing.T, s *Server) []json.RawMessage {
t.Helper()
env := decodeEnvelope(t, authedCall(t, s, `{"jsonrpc":"2.0","id":1,"method":"tools/list"}`))
if env.Error != nil {
t.Fatalf("tools/list error: %+v", env.Error)
}
var result struct {
Tools []json.RawMessage `json:"tools"`
}
if err := json.Unmarshal(env.Result, &result); err != nil {
t.Fatalf("decode result: %v", err)
}
return result.Tools
}
// TestToolsListMatchesEmbedded pins the published definitions to the embedded
// file: same order, same content, no annotations. tools_minimal.json in turn is
// checked against mcp/tools.json by gen_go_tools.py --check.
func TestToolsListMatchesEmbedded(t *testing.T) {
var want []any
if err := json.Unmarshal(toolsJSON, &want); err != nil {
t.Fatalf("embedded tools: %v", err)
}
for _, readonly := range []bool{false, true} {
got := listTools(t, testServer(t, readonly))
if readonly {
if len(got) != 7 {
t.Fatalf("readonly tools = %d, want 7", len(got))
}
} else if len(got) != len(want) {
t.Fatalf("tools = %d, want %d", len(got), len(want))
}
wantIdx := 0
for _, raw := range got {
var tool map[string]any
if err := json.Unmarshal(raw, &tool); err != nil {
t.Fatalf("tool is not an object: %v", err)
}
name, _ := tool["name"].(string)
if _, ok := tool["annotations"]; ok {
t.Fatalf("tool %s must not carry annotations (MFC compatibility)", name)
}
if readonly && (name == "terminal_exec" || name == "terminal_close") {
t.Fatalf("readonly mode must hide %s", name)
}
// Skip over tools the filter removed, keeping the order check.
for wantIdx < len(want) && want[wantIdx].(map[string]any)["name"] != name {
wantIdx++
}
if wantIdx == len(want) {
t.Fatalf("tool %s is not in tools_minimal.json in this order", name)
}
if !reflect.DeepEqual(tool, want[wantIdx]) {
t.Fatalf("tool %s differs from tools_minimal.json", name)
}
wantIdx++
}
if wantIdx != len(want) {
t.Fatalf("filtered list stopped at %d of %d embedded tools", wantIdx, len(want))
}
}
}
func TestNotification(t *testing.T) {
s := testServer(t, false)
rec := authedCall(t, s, `{"jsonrpc":"2.0","method":"notifications/initialized"}`)
if rec.Code != http.StatusNoContent {
t.Fatalf("status = %d, want 204", rec.Code)
}
if rec.Body.Len() != 0 {
t.Fatalf("notification response body = %q, want empty", rec.Body.String())
}
}
func TestUnknownMethod(t *testing.T) {
env := decodeEnvelope(t, authedCall(t, testServer(t, false),
`{"jsonrpc":"2.0","id":1,"method":"does/not/exist"}`))
if env.Error == nil || env.Error.Code != CodeMethodNotFound {
t.Fatalf("error = %+v, want code %d", env.Error, CodeMethodNotFound)
}
}
func TestTransportErrors(t *testing.T) {
s := testServer(t, false)
t.Run("get", func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/mcp", nil)
req.Header.Set("Authorization", "Bearer "+testToken)
rec := httptest.NewRecorder()
s.Handle(rec, req)
if rec.Code != http.StatusMethodNotAllowed {
t.Fatalf("status = %d, want 405", rec.Code)
}
if got := rec.Header().Get("Allow"); got != http.MethodPost {
t.Fatalf("Allow = %q, want POST", got)
}
})
t.Run("delete", func(t *testing.T) {
req := httptest.NewRequest(http.MethodDelete, "/mcp", nil)
req.Header.Set("Authorization", "Bearer "+testToken)
rec := httptest.NewRecorder()
s.Handle(rec, req)
if rec.Code != http.StatusMethodNotAllowed {
t.Fatalf("status = %d, want 405", rec.Code)
}
})
t.Run("batch", func(t *testing.T) {
env := decodeEnvelope(t, authedCall(t, s,
`[{"jsonrpc":"2.0","id":1,"method":"ping"},{"jsonrpc":"2.0","id":2,"method":"ping"}]`))
if env.Error == nil || env.Error.Code != CodeInvalidRequest {
t.Fatalf("error = %+v, want code %d", env.Error, CodeInvalidRequest)
}
if string(env.ID) != "null" {
t.Fatalf("id = %s, want null", env.ID)
}
})
t.Run("oversize", func(t *testing.T) {
body := `{"jsonrpc":"2.0","id":1,"method":"ping","params":"` +
strings.Repeat("x", maxBodyBytes) + `"}`
rec := authedCall(t, s, body)
if rec.Code != http.StatusRequestEntityTooLarge {
t.Fatalf("status = %d, want 413", rec.Code)
}
})
t.Run("parse error", func(t *testing.T) {
env := decodeEnvelope(t, authedCall(t, s, `{"jsonrpc":`))
if env.Error == nil || env.Error.Code != CodeParseError {
t.Fatalf("error = %+v, want code %d", env.Error, CodeParseError)
}
})
t.Run("missing method", func(t *testing.T) {
env := decodeEnvelope(t, authedCall(t, s, `{"jsonrpc":"2.0","id":1}`))
if env.Error == nil || env.Error.Code != CodeInvalidRequest {
t.Fatalf("error = %+v, want code %d", env.Error, CodeInvalidRequest)
}
})
}
func TestToolsCallGates(t *testing.T) {
s := testServer(t, false)
readonly := testServer(t, true)
cases := []struct {
name string
srv *Server
body string
code int
}{
{
name: "unknown tool",
srv: s,
body: `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"nope"}}`,
code: CodeMethodNotFound,
},
{
name: "missing name",
srv: s,
body: `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{}}`,
code: CodeInvalidParams,
},
{
name: "missing params",
srv: s,
body: `{"jsonrpc":"2.0","id":1,"method":"tools/call"}`,
code: CodeInvalidParams,
},
{
// testServer has no hub: the handler exists (M2) and must fail
// loudly rather than report an empty device list.
name: "local tool without device registry",
srv: s,
body: `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"list_hosts"}}`,
code: CodeInternal,
},
{
name: "readonly refuses write tool",
srv: readonly,
body: `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"terminal_exec"}}`,
code: CodeDenied,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
env := decodeEnvelope(t, authedCall(t, tc.srv, tc.body))
if env.Error == nil || env.Error.Code != tc.code {
t.Fatalf("error = %+v, want code %d", env.Error, tc.code)
}
})
}
}
+374
View File
@@ -0,0 +1,374 @@
package mcp
import (
"bytes"
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"sync"
"sync/atomic"
"time"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/hub"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/protocol"
)
// errNoDeviceHub means the endpoint was built without a device registry, so
// no shell can be opened. Mirrors the local tools' nil-Hub behaviour (-32000).
var errNoDeviceHub = errors.New("no device hub configured")
// terminalHub is the slice of *hub.Hub the session table needs. An interface
// keeps the table testable and documents that MCP never touches a terminal
// sub-connection directly — it goes through the hub's single-viewer lease.
type terminalHub interface {
OpenTerminalSessionLease(deviceID string) (uint64, error)
CloseTerminalSessionLease(deviceID string, lease uint64) bool
HasTerminalSession(deviceID string) bool
SendToTerminal(deviceID string, data []byte) error
}
// sessionTable owns the MCP-created terminal sessions, keyed by device. A
// session is created before hub.OpenTerminalSession so OnTerminalReady (which
// can fire on another goroutine as soon as the client answers) always finds
// the object; a failed open rolls the entry back.
type sessionTable struct {
hub terminalHub
mu sync.Mutex
byDevice map[string]*termSession
}
func newSessionTable(h terminalHub) *sessionTable {
return &sessionTable{hub: h, byDevice: make(map[string]*termSession)}
}
func (t *sessionTable) get(deviceID string) *termSession {
t.mu.Lock()
defer t.mu.Unlock()
return t.byDevice[deviceID]
}
// errSessionClosed means the session disappeared while its open was in
// flight (shutdown or an explicit close raced it).
var errSessionClosed = errors.New("terminal session closed during open")
// open claims a shell for the device. ErrTerminalBusy comes back when a web
// console (or another MCP call) already holds it; the hub enforces the
// single-viewer lease, so v1 never pre-empts a human.
func (t *sessionTable) open(deviceID string) (*termSession, error) {
if t.hub == nil {
return nil, errNoDeviceHub
}
t.mu.Lock()
if _, ok := t.byDevice[deviceID]; ok {
t.mu.Unlock()
return nil, hub.ErrTerminalBusy
}
sess := newTermSession(deviceID)
// Until the hub call returns, any OnTerminalClosed for this device belongs
// to the viewer that just released the lease, not to this session.
sess.opening = true
t.byDevice[deviceID] = sess
t.mu.Unlock()
lease, err := t.hub.OpenTerminalSessionLease(deviceID)
if err != nil {
t.mu.Lock()
delete(t.byDevice, deviceID)
t.mu.Unlock()
sess.mu.Lock()
sess.opening = false
sess.closed = true
sess.closeReason = "open failed"
sess.cond.Broadcast()
sess.mu.Unlock()
return nil, err
}
sess.mu.Lock()
sess.opening = false
sess.lease = lease
sess.mu.Unlock()
// An explicit close (or shutdown) may have removed the entry while the hub
// call was in flight. The hub lease is ours by now, so release it instead
// of returning a session nobody can reach.
t.mu.Lock()
cur, ok := t.byDevice[deviceID]
t.mu.Unlock()
if !ok || cur != sess {
t.hub.CloseTerminalSessionLease(deviceID, lease)
return nil, errSessionClosed
}
return sess, nil
}
// ready records that the shell sub-conn is bound. Called from the hub's TCP
// read loop, so it must stay short (a mutex and a broadcast).
func (t *sessionTable) ready(deviceID string, isPTY bool) {
sess := t.get(deviceID)
if sess == nil {
return
}
sess.mu.Lock()
sess.isPTY = isPTY
sess.ready = true
sess.lastUsed = time.Now()
sess.cond.Broadcast()
sess.mu.Unlock()
}
// closed runs when the shell ends for any reason — device-side exit, sub-conn
// drop, or an explicit teardown. Waiters wake up and deliver whatever output
// is already buffered.
//
// A session with a command still in flight stays in the table even after the
// shell is gone: the bytes it produced but nobody has polled yet must remain
// reachable (MFC's closed branch keeps it for the same reason). The entry is
// dropped by forget once the tail is delivered, or by the M4c idle reaper if
// the model never comes back.
func (t *sessionTable) closed(deviceID, reason string) {
// A web console's teardown can race a fresh open: by the time this event is
// delivered, the hub lease may already belong to a new MCP session. The hub
// is the authority on whether a session still exists; if it does, the event
// described the previous viewer and must not touch ours.
if t.hub != nil && t.hub.HasTerminalSession(deviceID) {
return
}
t.mu.Lock()
defer t.mu.Unlock()
sess, ok := t.byDevice[deviceID]
if !ok {
return
}
sess.mu.Lock()
defer sess.mu.Unlock()
if sess.opening {
// Our own hub call has not returned yet, so any close for this device
// still refers to whoever held the lease before us.
return
}
if !sess.hasUndrainedLocked() {
delete(t.byDevice, deviceID)
}
sess.closed = true
sess.closeReason = reason
sess.cond.Broadcast()
}
// hasUndrainedLocked reports whether the in-flight command still has output the
// client has not received. An ended shell delivers everything up to total, so a
// running command's undelivered bytes all count.
func (s *termSession) hasUndrainedLocked() bool {
p := s.pending
if p == nil {
return false
}
end := s.total
if p.done {
end = min(p.outputEnd, s.total)
}
return s.delivered < end
}
// forget removes a session whose shell is already gone. It must not call the
// hub: the device may have reconnected and a new viewer may hold a fresh shell
// by now.
func (t *sessionTable) forget(deviceID string, want *termSession) {
t.mu.Lock()
if t.byDevice[deviceID] == want {
delete(t.byDevice, deviceID)
}
t.mu.Unlock()
}
// closeSession tears down the MCP-owned session for deviceID, if any. It is
// idempotent: a call for a device MCP does not own returns false and leaves
// the web console's session alone.
func (t *sessionTable) closeSession(deviceID string) bool {
return t.closeSessionIf(deviceID, nil)
}
// closeSessionIf closes the device's session only if the table still holds
// exactly want. The identity check matters for sweepIdle: between its scan
// and the close, the stale session can be replaced by a fresh one.
func (t *sessionTable) closeSessionIf(deviceID string, want *termSession) bool {
return t.closeIf(deviceID, want, func(*termSession) string { return "closed" })
}
// closeIf closes a session if decide says so. decide runs with both locks held
// (table then session), so it must read only session fields and lock nothing:
// the staleness reaper uses it to re-check under the same lock that deletes,
// closing the scan-then-close window where a poll could refresh the session.
// A returned "" cancels the close and nothing is touched.
func (t *sessionTable) closeIf(deviceID string, want *termSession, decide func(*termSession) string) bool {
t.mu.Lock()
sess, ok := t.byDevice[deviceID]
if !ok || (want != nil && sess != want) {
t.mu.Unlock()
return false
}
sess.mu.Lock()
reason := decide(sess)
if reason == "" {
sess.mu.Unlock()
t.mu.Unlock()
return false
}
delete(t.byDevice, deviceID)
wasClosed := sess.closed
lease := sess.lease
sess.closed = true
sess.closeReason = reason
sess.cond.Broadcast()
sess.mu.Unlock()
t.mu.Unlock()
// A session that was already closed lost its hub lease when the close event
// arrived; the hub may since have handed a fresh shell to another viewer (a
// reconnected device). Only an explicit close of a live session may touch
// it, and even then only the lease MCP itself opened (the generation check
// in the hub), never whatever lease the device holds now.
if t.hub != nil && !wasClosed && lease != 0 {
t.hub.CloseTerminalSessionLease(deviceID, lease)
}
return true
}
// termBusyMax bounds how long one command may hold a session with nobody
// polling it. Without it a hung command — or a model that never comes back —
// would lock the device's single terminal slot forever. MFC reclaims at the
// same one-hour limit (McpServer.cpp:4674).
const termBusyMax = time.Hour
// sweepIdle closes sessions whose last use is older than idle, plus live
// commands that outlived termBusyMax. Intended for the periodic reaper: a
// model that forgets terminal_close must not lock a human out of the device's
// shell.
//
// A session with a live command (pending, not done) is skipped no matter how
// quiet it is: a sleep or a slow download still owns the lease and must not be
// reaped just because it printed nothing for a while. A session whose shell is
// already gone is reaped on idle alone — its only remaining value is the
// undelivered tail, and a model that never polls it must not pin the slot.
// A session that never became ready is left alone: its open is still waiting
// on a caller, which releases it (with a lease-checked close) on its own.
func (t *sessionTable) sweepIdle(now time.Time, idle time.Duration) int {
type entry struct {
id string
sess *termSession
}
var candidates []entry
t.mu.Lock()
for id, sess := range t.byDevice {
candidates = append(candidates, entry{id, sess})
}
t.mu.Unlock()
n := 0
for _, e := range candidates {
if t.closeIf(e.id, e.sess, func(s *termSession) string {
return s.reclaimReasonLocked(now, idle)
}) {
n++
}
}
return n
}
// reclaimReasonLocked returns why the session should be dropped, or "" to keep
// it. Callers hold s.mu.
func (s *termSession) reclaimReasonLocked(now time.Time, idle time.Duration) string {
inactive := func() string {
return fmt.Sprintf(
"Terminal session was reclaimed after %s of inactivity; call terminal_exec again to open a new one", idle)
}
if !s.ready {
// Still waiting for the shell to bind; a caller holds this session and
// releases it when its own wait ends. Reaping here would kill a live
// open (and, if the lease changed hands meanwhile, someone else's).
return ""
}
if s.closed {
if now.Sub(s.lastUsed) >= idle {
return inactive()
}
return ""
}
if p := s.pending; p != nil && !p.done {
if now.Sub(p.busySince) >= termBusyMax {
return fmt.Sprintf(
"Terminal session was reclaimed after the command ran longer than %s; call terminal_exec again to open a new one", termBusyMax)
}
return ""
}
if now.Sub(s.lastUsed) >= idle {
return inactive()
}
return ""
}
// closeAll drops every session; used at shutdown. The hub teardown is still
// best-effort because the TCP servers may already be stopping.
func (t *sessionTable) closeAll() {
t.mu.Lock()
ids := make([]string, 0, len(t.byDevice))
for id := range t.byDevice {
ids = append(ids, id)
}
t.mu.Unlock()
for _, id := range ids {
t.closeSession(id)
}
}
// sessionIDFallback numbers ids when crypto/rand is unavailable. It is only a
// last resort: ids are opaque to clients, and uniqueness matters, not secrecy.
var sessionIDFallback atomic.Uint32
func newSessionID() string {
var b [3]byte
if _, err := rand.Read(b[:]); err == nil {
return "s-" + hex.EncodeToString(b[:])
}
return fmt.Sprintf("s-%06x", sessionIDFallback.Add(1)&0xffffff)
}
// Server implements hub.EventHandler so the endpoint can observe shell
// traffic. Only the terminal events do work; the screen and lifecycle events
// are ignored (the web console owns those views).
var _ hub.EventHandler = (*Server)(nil)
func (s *Server) OnDeviceOnline(hub.DeviceInfo) {}
func (s *Server) OnDeviceOffline(string) {}
func (s *Server) OnDeviceUpdate(string, int, string) {}
func (s *Server) OnScreenFrame(string, []byte, bool) {}
func (s *Server) OnResolutionChange(string, int, int) {}
func (s *Server) OnCursorChange(string, byte, int, int) {}
func (s *Server) OnClipboardText(string, string) {}
func (s *Server) OnTerminalReady(deviceID string, isPTY bool) { s.sessions.ready(deviceID, isPTY) }
func (s *Server) OnTerminalClosed(deviceID, reason string) { s.sessions.closed(deviceID, reason) }
// OnTerminalData runs on the device's TCP read loop. It must never block:
// look up the session, strip the browser demux prefix, append to the ring,
// check the in-flight sentinel and wake any waiter. Sessions MCP did not
// create (the web console's) are dropped at the map lookup with no work.
func (s *Server) OnTerminalData(deviceID string, packet []byte) {
sess := s.sessions.get(deviceID)
if sess == nil {
return
}
if len(packet) >= len(protocol.TerminalBinaryMagic) &&
bytes.Equal(packet[:len(protocol.TerminalBinaryMagic)], protocol.TerminalBinaryMagic[:]) {
packet = packet[len(protocol.TerminalBinaryMagic):]
}
sess.mu.Lock()
if sess.closed {
sess.mu.Unlock()
return
}
sess.appendLocked(packet)
sess.scanPendingLocked()
sess.cond.Broadcast()
sess.mu.Unlock()
}
+545
View File
@@ -0,0 +1,545 @@
package mcp
import (
"bytes"
"errors"
"strings"
"testing"
"time"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/connection"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/hub"
)
// terminalTestServer builds a server backed by a real hub with one online
// device (1001) whose shell commands are accepted by a no-op sender.
func terminalTestServer(t *testing.T) (*Server, *hub.Hub) {
t.Helper()
h := hub.New()
h.SetSender(func(*connection.Context, []byte) error { return nil })
h.Register(&hub.Device{ID: "1001", PeerIP: "10.0.0.1"},
&connection.Context{RemoteAddr: "10.0.0.1:54321"})
s := New(Config{Token: testToken, Hub: h})
t.Cleanup(s.Close)
return s, h
}
// termPacket wraps shell output the way cmd/main.go publishes it.
func termPacket(s string) []byte {
p := make([]byte, 4+len(s))
copy(p, "TRM1")
copy(p[4:], s)
return p
}
func TestTermRingTrimsOldest(t *testing.T) {
sess := newTermSession("1001")
payload := make([]byte, 1<<20)
for i := range payload {
payload[i] = byte(i*7 + 1)
}
sess.mu.Lock()
sess.appendLocked(payload)
data, next, lost := sess.readLocked(0, 1<<20)
size, total, dropped := sess.size, sess.total, sess.droppedBytes
sess.mu.Unlock()
if size != termRingCap {
t.Fatalf("retained = %d, want cap %d", size, termRingCap)
}
if total != 1<<20 {
t.Fatalf("total = %d, want %d", total, 1<<20)
}
if dropped != uint64((1<<20)-termRingCap) {
t.Fatalf("dropped = %d, want %d", dropped, (1<<20)-termRingCap)
}
if !lost {
t.Fatal("reading from 0 after overflow should report lost data")
}
if len(data) != termRingCap || next != 1<<20 {
t.Fatalf("read len/next = %d/%d, want %d/%d", len(data), next, termRingCap, 1<<20)
}
if want := payload[(1<<20)-termRingCap:]; !bytes.Equal(data, want) {
t.Fatal("retained data is not the newest window of the stream")
}
}
func TestTermRingWraps(t *testing.T) {
sess := newTermSession("1001")
var want []byte
for i := range 10 {
chunk := bytes.Repeat([]byte{byte('a' + i)}, 40<<10)
want = append(want, chunk...)
sess.mu.Lock()
sess.appendLocked(chunk)
sess.mu.Unlock()
}
sess.mu.Lock()
base, total := sess.baseLocked(), sess.total
data, next, lost := sess.readLocked(0, termRingCap)
tail, _, _ := sess.readLocked(total-100, 100)
sess.mu.Unlock()
if !lost {
t.Fatal("reading from 0 after wraparound should report lost data")
}
if base != uint64(len(want)-termRingCap) {
t.Fatalf("base = %d, want %d", base, len(want)-termRingCap)
}
if next != total {
t.Fatalf("next = %d, want total %d", next, total)
}
if wantWin := want[len(want)-termRingCap:]; !bytes.Equal(data, wantWin) {
t.Fatal("wrapped ring does not return the newest window in order")
}
if wantTail := want[len(want)-100:]; !bytes.Equal(tail, wantTail) {
t.Fatal("tail read is not the newest bytes")
}
}
func TestScanSentinel(t *testing.T) {
const sentinel = "__MCP_DONE_abc123__"
cases := []struct {
name string
in string
code int
ok bool
}{
{"plain", "x\r\n" + sentinel + "0\r\n", 0, true},
{"nonzero", sentinel + "42", 42, true},
{"negative", sentinel + "-1073741510", -1073741510, true},
{"echo then real", sentinel + "%errorlevel%\r\n" + sentinel + "1\r\n", 1, true},
{"posix echo then real", sentinel + "$?\n" + sentinel + "0\n", 0, true},
{"command echo only", sentinel + "%errorlevel%", 0, false},
{"absent", "hello world", 0, false},
{"empty", "", 0, false},
}
for _, tc := range cases {
code, start, end, ok := scanSentinel([]byte(tc.in), sentinel)
if ok != tc.ok {
t.Errorf("%s: ok = %v, want %v", tc.name, ok, tc.ok)
continue
}
if ok && code != tc.code {
t.Errorf("%s: code = %d, want %d", tc.name, code, tc.code)
}
if ok && (start < 0 || start >= end || end > len(tc.in)) {
t.Errorf("%s: start/end = %d/%d, want 0<=start<end<=%d", tc.name, start, end, len(tc.in))
}
}
if _, _, _, ok := scanSentinel([]byte("123"), ""); ok {
t.Fatal("empty sentinel must never match")
}
}
func TestOpenSessionWaitsForReadyAndBuffers(t *testing.T) {
s, h := terminalTestServer(t)
sess, err := s.sessions.open("1001")
if err != nil {
t.Fatalf("open: %v", err)
}
if !strings.HasPrefix(sess.id, "s-") || len(sess.id) != 8 {
t.Fatalf("session id = %q, want s-XXXXXX", sess.id)
}
sess.mu.Lock()
ready := sess.ready
sess.mu.Unlock()
if ready {
t.Fatal("session must not be ready before OnTerminalReady")
}
s.OnTerminalReady("1001", true)
sess.mu.Lock()
ready, isPTY := sess.ready, sess.isPTY
sess.mu.Unlock()
if !ready || !isPTY {
t.Fatalf("after ready: ready=%v isPTY=%v", ready, isPTY)
}
// The browser demux prefix is stripped; a raw chunk is accepted as-is.
s.OnTerminalData("1001", termPacket("hello "))
s.OnTerminalData("1001", []byte("world"))
sess.mu.Lock()
data, next, lost := sess.readLocked(0, 1<<10)
sess.mu.Unlock()
if string(data) != "hello world" || next != 11 || lost {
t.Fatalf("buffered = %q next=%d lost=%v", data, next, lost)
}
// Simulate a genuine teardown: the hub releases the lease first, then its
// event reaches the MCP subscriber.
h.CloseTerminalSession("1001")
s.OnTerminalClosed("1001", "closed")
if s.sessions.get("1001") != nil {
t.Fatal("closed session still in the table")
}
sess.mu.Lock()
closed, reason := sess.closed, sess.closeReason
sess.mu.Unlock()
if !closed || reason != "closed" {
t.Fatalf("session state: closed=%v reason=%q", closed, reason)
}
}
func TestOpenSessionBusyWithBrowser(t *testing.T) {
s, h := terminalTestServer(t)
_ = s
// The web console opens the shell first (same call it makes today).
if err := h.OpenTerminalSession("1001"); err != nil {
t.Fatalf("browser open: %v", err)
}
tbl := newSessionTable(h)
if _, err := tbl.open("1001"); !errors.Is(err, hub.ErrTerminalBusy) {
t.Fatalf("open while browser holds it = %v, want ErrTerminalBusy", err)
}
if tbl.get("1001") != nil {
t.Fatal("failed open must not leave a session marker behind")
}
// After the browser closes, MCP can claim the shell.
h.CloseTerminalSession("1001")
if _, err := tbl.open("1001"); err != nil {
t.Fatalf("open after browser closed: %v", err)
}
}
func TestTerminalSentinelWakesPending(t *testing.T) {
s, _ := terminalTestServer(t)
sess, err := s.sessions.open("1001")
if err != nil {
t.Fatalf("open: %v", err)
}
s.OnTerminalReady("1001", true)
sess.mu.Lock()
sess.pending = &pendingCmd{sentinel: "__MCP_DONE_abc123__"}
sess.mu.Unlock()
s.OnTerminalData("1001", termPacket("dir\r\nfile.txt\r\n__MCP_DONE_abc123__1\r\n"))
sess.mu.Lock()
p := sess.pending
done, code, end := p.done, p.exitCode, p.outputEnd
sess.mu.Unlock()
if !done || code != 1 {
t.Fatalf("pending: done=%v code=%d", done, code)
}
if end == 0 {
t.Fatal("sentinel end offset not recorded")
}
}
func TestSessionIdleSweep(t *testing.T) {
s, _ := terminalTestServer(t)
sess, err := s.sessions.open("1001")
if err != nil {
t.Fatalf("open: %v", err)
}
sess.mu.Lock()
sess.ready = true
sess.lastUsed = time.Now().Add(-time.Hour)
sess.mu.Unlock()
if n := s.sessions.sweepIdle(time.Now(), time.Minute); n != 1 {
t.Fatalf("swept = %d, want 1", n)
}
if s.sessions.get("1001") != nil {
t.Fatal("idle session still in the table")
}
sess.mu.Lock()
closed := sess.closed
sess.mu.Unlock()
if !closed {
t.Fatal("swept session not marked closed")
}
}
func TestSessionTableCloseAll(t *testing.T) {
s, h := terminalTestServer(t)
h.Register(&hub.Device{ID: "2002", PeerIP: "10.0.0.2"},
&connection.Context{RemoteAddr: "10.0.0.2:54321"})
for _, id := range []string{"1001", "2002"} {
if _, err := s.sessions.open(id); err != nil {
t.Fatalf("open %s: %v", id, err)
}
}
s.Close()
for _, id := range []string{"1001", "2002"} {
if s.sessions.get(id) != nil {
t.Fatalf("session %s survived Close", id)
}
}
}
// A close event emitted by the previous viewer's teardown must not delete a
// session whose open already owns the hub lease. Regression for the race where
// the web console closes as MCP opens.
func TestStaleTerminalCloseKeepsSession(t *testing.T) {
s, h := terminalTestServer(t)
sess, err := s.sessions.open("1001")
if err != nil {
t.Fatalf("open: %v", err)
}
// The hub still holds our (new) pending lease, so this event describes the
// viewer that just went away.
s.OnTerminalClosed("1001", "closed")
if got := s.sessions.get("1001"); got != sess {
t.Fatal("stale close event removed the fresh session")
}
sess.mu.Lock()
closed := sess.closed
sess.mu.Unlock()
if closed {
t.Fatal("stale close event marked the fresh session closed")
}
// Once the hub really has no session, the event is genuine.
h.CloseTerminalSession("1001")
s.OnTerminalClosed("1001", "closed")
if s.sessions.get("1001") != nil {
t.Fatal("genuine close event did not remove the session")
}
}
func TestClosedIgnoredWhileOpening(t *testing.T) {
tbl := newSessionTable(nil)
sess := newTermSession("1001")
sess.opening = true
tbl.byDevice["1001"] = sess
tbl.closed("1001", "closed")
if tbl.get("1001") != sess {
t.Fatal("close event during open removed the session")
}
sess.mu.Lock()
sess.opening = false
sess.mu.Unlock()
tbl.closed("1001", "closed")
if tbl.get("1001") != nil {
t.Fatal("close after open finished did not remove the session")
}
}
// sweepIdle snapshots sessions before closing them; if the entry was replaced
// in between, the close must not take out the new session.
func TestSweepSkipsReplacedSession(t *testing.T) {
tbl := newSessionTable(nil)
old := newTermSession("1001")
old.lastUsed = old.lastUsed.Add(-time.Hour)
fresh := newTermSession("1001")
tbl.byDevice["1001"] = fresh
if tbl.closeSessionIf("1001", old) {
t.Fatal("closeSessionIf closed a session it did not own")
}
if tbl.get("1001") != fresh {
t.Fatal("replacement session was removed")
}
if n := tbl.sweepIdle(time.Now(), time.Minute); n != 0 {
t.Fatalf("swept = %d, want 0", n)
}
}
// A draining session's close must not tear down a hub lease that a reconnected
// viewer has since opened: the shell the session referred to is already gone.
func TestCloseOfEndedSessionLeavesNewHubLease(t *testing.T) {
s, h := terminalTestServer(t)
sess, err := s.sessions.open("1001")
if err != nil {
t.Fatalf("open: %v", err)
}
s.OnTerminalReady("1001", true)
if _, rerr := sess.beginCommand("ab12cd34", "cmd", ""); rerr != nil {
t.Fatalf("begin: %v", rerr)
}
s.OnTerminalData("1001", termPacket("out\r\n"))
// The shell ends with output the client has not polled yet: the session
// stays in the table so the tail can still be collected. The hub event is
// delivered to subscribers by cmd/main.go's wiring.
h.CloseTerminalSession("1001")
s.OnTerminalClosed("1001", "closed")
if s.sessions.get("1001") != sess {
t.Fatal("draining session was dropped")
}
// Another viewer (or the same device after reconnecting) gets a fresh lease.
if err := h.OpenTerminalSession("1001"); err != nil {
t.Fatalf("new lease: %v", err)
}
if !h.HasTerminalSession("1001") {
t.Fatal("new lease not established")
}
if !s.sessions.closeSessionIf("1001", sess) {
t.Fatal("close did not remove the draining session")
}
if !h.HasTerminalSession("1001") {
t.Fatal("closing the ended session tore down the new viewer's shell")
}
}
func TestSentinelSplitAcrossChunks(t *testing.T) {
s, _ := terminalTestServer(t)
sess, err := s.sessions.open("1001")
if err != nil {
t.Fatalf("open: %v", err)
}
s.OnTerminalReady("1001", true)
sess.mu.Lock()
sess.pending = &pendingCmd{sentinel: "__MCP_DONE_abc123__"}
sess.mu.Unlock()
// The sentinel prefix ends more than 64 bytes before the chunk boundary,
// so the retained overlap is what lets the second chunk complete it.
s.OnTerminalData("1001", termPacket(strings.Repeat("x", 100)+"__MCP_DONE_ab"))
s.OnTerminalData("1001", termPacket("c123__3\r\n"))
sess.mu.Lock()
p := sess.pending
done, code := p.done, p.exitCode
sess.mu.Unlock()
if !done || code != 3 {
t.Fatalf("split sentinel: done=%v code=%d", done, code)
}
}
// A quiet command still owns the device's shell lease: the reaper must not
// reclaim a session just because it printed nothing for a while.
func TestSweepKeepsRunningCommand(t *testing.T) {
tbl := newSessionTable(nil)
sess := newTermSession("1001")
sess.ready = true
sess.lastUsed = sess.lastUsed.Add(-time.Hour)
sess.pending = &pendingCmd{start: 0, busySince: time.Now()}
tbl.byDevice["1001"] = sess
if n := tbl.sweepIdle(time.Now(), time.Minute); n != 0 {
t.Fatalf("swept = %d, want 0 while the command runs", n)
}
if tbl.get("1001") != sess {
t.Fatal("running session was removed")
}
}
// Once the shell is gone, only the undelivered tail keeps the session alive;
// a model that never polls must not pin the slot indefinitely.
func TestSweepReapsClosedDrainingSession(t *testing.T) {
tbl := newSessionTable(nil)
sess := newTermSession("1001")
sess.ready = true
sess.closed = true
sess.pending = &pendingCmd{busySince: time.Now()}
sess.lastUsed = sess.lastUsed.Add(-time.Hour)
tbl.byDevice["1001"] = sess
if n := tbl.sweepIdle(time.Now(), time.Minute); n != 1 {
t.Fatalf("swept = %d, want 1", n)
}
if tbl.get("1001") != nil {
t.Fatal("draining session not removed")
}
}
// The reaper is wired to a ticker in New: an idle session is reclaimed without
// any further tool call.
func TestSweepTickerReclaimsIdleSession(t *testing.T) {
h := hub.New()
h.SetSender(func(*connection.Context, []byte) error { return nil })
h.Register(&hub.Device{ID: "1001", PeerIP: "10.0.0.1"},
&connection.Context{RemoteAddr: "10.0.0.1:54321"})
s := New(Config{Token: testToken, Hub: h, TermIdle: 100 * time.Millisecond})
t.Cleanup(s.Close)
if _, err := s.sessions.open("1001"); err != nil {
t.Fatalf("open: %v", err)
}
s.OnTerminalReady("1001", true)
deadline := time.Now().Add(3 * time.Second)
for s.sessions.get("1001") != nil {
if time.Now().After(deadline) {
t.Fatal("idle session was not reaped by the ticker")
}
time.Sleep(10 * time.Millisecond)
}
if h.HasTerminalSession("1001") {
t.Fatal("reaped session still holds the hub lease")
}
}
// A command that outlives the busy cap is reclaimed even with no output and no
// poller, so a hung shell cannot hold the device slot forever.
func TestSweepReapsOverdueCommand(t *testing.T) {
tbl := newSessionTable(nil)
sess := newTermSession("1001")
sess.ready = true
sess.lastUsed = sess.lastUsed.Add(-time.Minute)
sess.pending = &pendingCmd{start: 0, busySince: time.Now().Add(-termBusyMax - time.Second)}
tbl.byDevice["1001"] = sess
if n := tbl.sweepIdle(time.Now(), time.Minute); n != 1 {
t.Fatalf("swept = %d, want 1 for an overdue command", n)
}
if tbl.get("1001") != nil {
t.Fatal("overdue session not removed")
}
}
// A session whose shell never bound has a caller still waiting on it; the
// reaper must leave it to that caller's own release path.
func TestSweepKeepsNotReadySession(t *testing.T) {
tbl := newSessionTable(nil)
sess := newTermSession("1001")
sess.lastUsed = sess.lastUsed.Add(-time.Hour)
tbl.byDevice["1001"] = sess
if n := tbl.sweepIdle(time.Now(), time.Minute); n != 0 {
t.Fatalf("swept = %d, want 0 for a session still opening", n)
}
if tbl.get("1001") != sess {
t.Fatal("not-ready session was removed")
}
}
// A device re-login drops a pending lease without emitting OnTerminalClosed.
// If a human then takes the freed slot, a late close from the MCP session that
// lost it must not tear the human's shell down (design §6.2: never pre-empt).
func TestCloseLeavesRenewedLeaseAlone(t *testing.T) {
s, h := terminalTestServer(t)
sess, err := s.sessions.open("1001")
if err != nil {
t.Fatalf("open: %v", err)
}
// Register carries the terminal generation over, exactly like a real
// re-login racing the old connection's disconnect.
h.Register(&hub.Device{ID: "1001", PeerIP: "10.0.0.1"},
&connection.Context{RemoteAddr: "10.0.0.1:54321"})
if err := h.OpenTerminalSession("1001"); err != nil {
t.Fatalf("human open: %v", err)
}
if !s.sessions.closeSessionIf("1001", sess) {
t.Fatal("close did not remove the stale session")
}
if !h.HasTerminalSession("1001") {
t.Fatal("close tore down a lease the stale session no longer owned")
}
}
func TestCloseStopsReaper(t *testing.T) {
s, _ := terminalTestServer(t)
s.Close()
select {
case <-s.reaperDone:
default:
t.Fatal("Close returned before the reaper stopped")
}
s.Close() // idempotent; the Cleanup will call it a third time
}
+210
View File
@@ -0,0 +1,210 @@
package mcp
import (
"bytes"
"strconv"
"sync"
"time"
)
// termRingCap bounds one session's retained output. A shell that floods the
// session (a log tail, a build) must not grow server memory without bound;
// the oldest bytes are dropped and the loss is surfaced as truncated output
// (design §6.3).
const termRingCap = 256 << 10
// pendingCmd is one command whose output is still being collected. It lives
// on the session so a timed-out terminal_exec can hand the same command back
// to a later polling call: the shell keeps running and its output keeps
// accumulating whether or not an HTTP request is attached.
type pendingCmd struct {
sentinel string // "__MCP_DONE_<6 hex>__"
nonce string // the 6-hex id inside sentinel, for output cleaning
cmdLine string // wire command line, removed from the PTY's echo
sentLine string // wire sentinel line, removed from the PTY's echo
start uint64 // absolute offset where this command's output begins
scanPos uint64 // absolute offset scanned so far (sentinel may span chunks)
deadline time.Time // when the current waiter gives up (the session survives)
done bool
exitCode int
outputEnd uint64 // absolute offset where the delivered output ends (sentinel start)
lost uint64 // this command's bytes evicted by the ring, cumulative
// firstChunk is true until the command's first delivery window is cleaned:
// the PTY echoes the input exactly once, at the start.
firstChunk bool
busySince time.Time // when the command started, for the M4c busy reaper
}
// termSession is the server-side view of one shell child. All mutable state
// is guarded by mu; cond wakes a waiter when data arrives, the command ends,
// or the session closes.
type termSession struct {
id string
deviceID string
createdAt time.Time
mu sync.Mutex
cond *sync.Cond
lastUsed time.Time
buf []byte // ring of termRingCap bytes
head int // index the next write goes to
size int // valid bytes in buf
total uint64 // bytes the shell produced, including dropped ones
delivered uint64 // absolute offset already handed to the client
droppedBytes uint64
isPTY bool
ready bool // OnTerminalReady seen
sawOutput bool // shell printed its first screen (prompt); bootstrap done
opening bool // hub.OpenTerminalSession still in flight
lease uint64 // hub lease generation; 0 until the open completes
closed bool
closeReason string
pending *pendingCmd // nil = idle
}
func newTermSession(deviceID string) *termSession {
now := time.Now()
s := &termSession{
id: newSessionID(),
deviceID: deviceID,
createdAt: now,
lastUsed: now,
buf: make([]byte, termRingCap),
}
s.cond = sync.NewCond(&s.mu)
return s
}
// baseLocked is the absolute offset of the oldest retained byte.
func (s *termSession) baseLocked() uint64 { return s.total - uint64(s.size) }
// appendLocked writes p into the ring, dropping the oldest bytes on overflow.
// total counts every byte the shell produced, including dropped ones, so the
// absolute offsets stay monotonic and a client can tell that it lost data.
func (s *termSession) appendLocked(p []byte) {
s.lastUsed = time.Now()
if len(p) == 0 {
return
}
s.sawOutput = true
if len(p) > len(s.buf) {
drop := len(p) - len(s.buf)
s.droppedBytes += uint64(drop)
s.total += uint64(drop)
p = p[drop:]
}
if overflow := s.size + len(p) - len(s.buf); overflow > 0 {
// The oldest overflow bytes are simply forgotten: head still marks
// the next write, and size now describes a shorter prefix.
s.droppedBytes += uint64(overflow)
s.size -= overflow
}
if n := copy(s.buf[s.head:], p); n < len(p) {
copy(s.buf, p[n:])
}
s.head = (s.head + len(p)) % len(s.buf)
s.size += len(p)
s.total += uint64(len(p))
}
// readLocked returns up to max bytes starting at absolute offset. lost is
// true when the requested offset predates the ring's oldest byte; the data
// then starts at the oldest retained byte instead.
func (s *termSession) readLocked(offset uint64, max int) (data []byte, next uint64, lost bool) {
if max <= 0 {
return nil, offset, false
}
base := s.baseLocked()
if offset < base {
offset = base
lost = true
}
if offset >= s.total {
return nil, s.total, lost
}
n := int(min(s.total-offset, uint64(max)))
idx := (s.head - s.size + int(offset-base)) % len(s.buf)
if idx < 0 {
idx += len(s.buf)
}
data = make([]byte, n)
first := copy(data, s.buf[idx:min(idx+n, len(s.buf))])
copy(data[first:], s.buf[:n-first])
return data, offset + uint64(n), lost
}
// scanPendingLocked looks for the in-flight command's sentinel in the bytes
// appended since the last look. A tail overlap is retained so a sentinel split
// across two TCP reads is still found.
func (s *termSession) scanPendingLocked() {
p := s.pending
if p == nil || p.done {
return
}
from := max(p.scanPos, s.baseLocked())
if from >= s.total {
return
}
data, next, _ := s.readLocked(from, int(s.total-from))
if code, start, _, ok := scanSentinel(data, p.sentinel); ok {
p.done = true
p.exitCode = code
// Deliver only up to the sentinel itself: the echoed sentinel line and
// the prompt printed after it are not the command's output.
p.outputEnd = from + uint64(start)
s.cond.Broadcast()
return
}
// Keep the last few bytes: the next chunk may complete a sentinel whose
// prefix sits just before the boundary.
const overlap = 64
if next > overlap {
next -= overlap
}
if next > p.scanPos {
p.scanPos = next
}
}
// scanSentinel finds the first occurrence of sentinel followed by a decimal
// exit code. The Windows %errorlevel% is signed (0xC000013A prints as
// -1073741510), so a leading '-' is accepted. start is where the sentinel
// begins (delivery stops there); end is one past the last digit.
//
// Echoed command lines contain the sentinel too but not the exit code
// ("__MCP_DONE_x__$?" / "__MCP_DONE_x__%errorlevel%"), so occurrences without
// digits are skipped rather than reported.
func scanSentinel(data []byte, sentinel string) (code, start, end int, ok bool) {
if sentinel == "" {
// Defensive: an empty needle matches everywhere and would spin the
// device read loop. Callers always mint a non-empty sentinel.
return 0, 0, 0, false
}
needle := []byte(sentinel)
from := 0
for {
idx := bytes.Index(data[from:], needle)
if idx < 0 {
return 0, 0, 0, false
}
idx += from
rest := data[idx+len(needle):]
i := 0
if i < len(rest) && rest[i] == '-' {
i++
}
digits := i
for i < len(rest) && rest[i] >= '0' && rest[i] <= '9' {
i++
}
if i > digits {
if n, err := strconv.Atoi(string(rest[:i])); err == nil {
return n, idx, idx + len(needle) + i, true
}
}
from = idx + len(needle)
}
}
+88
View File
@@ -0,0 +1,88 @@
package mcp
import (
_ "embed"
"encoding/json"
)
// tools_minimal.json is generated from mcp/tools.json by
// tools/mcp_tools/gen_go_tools.py — never edit it by hand. It is embedded so
// tools/list is a compile-time constant: no disk I/O, no drift between the
// schema the model sees and the schema the handlers were written against.
//
//go:embed tools_minimal.json
var toolsJSON []byte
// writeTools are hidden from tools/list in readonly mode and rejected with
// -32006 if called anyway (design §3.1: readonly exposes 7 of 9 tools).
var writeTools = map[string]bool{
"terminal_exec": true,
"terminal_close": true,
}
// unlockedTools run without the per-device lock. terminal_close must be usable
// while a terminal_exec call is still waiting on the same device: that call
// holds the lock for its whole timeout, and a close that answers -32003 could
// never interrupt it.
var unlockedTools = map[string]bool{
"terminal_close": true,
}
// toolDef holds one published definition plus its name, so filtering does not
// re-parse the JSON on every tools/list call.
type toolDef struct {
name string
raw json.RawMessage
}
type toolSet struct {
defs []toolDef
names map[string]bool
}
// buildToolSet validates the embedded payload once at startup. A malformed
// file is a build defect, so panic loudly rather than serve a broken list.
func buildToolSet(raw []byte) *toolSet {
var raws []json.RawMessage
if err := json.Unmarshal(raw, &raws); err != nil {
panic("mcp: embedded tools_minimal.json is not a JSON array: " + err.Error())
}
ts := &toolSet{defs: make([]toolDef, 0, len(raws)), names: make(map[string]bool, len(raws))}
for _, r := range raws {
var head struct {
Name string `json:"name"`
}
if err := json.Unmarshal(r, &head); err != nil || head.Name == "" {
panic("mcp: embedded tool definition without a name")
}
if ts.names[head.Name] {
panic("mcp: duplicate embedded tool " + head.Name)
}
ts.names[head.Name] = true
ts.defs = append(ts.defs, toolDef{name: head.Name, raw: r})
}
return ts
}
// visible returns the tool definitions to publish, preserving tools.json
// order. The raw bytes are passed through untouched, so descriptions and
// schemas stay exactly what mcp/tools.json says (no annotations, like MFC).
func (ts *toolSet) visible(readonly bool) []json.RawMessage {
out := make([]json.RawMessage, 0, len(ts.defs))
for _, def := range ts.defs {
if readonly && writeTools[def.name] {
continue
}
out = append(out, def.raw)
}
return out
}
// known reports whether name is a tool this server defines, including tools
// hidden by readonly mode. Unknown names are -32601; hidden ones are -32006.
func (ts *toolSet) known(name string) bool { return ts.names[name] }
// toolsListResult is the MCP tools/list payload.
type toolsListResult struct {
Tools []json.RawMessage `json:"tools"`
}
+694
View File
@@ -0,0 +1,694 @@
package mcp
import (
"context"
"encoding/json"
"fmt"
"strconv"
"strings"
"time"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/auditquery"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/hub"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/protocol"
)
// Local read tools: they answer from the server's own state (device hub,
// device history, audit file) and never open a channel to a client. The
// remote tools (screenshot, files, terminal) live in later milestones.
const (
// Page size bounds shared by list_hosts and get_audit_log, matching the
// tool descriptions in mcp/tools.json.
listDefaultLimit = 100
listMaxLimit = 1000
// batchMaxIDs is the per-call cap for get_host_detail.ids, matching the
// Win32 server.
batchMaxIDs = 50
)
// toolResult is the MCP tools/call success envelope, byte-compatible with the
// Win32 server: one text item plus structuredContent. Failures are JSON-RPC
// error objects at the top level, not isError results.
type toolResult struct {
Content []contentItem `json:"content"`
StructuredContent any `json:"structuredContent"`
IsError bool `json:"isError"`
}
// contentItem is one MCP content block. Text tools fill Text; get_screenshot
// emits an image block (Data is base64, MimeType image/jpeg), so both the text
// and image fields are optional on the wire.
type contentItem struct {
Type string `json:"type"`
Text string `json:"text,omitempty"`
Data string `json:"data,omitempty"`
MimeType string `json:"mimeType,omitempty"`
}
func newToolResult(text string, structured any) toolResult {
return toolResult{
Content: []contentItem{{Type: "text", Text: text}},
StructuredContent: structured,
IsError: false,
}
}
func (s *Server) registerLocalTools() {
s.handlers["list_hosts"] = s.callListHosts
s.handlers["get_host_detail"] = s.callGetHostDetail
s.handlers["get_server_status"] = s.callGetServerStatus
s.handlers["get_audit_log"] = s.callGetAuditLog
}
// decodeArgs unmarshals tools/call arguments into v. An absent/null arguments
// object leaves v at its zero value, which is valid for the all-optional tools.
func decodeArgs(raw json.RawMessage, v any) *rpcError {
if len(raw) == 0 || string(raw) == "null" {
return nil
}
if err := json.Unmarshal(raw, v); err != nil {
return errf(CodeInvalidParams, "invalid arguments: %v", err)
}
return nil
}
// ----- list_hosts -----------------------------------------------------------
type listHostsArgs struct {
ClientType string `json:"client_type"`
Group string `json:"group"`
IncludeOffline *bool `json:"include_offline"`
IP string `json:"ip"`
Limit int `json:"limit"`
Name string `json:"name"`
Offset int `json:"offset"`
Online *bool `json:"online"`
OS string `json:"os"`
Query string `json:"query"`
}
func (s *Server) callListHosts(_ context.Context, raw json.RawMessage) (any, *rpcError) {
if s.cfg.Hub == nil {
return nil, errf(CodeInternal, "server device registry is not configured")
}
var args listHostsArgs
if rerr := decodeArgs(raw, &args); rerr != nil {
return nil, rerr
}
// online defaults to true (only online hosts). online=false means "only
// offline"; include_offline=true merges history behind the online hosts.
online := true
if args.Online != nil {
online = *args.Online
}
includeOffline := args.IncludeOffline != nil && *args.IncludeOffline
onlineDevices := s.cfg.Hub.ListDevices()
onlineSet := make(map[string]struct{}, len(onlineDevices))
for _, d := range onlineDevices {
onlineSet[d.ID] = struct{}{}
}
offlineDevices := s.offlineDevices(onlineSet)
var pool []hub.DeviceInfo
switch {
case !online:
pool = offlineDevices
case includeOffline:
pool = make([]hub.DeviceInfo, 0, len(onlineDevices)+len(offlineDevices))
pool = append(pool, onlineDevices...)
pool = append(pool, offlineDevices...)
default:
pool = onlineDevices
}
totalAll := len(pool)
// All filters are optional, ANDed, and substring matches. ASCII case
// folding is what the tool description promises; strings.ToLower is a
// superset and cannot change an ASCII-only match.
q := strings.ToLower(args.Query)
nameF := strings.ToLower(args.Name)
ipF := strings.ToLower(args.IP)
groupF := strings.ToLower(args.Group)
osF := strings.ToLower(args.OS)
ctF := strings.ToLower(args.ClientType)
matched := make([]hub.DeviceInfo, 0, len(pool))
for _, d := range pool {
group := d.Group
if group == "" {
group = "default"
}
ip := d.IP
if ip == "" {
ip = d.PeerIP
}
clientType := ""
if d.Online {
clientType = s.clientType(d.ID)
}
// query matches computer name, remark and IP. The two servers keep no
// remark column, so name+IP is the full set here.
if q != "" && !strings.Contains(strings.ToLower(d.Name), q) && !strings.Contains(strings.ToLower(ip), q) {
continue
}
if nameF != "" && !strings.Contains(strings.ToLower(d.Name), nameF) {
continue
}
if ipF != "" && !strings.Contains(strings.ToLower(ip), ipF) {
continue
}
if groupF != "" && !strings.Contains(strings.ToLower(group), groupF) {
continue
}
if osF != "" && !strings.Contains(strings.ToLower(d.OS), osF) {
continue
}
if ctF != "" && !strings.Contains(strings.ToLower(clientType), ctF) {
continue
}
matched = append(matched, d)
}
limit := clampPageLimit(args.Limit)
offset := max(args.Offset, 0)
total := len(matched)
begin := min(offset, total)
end := min(begin+limit, total)
hosts := make([]map[string]any, 0, end-begin)
for _, d := range matched[begin:end] {
hosts = append(hosts, s.hostJSON(d))
}
structured := map[string]any{
"hosts": hosts,
"total": total,
"totalAll": totalAll,
"limit": limit,
"offset": offset,
"hasMore": end < total,
}
text := pageSummary(total, limit, offset, "台主机")
if total != totalAll {
text += fmt.Sprintf("过滤前共 %d 台。", totalAll)
}
text = appendHostRows(text, hosts)
return newToolResult(text, structured), nil
}
// hostJSON projects a hub device onto the list_hosts/get_host_detail schema.
// Fields the Go server does not know (authStatus, tls, remark, clientType of
// an offline entry) are omitted rather than fabricated.
func (s *Server) hostJSON(d hub.DeviceInfo) map[string]any {
group := d.Group
if group == "" {
group = "default"
}
h := map[string]any{
"id": d.ID,
"name": d.Name,
"group": group,
"online": d.Online,
}
if d.Version != "" {
h["version"] = d.Version
}
if d.OS != "" {
h["os"] = d.OS
}
ip := d.IP
if ip == "" {
ip = d.PeerIP
}
if ip != "" {
h["ip"] = ip
}
if d.Location != "" {
h["location"] = d.Location
}
if d.InstallTime != "" {
h["install_time"] = d.InstallTime
}
if d.Screen != "" {
h["screen"] = d.Screen
}
if d.Online {
// RTT 0 means "no heartbeat yet", not "zero latency".
if d.RTT > 0 {
h["rtt"] = strconv.Itoa(d.RTT)
}
if d.ActiveWindow != "" {
h["activeWindow"] = d.ActiveWindow
}
if ct := s.clientType(d.ID); ct != "" {
h["clientType"] = ct
}
} else if d.LastSeen > 0 {
h["last_seen"] = time.Unix(d.LastSeen, 0).Format("2006-01-02 15:04:05")
}
return h
}
// clientType reads the RES_CLIENT_TYPE the client reported at login. It lives
// on the main connection's ClientInfo, not on the hub's Device projection.
func (s *Server) clientType(deviceID string) string {
if s.cfg.Hub == nil {
return ""
}
if ctx := s.cfg.Hub.MainConn(deviceID); ctx != nil {
return ctx.GetInfo().ClientType
}
return ""
}
// offlineDevices returns history entries that are not currently online. A nil
// history store (server started without persistence) yields no entries.
func (s *Server) offlineDevices(online map[string]struct{}) []hub.DeviceInfo {
if s.cfg.History == nil {
return nil
}
return s.cfg.History.Offline(online)
}
// ----- get_host_detail ------------------------------------------------------
type getHostDetailArgs struct {
ID string `json:"id"`
IDs []string `json:"ids"`
}
func (s *Server) callGetHostDetail(_ context.Context, raw json.RawMessage) (any, *rpcError) {
if s.cfg.Hub == nil {
return nil, errf(CodeInternal, "server device registry is not configured")
}
var args getHostDetailArgs
if rerr := decodeArgs(raw, &args); rerr != nil {
return nil, rerr
}
if len(args.IDs) > 0 {
return s.hostDetailBatch(args.IDs)
}
if args.ID == "" {
return nil, errf(CodeInvalidParams, "Missing required parameter: id or ids")
}
online, offline := s.hostMaps()
host, rerr := s.lookupHost(args.ID, online, offline)
if rerr != nil {
return nil, rerr
}
return newToolResult(hostDetailText(host), map[string]any{"host": host}), nil
}
func (s *Server) hostDetailBatch(ids []string) (any, *rpcError) {
if len(ids) > batchMaxIDs {
return nil, errf(CodeInvalidParams,
"Too many ids: %d (max %d per batch)", len(ids), batchMaxIDs)
}
online, offline := s.hostMaps()
results := make([]map[string]any, 0, len(ids))
succeeded, failed := 0, 0
for _, id := range ids {
host, rerr := s.lookupHost(id, online, offline)
if rerr != nil {
results = append(results, map[string]any{
"id": id,
"ok": false,
"text": rerr.Message,
"error": map[string]any{"code": rerr.Code, "message": rerr.Message},
})
failed++
continue
}
results = append(results, map[string]any{
"id": id,
"ok": true,
"text": hostSummary(host),
"data": map[string]any{"host": host},
})
succeeded++
}
structured := map[string]any{
"tool": "get_host_detail",
"total": len(ids),
"succeeded": succeeded,
"failed": failed,
"skipped": 0, // no batch deadline: every id is answered locally
"results": results,
}
text := fmt.Sprintf("批量调用 get_host_detail:共 %d 台,成功 %d 台,失败 %d 台。",
len(ids), succeeded, failed)
text = appendBatchRows(text, results)
return newToolResult(text, structured), nil
}
// hostMaps indexes the online devices and offline history by ID. Building both
// once per call keeps a 50-id batch at one hub snapshot instead of 50.
func (s *Server) hostMaps() (online, offline map[string]hub.DeviceInfo) {
onlineDevices := s.cfg.Hub.ListDevices()
online = make(map[string]hub.DeviceInfo, len(onlineDevices))
onlineSet := make(map[string]struct{}, len(onlineDevices))
for _, d := range onlineDevices {
online[d.ID] = d
onlineSet[d.ID] = struct{}{}
}
offlineDevices := s.offlineDevices(onlineSet)
offline = make(map[string]hub.DeviceInfo, len(offlineDevices))
for _, d := range offlineDevices {
offline[d.ID] = d
}
return online, offline
}
// lookupHost resolves one host: online first, then the last-known history
// record. It mirrors the Win32 server, which answers offline hosts with their
// final snapshot instead of an error.
func (s *Server) lookupHost(id string, online, offline map[string]hub.DeviceInfo) (map[string]any, *rpcError) {
if !isDecimalID(id) {
return nil, errf(CodeInvalidParams, "Invalid id: expected a decimal host id string")
}
if d, ok := online[id]; ok {
h := s.hostJSON(d)
h["capabilities"] = s.capabilities(d)
return h, nil
}
if d, ok := offline[id]; ok {
return s.hostJSON(d), nil
}
return nil, errf(CodeOffline, "Host not found or offline: %s", id)
}
// capabilities answers "what can this host do" from the capability hex string
// the client reported at login. v2 is deliberately absent: CLIENT_CAP_V2 is
// set by every platform, so listing it would only mislead.
func (s *Server) capabilities(d hub.DeviceInfo) map[string]any {
platform := s.clientType(d.ID)
windows := platform != "LNX" && platform != "MAC" && platform != "APK"
monitors := monitorCount(d.Screen)
// Multi-monitor Windows needs whole-virtual-desktop capture for the
// observed and injected coordinate spaces to line up; monitorCount 0
// means the client did not report the "N:W*H" form (legacy) and passes,
// matching the Win32 server's remote_open gate.
virtualDesktopOK := monitors <= 1 || !windows ||
protocol.SupportsCap(d.Capability, protocol.ClientCapVirtualDesktop)
caps := map[string]any{
"screenPreview": protocol.SupportsCap(d.Capability, protocol.ClientCapScreenPreview),
"screenRegion": protocol.SupportsCap(d.Capability, protocol.ClientCapScreenRegion),
"windowInfo": protocol.SupportsCap(d.Capability, protocol.ClientCapWindowInfo),
"fileTransferV2": protocol.SupportsCap(d.Capability, protocol.ClientCapV2),
"c2cPaths": protocol.SupportsCap(d.Capability, protocol.ClientCapC2CPaths),
"registry": windows,
"remoteControl": (windows || platform == "LNX" || platform == "APK") && virtualDesktopOK,
}
if platform != "" {
caps["platform"] = platform
}
return caps
}
// hostSummary is the human-readable text item for one host.
func hostSummary(h map[string]any) string {
name, _ := h["name"].(string)
ip, _ := h["ip"].(string)
if online, _ := h["online"].(bool); !online {
return fmt.Sprintf("主机 %s (%s) 当前离线,以下为其最后一次登录时的记录。", name, ip)
}
return fmt.Sprintf("主机 %s (%s) 的详情。", name, ip)
}
// hostDetailText is the text block for one host: the summary line followed by
// the host object as compact JSON. Text-only MCP clients never surface
// structuredContent, so without this they would see neither the id nor any
// field of the host they just asked about.
func hostDetailText(h map[string]any) string {
summary := hostSummary(h)
b, err := json.Marshal(h)
if err != nil {
return summary
}
return summary + "\n" + string(b)
}
// appendHostRows renders the returned page as a tab-separated table. The host
// id comes first because every follow-up tool (read_file, get_host_detail,
// terminal_exec, ...) is addressed by it.
func appendHostRows(text string, hosts []map[string]any) string {
rows := make([][]string, 0, len(hosts))
for _, h := range hosts {
online, _ := h["online"].(bool)
rows = append(rows, []string{
tableText(h["id"]), tableText(h["name"]), tableText(h["ip"]),
tableText(h["group"]), tableText(h["os"]), strconv.FormatBool(online),
tableText(h["clientType"]), tableText(h["last_seen"]),
})
}
return appendRows(text,
[]string{"id", "name", "ip", "group", "os", "online", "clientType", "last_seen"},
rows)
}
// appendBatchRows lists each batch result on its own line: failures carry the
// error message, successes the full host JSON.
func appendBatchRows(text string, results []map[string]any) string {
rows := make([][]string, 0, len(results))
for _, r := range results {
ok, _ := r["ok"].(bool)
var detail string
if ok {
if data, _ := r["data"].(map[string]any); data != nil {
if b, err := json.Marshal(data["host"]); err == nil {
detail = string(b)
}
}
} else {
detail, _ = r["text"].(string)
}
rows = append(rows, []string{tableText(r["id"]), strconv.FormatBool(ok), detail})
}
return appendRows(text, []string{"id", "ok", "detail"}, rows)
}
// ----- get_server_status ----------------------------------------------------
func (s *Server) callGetServerStatus(_ context.Context, _ json.RawMessage) (any, *rpcError) {
uptime := max(int64(time.Since(s.cfg.StartedAt).Seconds()), 0)
status := map[string]any{
"version": s.cfg.Version,
"uptime_sec": uptime,
}
text := fmt.Sprintf("YAMA Go 服务端已运行 %d 秒", uptime)
if s.cfg.Version != "" {
text = fmt.Sprintf("YAMA Go 服务端 %s 已运行 %d 秒", s.cfg.Version, uptime)
}
if s.cfg.Hub != nil {
onlineDevices := s.cfg.Hub.ListDevices()
onlineSet := make(map[string]struct{}, len(onlineDevices))
for _, d := range onlineDevices {
onlineSet[d.ID] = struct{}{}
}
offline := len(s.offlineDevices(onlineSet))
status["hosts"] = map[string]any{"online": len(onlineDevices), "offline": offline}
text += fmt.Sprintf(";在线 %d 台,离线 %d 台", len(onlineDevices), offline)
}
// MCP is mounted on the web server, so its listening address is the web
// server's. Port/bind stay absent when the caller did not provide them.
if s.cfg.Port > 0 {
status["port"] = s.cfg.Port
}
if s.cfg.Bind != "" {
status["bind"] = s.cfg.Bind
text += ",监听 " + s.cfg.Bind
}
// The status fields are flat in structuredContent (the outputSchema has no
// "status" wrapper object).
return newToolResult(text+"。", status), nil
}
// ----- get_audit_log --------------------------------------------------------
type getAuditLogArgs struct {
Keyword string `json:"keyword"`
Limit int `json:"limit"`
Offset int `json:"offset"`
Type string `json:"type"`
}
func (s *Server) callGetAuditLog(_ context.Context, raw json.RawMessage) (any, *rpcError) {
if s.cfg.AuditPath == "" {
return nil, errf(CodeInternal,
"audit log file is disabled on this server (YAMA_AUDIT_LOG=off)")
}
var args getAuditLogArgs
if rerr := decodeArgs(raw, &args); rerr != nil {
return nil, rerr
}
q := auditquery.Query{
Keyword: args.Keyword,
// The tool's "type" column is a case-insensitive substring of the
// event name; the web UI's exact/prefix Event filter does not fit.
EventContains: args.Type,
}
q.Limit = auditquery.ClampLimit(args.Limit, auditquery.MaxLimit)
q.Offset = auditquery.ClampOffset(args.Offset)
res, err := auditquery.Scan(s.cfg.AuditPath, q)
if err != nil {
return nil, errf(CodeInternal, "failed to read audit log: %v", err)
}
entries := make([]map[string]any, 0, len(res.Events))
for _, rec := range res.Events {
entries = append(entries, map[string]any{
"type": auditquery.StringField(rec, "event"),
"time": auditquery.StringField(rec, "time"),
"msg": auditMessage(rec),
})
}
// Scan caps Offset at auditquery.MaxOffset, so a page that reaches that
// point must not advertise a next page: the follow-up offset would be
// clamped back and return the same records forever.
reached := q.Offset + len(entries)
structured := map[string]any{
"entries": entries,
"total": res.Total,
"totalAll": res.TotalAll,
"limit": q.Limit,
"offset": q.Offset,
"hasMore": reached < res.Total && reached < auditquery.MaxOffset,
}
text := pageSummary(res.Total, q.Limit, q.Offset, "条日志")
if res.Total != res.TotalAll {
text += fmt.Sprintf("过滤前共 %d 条。", res.TotalAll)
}
if res.Truncated {
text += "(审计文件较大,仅扫描最近 32 MB。)"
}
rows := make([][]string, 0, len(entries))
for _, e := range entries {
rows = append(rows, []string{tableText(e["time"]), tableText(e["type"]), tableText(e["msg"])})
}
text = appendRows(text, []string{"time", "type", "msg"}, rows)
return newToolResult(text, structured), nil
}
// auditMessage renders the non-envelope fields as compact JSON. The web audit
// page shows the raw record; the MCP entry has dedicated type/time columns, so
// repeating them inside msg would only add noise.
func auditMessage(rec map[string]any) string {
rest := make(map[string]any, len(rec))
for k, v := range rec {
switch k {
case "audit", "level", "time", "event":
continue
}
rest[k] = v
}
if len(rest) == 0 {
return ""
}
b, err := json.Marshal(rest)
if err != nil {
return ""
}
return string(b)
}
// ----- shared helpers -------------------------------------------------------
func clampPageLimit(n int) int {
if n <= 0 {
return listDefaultLimit
}
if n > listMaxLimit {
return listMaxLimit
}
return n
}
// appendRows appends a tab-separated table to a summary line. The first
// column is always the addressable key (host id, file name, ...), because a
// text-only client sees only content[].text and needs the key for the next
// call. structuredContent remains the authoritative, exact copy.
func appendRows(text string, header []string, rows [][]string) string {
if len(rows) == 0 {
return text
}
var b strings.Builder
b.WriteString(text)
b.WriteByte('\n')
b.WriteString(strings.Join(header, "\t"))
for _, row := range rows {
b.WriteByte('\n')
for i, cell := range row {
if i > 0 {
b.WriteByte('\t')
}
b.WriteString(oneLine(cell))
}
}
return b.String()
}
// tableText extracts a string field. An absent field yields "", which oneLine
// renders as "-".
func tableText(v any) string {
s, _ := v.(string)
return s
}
// oneLine keeps a table cell on one line: a tab or newline inside a value
// would break the column layout. The exact value stays in structuredContent.
func oneLine(s string) string {
if s == "" {
return "-"
}
return strings.NewReplacer("\t", " ", "\r", " ", "\n", " ").Replace(s)
}
// pageSummary mirrors the Win32 server's summary line:
// 「共 N 台主机,本次返回第 1-100 条(还有更多,可用 offset 继续取)。」
func pageSummary(total, limit, offset int, unit string) string {
out := fmt.Sprintf("共 %d %s", total, unit)
if total == 0 {
return out + "。"
}
begin := min(offset, total)
if begin >= total {
return out + ",offset 超出范围,本次返回 0 条。"
}
end := min(begin+limit, total)
out += fmt.Sprintf(",本次返回第 %d-%d 条", begin+1, end)
if end < total {
out += "(还有更多,可用 offset 继续取)"
}
return out + "。"
}
// isDecimalID reports whether id is a non-empty decimal string. Host IDs are
// uint64 rendered in decimal; anything else is a caller mistake.
func isDecimalID(id string) bool {
if id == "" {
return false
}
for _, r := range id {
if r < '0' || r > '9' {
return false
}
}
return true
}
// monitorCount parses the "N:W*H" screen string the client reports. 0 means
// "not reported / not in that form".
func monitorCount(screen string) int {
i := strings.IndexByte(screen, ':')
if i <= 0 {
return 0
}
n, err := strconv.Atoi(strings.TrimSpace(screen[:i]))
if err != nil || n < 0 {
return 0
}
return n
}
+712
View File
@@ -0,0 +1,712 @@
package mcp
import (
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/auditquery"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/connection"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/devicehistory"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/hub"
)
// localFixture is the shared setup for the four local read tools: three online
// hosts (two Windows in one group, one Linux), two offline history entries, and
// a history store that is subscribed to the hub.
type localFixture struct {
srv *Server
hub *hub.Hub
hist *devicehistory.Store
}
func newLocalFixture(t *testing.T) *localFixture {
t.Helper()
h := hub.New()
hist, err := devicehistory.Open(filepath.Join(t.TempDir(), "devices.json"), 100, nil)
if err != nil {
t.Fatalf("open history: %v", err)
}
t.Cleanup(func() { _ = hist.Close() })
h.Subscribe(hist)
now := time.Now()
register := func(d hub.Device, clientType string) {
h.Register(&d, &connection.Context{
RemoteAddr: d.PeerIP + ":40000",
Info: connection.ClientInfo{ClientType: clientType},
})
}
register(hub.Device{
ID: "1001", Name: "ALPHA", Version: "1.2.3", Capability: "0005",
OS: "Windows 10", PublicIP: "10.0.0.1", PeerIP: "192.168.1.1",
Resolution: "1:1920*1080", ConnectedAt: now.Add(-3 * time.Minute),
}, "EXE")
register(hub.Device{
ID: "1002", Name: "BETA", Group: "Office", Version: "1.2.3", Capability: "0005",
OS: "Windows 11", PeerIP: "192.168.1.2",
Resolution: "2:3840*2160", ConnectedAt: now.Add(-2 * time.Minute),
}, "EXE")
register(hub.Device{
ID: "1003", Name: "GAMMA", Group: "Office", Version: "1.1.0",
OS: "Ubuntu 24.04", PublicIP: "10.1.0.3", PeerIP: "192.168.1.3",
Resolution: "1:2560*1440", ConnectedAt: now.Add(-time.Minute),
}, "LNX")
h.UpdateLive("1001", 42, "Notepad")
h.UpdateLive("1003", 120, "")
// Two devices that logged in and then left, so the history store has
// offline entries to merge into listings.
register(hub.Device{
ID: "2001", Name: "OLDWIN", Group: "Legacy", Version: "0.9.0", Capability: "0002",
OS: "Windows 7", PublicIP: "10.9.0.1", PeerIP: "192.168.9.1",
Resolution: "1:1280*1024", ConnectedAt: now.Add(-10 * time.Minute),
}, "EXE")
register(hub.Device{
ID: "2002", Name: "OLDMAC", Version: "0.8.0",
OS: "macOS 14", PublicIP: "10.9.0.2", PeerIP: "192.168.9.2",
Resolution: "1:1440*900", ConnectedAt: now.Add(-9 * time.Minute),
}, "MAC")
h.Unregister("2001")
h.Unregister("2002")
srv := New(Config{
Token: "test-token",
Hub: h,
History: hist,
Version: "v9.9.9",
StartedAt: time.Now().Add(-90 * time.Second),
Port: 6544,
Bind: "0.0.0.0",
})
return &localFixture{srv: srv, hub: h, hist: hist}
}
// callLocal drives one tools/call through the same gate the HTTP path uses and
// returns the decoded structuredContent plus the text item.
func callLocal(t *testing.T, s *Server, name, args string) (string, map[string]any, *rpcError) {
t.Helper()
params := fmt.Sprintf(`{"name":%q,"arguments":%s}`, name, args)
res, rerr := s.callTool(context.Background(), json.RawMessage(params))
if rerr != nil {
return "", nil, rerr
}
raw, err := json.Marshal(res)
if err != nil {
t.Fatalf("marshal tool result: %v", err)
}
var env struct {
Content []struct {
Type string `json:"type"`
Text string `json:"text"`
} `json:"content"`
StructuredContent map[string]any `json:"structuredContent"`
IsError bool `json:"isError"`
}
if err := json.Unmarshal(raw, &env); err != nil {
t.Fatalf("decode tool result: %v", err)
}
if env.IsError {
t.Fatalf("isError = true on success path: %s", raw)
}
if len(env.Content) != 1 || env.Content[0].Type != "text" {
t.Fatalf("content = %+v, want one text item", env.Content)
}
return env.Content[0].Text, env.StructuredContent, nil
}
func mustCallLocal(t *testing.T, s *Server, name, args string) (string, map[string]any) {
t.Helper()
text, sc, rerr := callLocal(t, s, name, args)
if rerr != nil {
t.Fatalf("%s returned error %d: %s", name, rerr.Code, rerr.Message)
}
return text, sc
}
func intField(t *testing.T, m map[string]any, key string) int {
t.Helper()
v, ok := m[key]
if !ok {
t.Fatalf("missing %q in %v", key, m)
}
f, ok := v.(float64)
if !ok {
t.Fatalf("%q = %v (%T), want number", key, v, v)
}
return int(f)
}
func boolField(t *testing.T, m map[string]any, key string) bool {
t.Helper()
v, ok := m[key]
if !ok {
t.Fatalf("missing %q in %v", key, m)
}
b, ok := v.(bool)
if !ok {
t.Fatalf("%q = %v (%T), want bool", key, v, v)
}
return b
}
func strField(t *testing.T, m map[string]any, key string) string {
t.Helper()
v, ok := m[key]
if !ok {
t.Fatalf("missing %q in %v", key, m)
}
s, ok := v.(string)
if !ok {
t.Fatalf("%q = %v (%T), want string", key, v, v)
}
return s
}
func hostList(t *testing.T, sc map[string]any) []map[string]any {
t.Helper()
raw, ok := sc["hosts"].([]any)
if !ok {
t.Fatalf("hosts = %v (%T), want array", sc["hosts"], sc["hosts"])
}
out := make([]map[string]any, 0, len(raw))
for _, item := range raw {
m, ok := item.(map[string]any)
if !ok {
t.Fatalf("host entry = %v (%T), want object", item, item)
}
out = append(out, m)
}
return out
}
func hostIDs(hosts []map[string]any) []string {
ids := make([]string, 0, len(hosts))
for _, h := range hosts {
ids = append(ids, h["id"].(string))
}
return ids
}
func wantIDs(t *testing.T, hosts []map[string]any, want ...string) {
t.Helper()
got := hostIDs(hosts)
if strings.Join(got, ",") != strings.Join(want, ",") {
t.Fatalf("ids = %v, want %v", got, want)
}
}
func TestAppendRowsSanitizesCells(t *testing.T) {
got := appendRows("head", []string{"a", "b"},
[][]string{{"x\ty", "line\nbreak"}, {"", ""}})
want := "head\na\tb\nx y\tline break\n-\t-"
if got != want {
t.Fatalf("appendRows = %q, want %q", got, want)
}
if got := appendRows("head", []string{"a"}, nil); got != "head" {
t.Fatalf("empty rows = %q, want unchanged summary", got)
}
}
func TestListHostsPoolsAndProjection(t *testing.T) {
f := newLocalFixture(t)
text, sc := mustCallLocal(t, f.srv, "list_hosts", `{}`)
hosts := hostList(t, sc)
wantIDs(t, hosts, "1001", "1002", "1003")
if got := intField(t, sc, "total"); got != 3 {
t.Fatalf("total = %d, want 3", got)
}
if got := intField(t, sc, "totalAll"); got != 3 {
t.Fatalf("totalAll = %d, want 3", got)
}
if got := intField(t, sc, "limit"); got != 100 {
t.Fatalf("limit = %d, want default 100", got)
}
if boolField(t, sc, "hasMore") {
t.Fatal("hasMore = true for a full 3-host page")
}
if !strings.Contains(text, "共 3 台主机") {
t.Fatalf("text = %q, want host count", text)
}
// Text-only MCP clients never see structuredContent, so the table in the
// text block must carry the id every follow-up call is addressed by.
if !strings.Contains(text, "id\tname\tip\tgroup\tos\tonline\tclientType\tlast_seen") {
t.Fatalf("text = %q, want host table header", text)
}
if !strings.Contains(text, "1001\tALPHA\t10.0.0.1\tdefault\tWindows 10\ttrue\tEXE\t-") {
t.Fatalf("text = %q, want ALPHA row with id first", text)
}
alpha := hosts[0]
if got := strField(t, alpha, "name"); got != "ALPHA" {
t.Fatalf("name = %q", got)
}
if got := strField(t, alpha, "group"); got != "default" {
t.Fatalf("group = %q, want normalized default", got)
}
if got := strField(t, alpha, "clientType"); got != "EXE" {
t.Fatalf("clientType = %q", got)
}
if got := strField(t, alpha, "rtt"); got != "42" {
t.Fatalf("rtt = %q, want decimal string", got)
}
if got := strField(t, alpha, "activeWindow"); got != "Notepad" {
t.Fatalf("activeWindow = %q", got)
}
if got := strField(t, alpha, "ip"); got != "10.0.0.1" {
t.Fatalf("ip = %q, want client-reported public IP", got)
}
if got := strField(t, alpha, "screen"); got != "1:1920*1080" {
t.Fatalf("screen = %q", got)
}
if _, ok := alpha["last_seen"]; ok {
t.Fatal("online host carries last_seen")
}
for _, absent := range []string{"remark", "authStatus", "tls"} {
if _, ok := alpha[absent]; ok {
t.Fatalf("%s present but the Go server has no such data", absent)
}
}
// include_offline merges history behind the online hosts.
_, sc = mustCallLocal(t, f.srv, "list_hosts", `{"include_offline":true}`)
hosts = hostList(t, sc)
wantIDs(t, hosts, "1001", "1002", "1003", "2001", "2002")
if got := intField(t, sc, "totalAll"); got != 5 {
t.Fatalf("totalAll = %d, want 5", got)
}
for _, h := range hosts[:3] {
if !boolField(t, h, "online") {
t.Fatalf("%s should be online", h["id"])
}
}
for _, h := range hosts[3:] {
if boolField(t, h, "online") {
t.Fatalf("%s should be offline", h["id"])
}
if h["last_seen"] == "" || h["last_seen"] == nil {
t.Fatalf("%s missing last_seen", h["id"])
}
}
// online=false lists offline only.
_, sc = mustCallLocal(t, f.srv, "list_hosts", `{"online":false}`)
hosts = hostList(t, sc)
wantIDs(t, hosts, "2001", "2002")
if got := intField(t, sc, "totalAll"); got != 2 {
t.Fatalf("totalAll = %d, want 2 offline hosts", got)
}
}
func TestListHostsFilters(t *testing.T) {
f := newLocalFixture(t)
cases := []struct {
name string
args string
want []string
}{
{"name substring", `{"name":"beta"}`, []string{"1002"}},
{"group substring", `{"group":"office"}`, []string{"1002", "1003"}},
{"os substring case-insensitive", `{"os":"windows"}`, []string{"1001", "1002"}},
{"client type", `{"client_type":"lnx"}`, []string{"1003"}},
{"public ip substring", `{"ip":"10.1.0"}`, []string{"1003"}},
{"peer ip fallback", `{"ip":"192.168.1.2"}`, []string{"1002"}},
{"query matches name", `{"query":"gamma"}`, []string{"1003"}},
{"query matches ip", `{"query":"10.0.0.1"}`, []string{"1001"}},
{"filters are ANDed", `{"group":"office","os":"ubuntu"}`, []string{"1003"}},
{"no match", `{"name":"zzz"}`, nil},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
text, sc := mustCallLocal(t, f.srv, "list_hosts", tc.args)
hosts := hostList(t, sc)
wantIDs(t, hosts, tc.want...)
if got := intField(t, sc, "total"); got != len(tc.want) {
t.Fatalf("total = %d, want %d (text %q)", got, len(tc.want), text)
}
// totalAll stays the unfiltered pool size.
if got := intField(t, sc, "totalAll"); got != 3 {
t.Fatalf("totalAll = %d, want 3", got)
}
})
}
// An empty result must be a JSON array, never null.
_, sc := mustCallLocal(t, f.srv, "list_hosts", `{"name":"zzz"}`)
raw, err := json.Marshal(sc)
if err != nil {
t.Fatalf("marshal: %v", err)
}
if !strings.Contains(string(raw), `"hosts":[]`) {
t.Fatalf("hosts not an empty array: %s", raw)
}
// client_type cannot match an offline record: history keeps no client type.
_, sc = mustCallLocal(t, f.srv, "list_hosts", `{"online":false,"client_type":"EXE"}`)
if hosts := hostList(t, sc); len(hosts) != 0 {
t.Fatalf("offline client_type filter matched %v, want none", hostIDs(hosts))
}
}
func TestListHostsPaging(t *testing.T) {
f := newLocalFixture(t)
_, sc := mustCallLocal(t, f.srv, "list_hosts", `{"limit":2}`)
hosts := hostList(t, sc)
wantIDs(t, hosts, "1001", "1002")
if got := intField(t, sc, "total"); got != 3 {
t.Fatalf("total = %d, want 3", got)
}
if !boolField(t, sc, "hasMore") {
t.Fatal("hasMore = false, want true")
}
_, sc = mustCallLocal(t, f.srv, "list_hosts", `{"limit":2,"offset":2}`)
hosts = hostList(t, sc)
wantIDs(t, hosts, "1003")
if boolField(t, sc, "hasMore") {
t.Fatal("hasMore = true on the last page")
}
if got := intField(t, sc, "offset"); got != 2 {
t.Fatalf("offset = %d, want 2", got)
}
text, sc := mustCallLocal(t, f.srv, "list_hosts", `{"offset":99}`)
if hosts := hostList(t, sc); len(hosts) != 0 {
t.Fatalf("offset past end returned %v", hostIDs(hosts))
}
if !strings.Contains(text, "offset 超出范围") {
t.Fatalf("text = %q, want out-of-range note", text)
}
_, sc = mustCallLocal(t, f.srv, "list_hosts", `{"limit":5000}`)
if got := intField(t, sc, "limit"); got != listMaxLimit {
t.Fatalf("limit = %d, want clamped to %d", got, listMaxLimit)
}
_, sc = mustCallLocal(t, f.srv, "list_hosts", `{"limit":-5}`)
if got := intField(t, sc, "limit"); got != listDefaultLimit {
t.Fatalf("limit = %d, want default %d", got, listDefaultLimit)
}
// Malformed arguments are a caller error, not an empty list.
if _, _, rerr := callLocal(t, f.srv, "list_hosts", `{"limit":"many"}`); rerr == nil || rerr.Code != CodeInvalidParams {
t.Fatalf("malformed limit error = %+v, want -32602", rerr)
}
}
func TestGetHostDetailOnlineAndOffline(t *testing.T) {
f := newLocalFixture(t)
text, sc := mustCallLocal(t, f.srv, "get_host_detail", `{"id":"1001"}`)
if !strings.Contains(text, "\n") || !strings.Contains(text, `"id":"1001"`) ||
!strings.Contains(text, `"name":"ALPHA"`) {
t.Fatalf("text = %q, want summary plus host JSON", text)
}
host, ok := sc["host"].(map[string]any)
if !ok {
t.Fatalf("host = %v", sc["host"])
}
if !boolField(t, host, "online") {
t.Fatal("1001 should be online")
}
caps, ok := host["capabilities"].(map[string]any)
if !ok {
t.Fatalf("capabilities = %v", host["capabilities"])
}
if !boolField(t, caps, "screenPreview") || !boolField(t, caps, "fileTransferV2") {
t.Fatalf("caps = %v, want preview+V2 from 0x0005", caps)
}
if boolField(t, caps, "screenRegion") {
t.Fatalf("caps = %v, screenRegion set without 0x0200", caps)
}
if !boolField(t, caps, "registry") {
t.Fatalf("caps = %v, Windows client must have registry", caps)
}
if !boolField(t, caps, "remoteControl") {
t.Fatalf("caps = %v, single-monitor Windows must allow remote control", caps)
}
if got := strField(t, caps, "platform"); got != "EXE" {
t.Fatalf("platform = %q", got)
}
if _, ok := caps["v2"]; ok {
t.Fatal("v2 must not be reported: every platform sets it")
}
// A multi-monitor Windows client without whole-desktop capture is not
// remotely controllable (coordinate spaces would not line up).
f.hub.Register(&hub.Device{
ID: "1004", Name: "DUAL", Capability: "0005",
OS: "Windows 11", PublicIP: "10.0.0.4", PeerIP: "192.168.1.4",
Resolution: "2:3840*2160", ConnectedAt: time.Now(),
}, &connection.Context{RemoteAddr: "192.168.1.4:40000",
Info: connection.ClientInfo{ClientType: "EXE"}})
_, sc = mustCallLocal(t, f.srv, "get_host_detail", `{"id":"1004"}`)
caps = sc["host"].(map[string]any)["capabilities"].(map[string]any)
if boolField(t, caps, "remoteControl") {
t.Fatalf("caps = %v, dual-monitor without VIRTUAL_DESKTOP must not allow remote control", caps)
}
// Offline detail comes from history: no capabilities (the device is gone),
// but the last-known fields are intact.
_, sc = mustCallLocal(t, f.srv, "get_host_detail", `{"id":"2001"}`)
host = sc["host"].(map[string]any)
if boolField(t, host, "online") {
t.Fatal("2001 should be offline")
}
if got := strField(t, host, "version"); got != "0.9.0" {
t.Fatalf("version = %q", got)
}
if _, ok := host["capabilities"]; ok {
t.Fatal("offline host must not report capabilities")
}
if _, _, rerr := callLocal(t, f.srv, "get_host_detail", `{"id":"9999"}`); rerr == nil || rerr.Code != CodeOffline {
t.Fatalf("unknown host error = %+v, want -32002", rerr)
}
if _, _, rerr := callLocal(t, f.srv, "get_host_detail", `{"id":"12ab"}`); rerr == nil || rerr.Code != CodeInvalidParams {
t.Fatalf("non-decimal id error = %+v, want -32602", rerr)
}
if _, _, rerr := callLocal(t, f.srv, "get_host_detail", `{}`); rerr == nil || rerr.Code != CodeInvalidParams {
t.Fatalf("missing id error = %+v, want -32602", rerr)
}
}
func TestGetHostDetailBatch(t *testing.T) {
f := newLocalFixture(t)
text, sc := mustCallLocal(t, f.srv, "get_host_detail", `{"ids":["1001","9999","2001"]}`)
if !strings.Contains(text, "id\tok\tdetail") ||
!strings.Contains(text, "1001\ttrue\t{") ||
!strings.Contains(text, "9999\tfalse\t") {
t.Fatalf("text = %q, want one row per id", text)
}
if got := strField(t, sc, "tool"); got != "get_host_detail" {
t.Fatalf("tool = %q", got)
}
if got := intField(t, sc, "total"); got != 3 {
t.Fatalf("total = %d, want 3", got)
}
if got := intField(t, sc, "succeeded"); got != 2 {
t.Fatalf("succeeded = %d, want 2", got)
}
if got := intField(t, sc, "failed"); got != 1 {
t.Fatalf("failed = %d, want 1", got)
}
if got := intField(t, sc, "skipped"); got != 0 {
t.Fatalf("skipped = %d, want 0", got)
}
results, ok := sc["results"].([]any)
if !ok || len(results) != 3 {
t.Fatalf("results = %v", sc["results"])
}
first := results[0].(map[string]any)
if !boolField(t, first, "ok") {
t.Fatal("first result should be ok")
}
data := first["data"].(map[string]any)
if id := strField(t, data["host"].(map[string]any), "id"); id != "1001" {
t.Fatalf("first host id = %q", id)
}
second := results[1].(map[string]any)
if boolField(t, second, "ok") {
t.Fatal("second result should fail")
}
errObj := second["error"].(map[string]any)
if got := intField(t, errObj, "code"); got != CodeOffline {
t.Fatalf("per-entry code = %d, want %d", got, CodeOffline)
}
third := results[2].(map[string]any)
if !boolField(t, third, "ok") {
t.Fatal("offline history entry should succeed in a batch")
}
ids := make([]string, batchMaxIDs+1)
for i := range ids {
ids[i] = "1001"
}
payload, _ := json.Marshal(map[string]any{"ids": ids})
if _, _, rerr := callLocal(t, f.srv, "get_host_detail", string(payload)); rerr == nil || rerr.Code != CodeInvalidParams {
t.Fatalf("oversized batch error = %+v, want -32602", rerr)
}
}
func TestGetServerStatus(t *testing.T) {
f := newLocalFixture(t)
_, sc := mustCallLocal(t, f.srv, "get_server_status", `{}`)
if got := strField(t, sc, "version"); got != "v9.9.9" {
t.Fatalf("version = %q", got)
}
// StartedAt is 90s in the past; the exact value depends on test runtime.
if got := intField(t, sc, "uptime_sec"); got < 90 {
t.Fatalf("uptime_sec = %d, want >= 90", got)
}
hosts, ok := sc["hosts"].(map[string]any)
if !ok {
t.Fatalf("hosts = %v", sc["hosts"])
}
if got := intField(t, hosts, "online"); got != 3 {
t.Fatalf("online = %d, want 3", got)
}
if got := intField(t, hosts, "offline"); got != 2 {
t.Fatalf("offline = %d, want 2", got)
}
if got := intField(t, sc, "port"); got != 6544 {
t.Fatalf("port = %d", got)
}
if got := strField(t, sc, "bind"); got != "0.0.0.0" {
t.Fatalf("bind = %q", got)
}
if _, ok := sc["sessions"]; ok {
t.Fatal("sessions reported before the MCP session table exists")
}
}
// A build without link-time version injection must not invent one: the status
// tool reports the empty string, and only initialize substitutes "dev".
func TestUnversionedBuild(t *testing.T) {
s := New(Config{Token: "test-token"})
_, sc := mustCallLocal(t, s, "get_server_status", `{}`)
if got, ok := sc["version"]; !ok || got != "" {
t.Fatalf("status version = %#v, want empty string", got)
}
if got := s.initializeResult().ServerInfo.Version; got != "dev" {
t.Fatalf("initialize version = %q, want dev", got)
}
}
func writeAuditFile(t *testing.T, lines ...string) string {
t.Helper()
path := filepath.Join(t.TempDir(), "audit.log")
body := strings.Join(lines, "\n") + "\n"
if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
t.Fatalf("write audit file: %v", err)
}
return path
}
func TestGetAuditLog(t *testing.T) {
path := writeAuditFile(t,
`{"audit":true,"time":"2026-11-12T10:00:00Z","level":"info","event":"web.login.success","actor":"admin","ip":"1.2.3.4"}`,
`{"audit":true,"time":"2026-11-12T10:01:00Z","level":"info","event":"web.login.failure","actor":"bob","ip":"5.6.7.8"}`,
`{"audit":true,"time":"2026-11-12T10:02:00Z","level":"warn","event":"authz.denied","actor":"admin","ip":"1.2.3.4","detail":"readonly"}`,
`{"audit":true,"time":"2026-11-12T10:03:00Z","level":"info","event":"device.online","device_id":"1001"}`,
)
s := New(Config{Token: "test-token", AuditPath: path})
text, sc := mustCallLocal(t, s, "get_audit_log", `{}`)
if !strings.Contains(text, "time\ttype\tmsg") ||
!strings.Contains(text, "2026-11-12T10:03:00Z\tdevice.online\t") {
t.Fatalf("text = %q, want audit rows", text)
}
entries, ok := sc["entries"].([]any)
if !ok || len(entries) != 4 {
t.Fatalf("entries = %v, want 4", sc["entries"])
}
if got := intField(t, sc, "total"); got != 4 {
t.Fatalf("total = %d, want 4", got)
}
if got := intField(t, sc, "totalAll"); got != 4 {
t.Fatalf("totalAll = %d, want 4", got)
}
if boolField(t, sc, "hasMore") {
t.Fatal("hasMore = true for a complete page")
}
newest := entries[0].(map[string]any)
if got := strField(t, newest, "type"); got != "device.online" {
t.Fatalf("newest type = %q, want newest first", got)
}
if got := strField(t, newest, "time"); got != "2026-11-12T10:03:00Z" {
t.Fatalf("newest time = %q", got)
}
msg := strField(t, newest, "msg")
if !strings.Contains(msg, `"device_id":"1001"`) {
t.Fatalf("msg = %q, want remaining fields", msg)
}
for _, envelope := range []string{`"audit"`, `"event"`, `"level"`, `"time"`} {
if strings.Contains(msg, envelope) {
t.Fatalf("msg repeats envelope key %s: %s", envelope, msg)
}
}
// type is a case-insensitive substring of the event name.
_, sc = mustCallLocal(t, s, "get_audit_log", `{"type":"LOGIN"}`)
if got := intField(t, sc, "total"); got != 2 {
t.Fatalf("login total = %d, want 2", got)
}
if got := intField(t, sc, "totalAll"); got != 4 {
t.Fatalf("login totalAll = %d, want unfiltered 4", got)
}
_, sc = mustCallLocal(t, s, "get_audit_log", `{"type":"login","keyword":"1.2.3.4"}`)
if got := intField(t, sc, "total"); got != 1 {
t.Fatalf("type+keyword total = %d, want 1", got)
}
// Paging: limit 2 → hasMore; the tail page stops there.
_, sc = mustCallLocal(t, s, "get_audit_log", `{"limit":2}`)
if got := len(sc["entries"].([]any)); got != 2 {
t.Fatalf("entries = %d, want 2", got)
}
if !boolField(t, sc, "hasMore") {
t.Fatal("hasMore = false with 2 of 4")
}
_, sc = mustCallLocal(t, s, "get_audit_log", `{"limit":2,"offset":3}`)
if got := len(sc["entries"].([]any)); got != 1 {
t.Fatalf("tail entries = %d, want 1", got)
}
if boolField(t, sc, "hasMore") {
t.Fatal("hasMore = true on the tail page")
}
// Empty result is an array, and the file is scanned only up to its size.
_, sc = mustCallLocal(t, s, "get_audit_log", `{"keyword":"no-such-thing"}`)
raw, _ := json.Marshal(sc)
if !strings.Contains(string(raw), `"entries":[]`) {
t.Fatalf("entries not an empty array: %s", raw)
}
// Missing file: an empty log, not an error.
f := newLocalFixture(t)
f.srv.cfg.AuditPath = filepath.Join(t.TempDir(), "missing.log")
if _, sc = mustCallLocal(t, f.srv, "get_audit_log", `{}`); intField(t, sc, "total") != 0 {
t.Fatalf("missing file total = %d, want 0", intField(t, sc, "total"))
}
// Disabled audit file (YAMA_AUDIT_LOG=off) is a configuration error.
off := New(Config{Token: "test-token"})
if _, _, rerr := callLocal(t, off, "get_audit_log", `{}`); rerr == nil || rerr.Code != CodeInternal {
t.Fatalf("disabled audit error = %+v, want -32000", rerr)
}
// Offset is clamped at auditquery.MaxOffset. A page that ends exactly
// there must not advertise a next page: the follow-up offset would be
// clamped back and return the same records forever.
var big strings.Builder
for i := range auditquery.MaxOffset + 2000 {
fmt.Fprintf(&big, `{"audit":true,"time":"2026-11-12T10:00:00Z","level":"info","event":"device.online","n":%d}`+"\n", i)
}
bigPath := filepath.Join(t.TempDir(), "audit.log")
if err := os.WriteFile(bigPath, []byte(big.String()), 0o600); err != nil {
t.Fatalf("write big audit file: %v", err)
}
bigSrv := New(Config{Token: "test-token", AuditPath: bigPath})
_, sc = mustCallLocal(t, bigSrv, "get_audit_log", `{"limit":500}`)
if !boolField(t, sc, "hasMore") {
t.Fatal("hasMore = false on the first page of a large log")
}
_, sc = mustCallLocal(t, bigSrv, "get_audit_log", `{"limit":500,"offset":9500}`)
if got := len(sc["entries"].([]any)); got != 500 {
t.Fatalf("entries at cap = %d, want 500", got)
}
if boolField(t, sc, "hasMore") {
t.Fatal("hasMore = true at the MaxOffset cap, paging would loop")
}
}
+979
View File
@@ -0,0 +1,979 @@
[
{
"name": "list_hosts",
"description": "列主机:默认只返回在线主机(含计算机名、IP、操作系统、版本、备注、分组、活动窗口、延迟等实时信息),include_offline=true 时连离线主机(历史连接过、当前未连接,来自主机列表记录)一起返回,在线主机排在最前面。query 子串匹配计算机名/备注/IP;group / os / client_type 为附加过滤条件(均可选、AND 组合、子串匹配、ASCII 不区分大小写);online=false 只看离线主机。过滤在分页之前生效:total 为命中台数,totalAll 为过滤前的主机库台数。结果按 limit/offset 分页(默认 100 条,上限 1000),hasMore 表示还有下一页。离线主机另有 last_seen(最后一次登录时间)、install_time 字段,但没有 rtt/version/activeWindow 等实时字段,也没有 clientType(按平台筛历史主机请用 os),group 恒为 default。authStatus 为主机授权状态(unauthorized/authorized_by_super/authorized_by_admin/forbidden)。tls=true 表示该客户端登录时使用了 TLS 加密传输(登录时上报,老客户端恒为 false)。",
"inputSchema": {
"properties": {
"client_type": {
"description": "按客户端类型过滤(子串,不区分大小写,如 EXE、LNX、MAC)。离线主机没有该字段,不会命中。省略则不过滤。",
"type": "string"
},
"group": {
"description": "按分组过滤(子串,不区分大小写)。省略则不过滤。",
"type": "string"
},
"include_offline": {
"description": "是否把离线主机一起返回,默认 false(只给在线);online=false 时无意义。list_all_hosts 别名默认 true。",
"type": "boolean"
},
"ip": {
"description": "只按 IP 过滤(search_hosts 的旧参数);与 query 同时给出时两者都需满足。",
"type": "string"
},
"limit": {
"description": "本次最多返回的条数,默认 100,上限 1000。",
"type": "integer"
},
"name": {
"description": "只按计算机名/备注过滤(search_hosts 的旧参数);与 query 同时给出时两者都需满足。",
"type": "string"
},
"offset": {
"description": "跳过前 N 条,默认 0;配合返回的 total/hasMore 翻页。",
"type": "integer"
},
"online": {
"description": "true(默认)返回在线主机;false 只返回离线主机(历史连接过、当前未连接)。",
"type": "boolean"
},
"os": {
"description": "按操作系统过滤(子串,不区分大小写,如 Windows、Linux、Android)。省略则不过滤。",
"type": "string"
},
"query": {
"description": "关键字:子串匹配计算机名、备注或 IP(ASCII 不区分大小写)。省略则不过滤。",
"type": "string"
}
},
"type": "object"
},
"outputSchema": {
"properties": {
"hasMore": {
"type": "boolean"
},
"hosts": {
"items": {
"properties": {
"activeWindow": {
"type": "string"
},
"authStatus": {
"type": "string"
},
"clientType": {
"type": "string"
},
"group": {
"type": "string"
},
"id": {
"type": "string"
},
"install_time": {
"type": "string"
},
"ip": {
"type": "string"
},
"last_seen": {
"type": "string"
},
"location": {
"type": "string"
},
"name": {
"type": "string"
},
"online": {
"type": "boolean"
},
"os": {
"type": "string"
},
"remark": {
"type": "string"
},
"rtt": {
"type": "string"
},
"screen": {
"type": "string"
},
"tls": {
"type": "boolean"
},
"version": {
"type": "string"
}
},
"type": "object"
},
"type": "array"
},
"limit": {
"type": "integer"
},
"offset": {
"type": "integer"
},
"total": {
"type": "integer"
},
"totalAll": {
"type": "integer"
}
},
"required": [
"hosts"
],
"type": "object"
}
},
{
"name": "get_host_detail",
"description": "获取单台在线主机的详细信息(id、计算机名、IP、操作系统、备注、分组、活动窗口、屏幕分辨率、客户端类型等)。tls=true 表示该客户端登录时使用了 TLS 加密传输(登录时上报,老客户端恒为 false)。",
"inputSchema": {
"anyOf": [
{
"required": [
"id"
]
},
{
"required": [
"ids"
]
}
],
"properties": {
"id": {
"description": "主机 id,取 list_hosts 返回的 id 字段;与 ids 二选一",
"type": "string"
},
"ids": {
"description": "批量查询:一次传多台主机 id(最多 50 个),结果按台汇总在 results 里。与 id 二选一,仅只读工具支持;limit/offset 对每台主机各自生效。",
"items": {
"type": "string"
},
"type": "array"
}
},
"type": "object"
},
"outputSchema": {
"anyOf": [
{
"properties": {
"host": {
"properties": {
"activeWindow": {
"type": "string"
},
"authStatus": {
"type": "string"
},
"capabilities": {
"properties": {
"c2cPaths": {
"description": "能否按路径清单接收另一台主机的文件(copy_files_c2c 源端的前提)",
"type": "boolean"
},
"fileTransferV2": {
"description": "是否支持 V2 文件传输(download_file / upload_file 的前提)",
"type": "boolean"
},
"platform": {
"description": "客户端形态:EXE/DLL/MEXE/SC/MDLL(Windows)、LNX(Linux)、MAC、APK",
"type": "string"
},
"registry": {
"description": "是否有 Windows 注册表可查(list_registry);仅 Windows 客户端为 true",
"type": "boolean"
},
"remoteControl": {
"description": "能否建立远程控制会话(remote_open/remote_mouse/remote_keyboard 的前提);Android 客户端只支持整屏目标,且需要已授权录屏与无障碍服务;还要求服务端 Web 远程服务已启动(WebSvrPort>0)",
"type": "boolean"
},
"screenPreview": {
"description": "能否截屏(get_screenshot 的前提)",
"type": "boolean"
},
"screenRegion": {
"description": "能否按区域/窗口/显示器原生分辨率截屏(get_screenshot 的 mode=region/window/monitor 前提);仅声明 CLIENT_CAP_SCREEN_REGION 的新 Windows 客户端为 true",
"type": "boolean"
},
"windowInfo": {
"description": "是否支持窗口信息(get_foreground_window、host_inspect 的 windows 项坐标/前后台字段、operate_window/host_control_window 的 activate);仅声明 CLIENT_CAP_WINDOW_INFO 的新客户端为 true",
"type": "boolean"
}
},
"type": "object"
},
"clientType": {
"type": "string"
},
"group": {
"type": "string"
},
"id": {
"type": "string"
},
"install_time": {
"type": "string"
},
"ip": {
"type": "string"
},
"last_seen": {
"type": "string"
},
"location": {
"type": "string"
},
"name": {
"type": "string"
},
"online": {
"type": "boolean"
},
"os": {
"type": "string"
},
"remark": {
"type": "string"
},
"rtt": {
"type": "string"
},
"screen": {
"type": "string"
},
"tls": {
"type": "boolean"
},
"version": {
"type": "string"
}
},
"type": "object"
}
},
"required": [
"host"
],
"type": "object"
},
{
"properties": {
"failed": {
"description": "失败的台数",
"type": "integer"
},
"results": {
"items": {
"properties": {
"data": {
"description": "该台成功时的单机 structuredContent(字段随工具而定)",
"type": "object"
},
"error": {
"description": "该台失败时的错误对象(code / message)",
"type": "object"
},
"id": {
"description": "主机 id",
"type": "string"
},
"ok": {
"description": "该台是否成功",
"type": "boolean"
},
"text": {
"description": "该台失败时的错误文字",
"type": "string"
}
},
"type": "object"
},
"type": "array"
},
"skipped": {
"description": "因整体时限用尽而未下发的台数(不是主机侧错误)",
"type": "integer"
},
"succeeded": {
"description": "成功的台数",
"type": "integer"
},
"tool": {
"description": "被批量调用的工具名",
"type": "string"
},
"total": {
"description": "请求里的 id 台数",
"type": "integer"
}
},
"required": [
"results"
],
"type": "object"
}
],
"type": "object"
}
},
{
"name": "get_screenshot",
"description": "截取指定在线主机的一帧画面,返回 base64 编码的 JPEG 图片:图片在 content 的 image 块(data 为 base64,mimeType=image/jpeg);structuredContent.image 只有 mimeType/width/height/bytes 元数据,不含图片数据。支持 Windows 与带 X11 桌面的 Linux 客户端(能力位 CLIENT_CAP_SCREEN_PREVIEW),主连接 RPC、一次性返回。Android 客户端用无障碍服务 takeScreenshot 抓屏(Android 11+ 且开启无障碍服务,此时登录会声明该能力位;只支持 mode=screen)。mode 可选 screen(默认,整虚拟桌面)/region(指定矩形)/window(指定 hwnd)/monitor(指定显示器);后三种默认按源尺寸 1:1 原生分辨率抓取(适合 OCR/视觉读字),需要较新的 Windows 客户端(CLIENT_CAP_SCREEN_REGION,否则 -32005),结果在 structuredContent.capture 里回报实际源矩形与缩放比例。",
"inputSchema": {
"allOf": [
{
"if": {
"properties": {
"mode": {
"enum": [
"region"
]
}
},
"required": [
"mode"
]
},
"then": {
"required": [
"width",
"height"
]
}
},
{
"if": {
"properties": {
"mode": {
"enum": [
"window"
]
}
},
"required": [
"mode"
]
},
"then": {
"required": [
"hwnd"
]
}
}
],
"properties": {
"height": {
"description": "region 模式必填:矩形高度(像素,1~8192)。超出虚拟桌面的部分会被裁剪。",
"type": "integer"
},
"hwnd": {
"description": "window 模式必填:窗口句柄(整数或 0x 前缀字符串),取 host_inspect 的 windows 项 / get_foreground_window 返回的 hwnd。窗口最小化时无法抓取(返回错误),先 activate/restore。",
"type": [
"integer",
"string"
]
},
"id": {
"description": "主机 id,取 list_hosts 返回的 id 字段",
"type": "string"
},
"max_width": {
"description": "期望图片最大宽度(像素,钳制到 64~1920)。screen 模式省略或传 0 时沿用 RTT 自适应缩略图档位(最大 1024);region/window/monitor 模式省略/传 0 时按源尺寸 1:1 抓取(原生分辨率),显式传入才等比缩小。",
"type": "integer"
},
"mode": {
"description": "抓取范围,默认 screen。screen=整个虚拟桌面(可缩放);region=指定矩形;window=指定窗口;monitor=指定显示器。region/window/monitor 默认按源尺寸 1:1 抓取(原生分辨率,适合 OCR/视觉读字),只有显式传 max_width 才缩放;这三种需要较新的 Windows 客户端(能力位 CLIENT_CAP_SCREEN_REGION),否则返回 -32005。",
"enum": [
"screen",
"region",
"window",
"monitor"
],
"type": "string"
},
"monitor": {
"description": "monitor 模式:显示器序号,0=主显示器(默认),1..N 为其余显示器(按系统枚举顺序)。序号越界返回错误。",
"type": "integer"
},
"width": {
"description": "region 模式必填:矩形宽度(像素,1~8192)。超出虚拟桌面的部分会被裁剪。",
"type": "integer"
},
"x": {
"description": "region 模式:矩形左上角的虚拟桌面 X 坐标(可为负;多显示器时以虚拟桌面左上角为原点)。省略按 0 处理。",
"type": "integer"
},
"y": {
"description": "region 模式:矩形左上角的虚拟桌面 Y 坐标(可为负)。省略按 0 处理。",
"type": "integer"
}
},
"required": [
"id"
],
"type": "object"
},
"outputSchema": {
"properties": {
"capture": {
"properties": {
"height": {
"type": "integer"
},
"mode": {
"type": "string"
},
"native": {
"type": "boolean"
},
"scale": {
"type": "integer"
},
"width": {
"type": "integer"
},
"x": {
"type": "integer"
},
"y": {
"type": "integer"
}
},
"type": "object"
},
"image": {
"properties": {
"bytes": {
"type": "integer"
},
"height": {
"type": "integer"
},
"mimeType": {
"type": "string"
},
"width": {
"type": "integer"
}
},
"type": "object"
}
},
"required": [
"image"
],
"type": "object"
}
},
{
"name": "list_files",
"description": "列举指定在线主机的目录。省略或空 path 返回驱动器列表(drives);给定 path 返回该目录一层内的文件/子目录(files,含 name/isDir/size/mtime),整目录解析后按 limit/offset 分页(默认 100 条、上限 1000 条,total/hasMore 是真实的目录条目数;目录超过 10 万条时按上限截断并返回 truncated=true)。Windows 上 \".\"/\"/\"/\"\\\\\" 视同省略 path;Linux/macOS 上 \"/\" 是根目录。只读。",
"inputSchema": {
"anyOf": [
{
"required": [
"id"
]
},
{
"required": [
"ids"
]
}
],
"properties": {
"id": {
"description": "主机 id,取 list_hosts 返回的 id 字段",
"type": "string"
},
"ids": {
"description": "批量查询:一次传多台主机 id(最多 50 个),结果按台汇总在 results 里。与 id 二选一,仅只读工具支持;limit/offset 对每台主机各自生效。",
"items": {
"type": "string"
},
"type": "array"
},
"limit": {
"description": "本次最多返回的条数,默认 100,上限 1000。",
"type": "integer"
},
"offset": {
"description": "跳过前 N 条,默认 0;配合返回的 total/hasMore 翻页。",
"type": "integer"
},
"path": {
"description": "要列举的目录路径(如 C:\\Windows 或 /etc)。省略或传空返回驱动器列表;Windows 上 \".\"、\"/\"、\"\\\\\" 视同省略;Linux/macOS 上 \"/\" 是根目录,按真实目录列举。",
"type": "string"
}
},
"type": "object"
},
"outputSchema": {
"anyOf": [
{
"properties": {
"drives": {
"items": {
"properties": {
"drive": {
"type": "string"
},
"fileSystem": {
"type": "string"
},
"freeMB": {
"type": "integer"
},
"totalMB": {
"type": "integer"
},
"type": {
"type": "integer"
},
"typeName": {
"type": "string"
}
},
"type": "object"
},
"type": "array"
},
"files": {
"items": {
"properties": {
"isDir": {
"type": "boolean"
},
"mtime": {
"type": "integer"
},
"name": {
"type": "string"
},
"size": {
"type": "integer"
}
},
"type": "object"
},
"type": "array"
},
"hasMore": {
"type": "boolean"
},
"limit": {
"type": "integer"
},
"offset": {
"type": "integer"
},
"total": {
"type": "integer"
},
"totalAll": {
"type": "integer"
},
"truncated": {
"description": "目录条目超过服务端解析上限(100000 条)时为 true;仅在返回 files 时可能出现,此时 total 不是真实总数。",
"type": "boolean"
}
},
"type": "object"
},
{
"properties": {
"failed": {
"description": "失败的台数",
"type": "integer"
},
"results": {
"items": {
"properties": {
"data": {
"description": "该台成功时的单机 structuredContent(字段随工具而定)",
"type": "object"
},
"error": {
"description": "该台失败时的错误对象(code / message)",
"type": "object"
},
"id": {
"description": "主机 id",
"type": "string"
},
"ok": {
"description": "该台是否成功",
"type": "boolean"
},
"text": {
"description": "该台失败时的错误文字",
"type": "string"
}
},
"type": "object"
},
"type": "array"
},
"skipped": {
"description": "因整体时限用尽而未下发的台数(不是主机侧错误)",
"type": "integer"
},
"succeeded": {
"description": "成功的台数",
"type": "integer"
},
"tool": {
"description": "被批量调用的工具名",
"type": "string"
},
"total": {
"description": "请求里的 id 台数",
"type": "integer"
}
},
"required": [
"results"
],
"type": "object"
}
],
"type": "object"
}
},
{
"name": "get_audit_log",
"description": "获取 YAMA 服务端主界面的消息/审计日志(主机上线/下线、操作结果、告警等),按 limit/offset 分页(新在前,服务端只保留最近 1000 条)。可选 type 按类型列做不区分大小写的子串过滤(如 MCP、主机),keyword 按正文字串过滤;过滤在分页之前生效,total 为命中条数、totalAll 为镜像里的全部条数。只读、纯内存。",
"inputSchema": {
"properties": {
"keyword": {
"description": "正文子串过滤,不区分大小写(如 445、timeout)。省略则不过滤。",
"type": "string"
},
"limit": {
"description": "本次最多返回的条数,默认 100,上限 1000。",
"type": "integer"
},
"offset": {
"description": "跳过前 N 条,默认 0;配合返回的 total/hasMore 翻页。",
"type": "integer"
},
"type": {
"description": "类型列的子串过滤,不区分大小写(如 MCP、主机上线)。省略则不过滤。",
"type": "string"
}
},
"required": [],
"type": "object"
},
"outputSchema": {
"properties": {
"entries": {
"items": {
"properties": {
"msg": {
"type": "string"
},
"time": {
"type": "string"
},
"type": {
"type": "string"
}
},
"type": "object"
},
"type": "array"
},
"hasMore": {
"type": "boolean"
},
"limit": {
"type": "integer"
},
"offset": {
"type": "integer"
},
"total": {
"type": "integer"
},
"totalAll": {
"type": "integer"
}
},
"required": [
"entries"
],
"type": "object"
}
},
{
"name": "get_server_status",
"description": "获取 YAMA 服务端自身的状态:程序版本与 exe 构建时间、进程已运行秒数、MCP 监听地址与端口、各功能开关(只读/终端/远程控制/文件传输/管理/主机管理/高风险操作/键盘记录/远程交谈)、在线与离线主机数、各类在飞会话数、当前被封禁的来源 IP 数。只读、纯内存,不返回 token。",
"inputSchema": {
"properties": {},
"required": [],
"type": "object"
},
"outputSchema": {
"properties": {
"app_name": {
"type": "string"
},
"bind": {
"type": "string"
},
"blocked_auth_ips": {
"type": "integer"
},
"exe_build_time": {
"type": "string"
},
"hosts": {
"type": "object"
},
"port": {
"type": "integer"
},
"sessions": {
"type": "object"
},
"switches": {
"type": "object"
},
"uptime_sec": {
"type": "integer"
},
"version": {
"type": "string"
}
},
"required": [],
"type": "object"
}
},
{
"name": "terminal_exec",
"description": "在已打开的持久会话中执行一条命令,或轮询取回正在运行的命令输出。带 command 时执行并在 timeout_ms 内等待;等待超时返回 done:false 与已产生的部分输出,会话不销毁(命令仍在远端运行)。session_id 可省略:自动复用该主机已有的持久会话,没有就隐式打开一个(结果里有 session_id 与 reused),不必先 terminal_open。不带 command、只传 session_id 时进入轮询模式:继续等待并取回增量输出,直到 done:true(此时有 exit_code)。命令不受白名单约束。PTY 会话(新 Windows 客户端 ConPTY / Linux 与新版 Android 的 POSIX PTY)下可用管道 | 与 && / || 串联,退出码取整条管道/串联,适合「ls -1 | wc -l」这类先过滤再回传的用法;不要用后台执行符 &(POSIX)或换行。老非 PTY Windows 客户端仍不支持 & 与 |,请拆成多条调用。",
"inputSchema": {
"anyOf": [
{
"required": [
"command"
]
},
{
"required": [
"session_id"
]
}
],
"properties": {
"command": {
"description": "要执行的命令(完整 shell,不受白名单约束)。省略时进入轮询模式:不执行新命令,只等待并取回当前会话的增量输出(上一条命令超时后用这个方式继续取)。PTY 会话(Windows ConPTY / Linux PTY)下可用管道 | 与 && / || 串联,退出码取整条管道/串联;不要用后台执行符 &(POSIX)或换行。老非 PTY 客户端仍不支持 & 与 |,请拆成多条调用。Linux 下通过 POSIX shell 执行,可用 ; 串联且退出码取最后一条命令",
"type": "string"
},
"id": {
"description": "主机 id,取 list_hosts 返回的 id 字段",
"type": "string"
},
"max_output_bytes": {
"description": "单次返回的原始输出上限(可选,默认 65536,最小 1024,最大 1048576);超出按换行边界截断并置 truncated:true,再轮询一次可取回剩余",
"type": "integer"
},
"session_id": {
"description": "会话 token。带 command 时可省略:自动复用该主机已有的持久会话,没有就在内部打开一个(结果里有 session_id 与 reused)。轮询模式必须提供",
"type": "string"
},
"timeout_ms": {
"description": "本次调用最多等待的毫秒数(可选,默认 20000,上限 600000)。等待超时不算失败:返回 done:false 与已产生的输出,命令仍在远端运行,继续轮询即可",
"type": "integer"
}
},
"required": [
"id"
],
"type": "object"
},
"outputSchema": {
"properties": {
"done": {
"description": "false=命令仍在运行,用同一工具只传 session_id 继续取增量;true=命令已结束,exit_code 有效",
"type": "boolean"
},
"dropped_bytes": {
"description": "因单条命令输出超过 8MB 上限被丢弃的最旧字节数(该命令累计,0 或省略=无丢失)",
"type": "integer"
},
"elapsed_ms": {
"description": "本次调用实际等待的毫秒数",
"type": "integer"
},
"exit_code": {
"description": "退出码(done=true 时提供):PTY 客户端(Windows ConPTY / Linux PTY)为命令的真实退出码;老客户端(非 PTY)仅区分 0/非 0;-1=未知(shell 进程退出)",
"type": "integer"
},
"is_pty": {
"description": "true=PTY(UTF-8)(Windows ConPTY / Linux PTY);false=老 cmd 管道(GBK)",
"type": "boolean"
},
"reused": {
"description": "true=复用了该主机已有的持久会话;false=本次隐式新建(省略 session_id 时)",
"type": "boolean"
},
"session_id": {
"description": "会话 token,原样回传,便于续接轮询",
"type": "string"
},
"stdout": {
"description": "本次新增的输出(已剥哨兵与 ANSI 转义)",
"type": "string"
},
"truncated": {
"description": "true=本次受 max_output_bytes 限制仍有剩余输出,立即再轮询即可取回",
"type": "boolean"
}
},
"required": [
"stdout",
"done",
"session_id"
],
"type": "object"
}
},
{
"name": "terminal_close",
"description": "关闭并释放指定持久会话(幂等:会话已不存在也返回成功)。",
"inputSchema": {
"properties": {
"id": {
"description": "主机 id,取 list_hosts 返回的 id 字段",
"type": "string"
},
"session_id": {
"description": "terminal_open 返回的 session_id",
"type": "string"
}
},
"required": [
"id",
"session_id"
],
"type": "object"
},
"outputSchema": {
"properties": {
"closed": {
"description": "恒为 true(关闭幂等)",
"type": "boolean"
}
},
"required": [
"closed"
],
"type": "object"
}
},
{
"name": "read_file",
"description": "按字节读取指定在线主机上的一个文本文件(分页 + 编码识别 + 整文件 SHA-256),只支持单个普通文件。path 为远程绝对路径:Windows 用 D:\\cfg\\app.ini 这类盘符路径,Linux/macOS 用 /etc/app.conf 这类 POSIX 路径。offset 支持负数(-200 = 最后 200 行,看日志尾部);limit 为最多返回的行数(默认 2000);encoding=auto 时按 BOM → UTF-8 合法性 → GBK 回退识别,也可显式传 utf-8 / gbk / latin1;max_bytes 限制本次返回的文本字节数(默认 262144=256KB,超出按 truncated=true 截断)。目录、或大于 2MB 的文件返回 -32602(请改用 download_file)。返回 size/encoding/eol/lines_total/offset/lines_returned/truncated/text/sha256(sha256 是整个文件,不是本次片段)。读配置文件/日志时用它,不要用 exec_command 的 type/Get-Content(GBK 会乱码、行尾会被归一化);看被管业务程序的日志尾部用 offset=-N(如 offset=-200,N 为行数)。",
"inputSchema": {
"properties": {
"encoding": {
"description": "auto(默认,按 BOM → UTF-8 合法性 → GBK 回退)/ utf-8 / gbk / gb18030 / latin1",
"type": "string"
},
"id": {
"description": "主机 id,取 list_hosts 返回的 id 字段",
"type": "string"
},
"limit": {
"description": "最多返回的行数(1..200000,默认 2000)",
"type": "integer"
},
"max_bytes": {
"description": "本次返回文本的字节上限(1024..2097152,默认 262144=256KB),超出按 truncated=true 截断",
"type": "integer"
},
"offset": {
"description": "起始行(0 基)。负数表示从末尾倒数:-200 = 最后 200 行;默认 0",
"type": "integer"
},
"path": {
"description": "远程文件的绝对路径。Windows 用 D:\\cfg\\app.ini 这类盘符路径;Linux/macOS 用 /etc/app.conf 这类 POSIX 路径。必须是单个普通文件(目录或大于 2MB 的文件返回 -32602)",
"type": "string"
}
},
"required": [
"id",
"path"
],
"type": "object"
},
"outputSchema": {
"properties": {
"encoding": {
"description": "实际使用的编码:utf-8 / utf-16le / utf-16be / gbk / gb18030 / latin1",
"type": "string"
},
"eol": {
"description": "行尾风格:crlf / lf / cr / mixed / none",
"type": "string"
},
"lines_returned": {
"description": "本次返回的行数",
"type": "integer"
},
"lines_total": {
"description": "文件总行数(末尾换行不计空行)",
"type": "integer"
},
"offset": {
"description": "本次实际起始行(负数已换算成绝对行号)",
"type": "integer"
},
"path": {
"description": "远程路径(原样回传)",
"type": "string"
},
"sha256": {
"description": "整个文件的 SHA-256(不是本次片段),可与 download_file 的结果比对",
"type": "string"
},
"size": {
"description": "文件总字节数",
"type": "integer"
},
"text": {
"description": "文件内容(UTF-8,行以 \\n 分隔,已去掉 BOM)",
"type": "string"
},
"truncated": {
"description": "true=还有内容没返回(超出 limit / max_bytes),可调整 offset 继续读",
"type": "boolean"
}
},
"required": [
"path",
"size",
"encoding",
"eol",
"lines_total",
"offset",
"lines_returned",
"truncated",
"text",
"sha256"
],
"type": "object"
}
}
]
+621
View File
@@ -0,0 +1,621 @@
package mcp
import (
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"strings"
"sync/atomic"
"time"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/hub"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/protocol"
)
// terminal_exec bounds. They mirror the Win32 server (McpServer.cpp:4669-4674)
// except the per-command buffer, which is the M4a session ring (256 KiB).
const (
termDefaultTimeoutMS = 20000
termMaxTimeoutMS = 600000
termDefaultMaxOutput = 65536
termMinMaxOutput = 1024
termMaxMaxOutput = 1 << 20
// termTruncBackup is how far back a truncated window may move to end on a
// newline: neither UTF-8 nor GBK can hide a '\n' inside a multibyte char,
// so truncating on a line boundary never corrupts the encoding.
termTruncBackup = 4096
// termBootstrapWait is the longest we wait for a POSIX shell's first
// prompt before writing, so the line discipline does not echo our input
// twice (MFC WaitTerminalBootstrap).
termBootstrapWait = 2 * time.Second
)
// terminalExecArgs is the published inputSchema as Go.
type terminalExecArgs struct {
ID string `json:"id"`
Command string `json:"command"`
SessionID string `json:"session_id"`
TimeoutMS int `json:"timeout_ms"`
MaxOutputBytes int `json:"max_output_bytes"`
}
type terminalExecOutput struct {
Stdout string `json:"stdout"`
Done bool `json:"done"`
SessionID string `json:"session_id"`
IsPTY bool `json:"is_pty"`
Reused bool `json:"reused"`
ExitCode *int `json:"exit_code,omitempty"`
Truncated bool `json:"truncated"`
DroppedBytes uint64 `json:"dropped_bytes,omitempty"`
ElapsedMS int64 `json:"elapsed_ms"`
}
// terminalCloseArgs is the published inputSchema as Go.
type terminalCloseArgs struct {
ID string `json:"id"`
SessionID string `json:"session_id"`
}
type terminalCloseOutput struct {
Closed bool `json:"closed"`
}
func (s *Server) registerTerminalTools() {
s.handlers["terminal_exec"] = s.callTerminalExec
s.handlers["terminal_close"] = s.callTerminalClose
}
// callTerminalClose releases the persistent session MCP opened for a device.
//
// It is idempotent for the session it is given: a session that is already gone
// still answers closed, so a retried close after a timeout does not fail. Only
// sessions in MCP's own table are touched — the web console's shell is left
// alone, and the hub-side close is lease-checked, so a session whose lease was
// taken over is never torn down.
//
// A session_id that names a different live session is a caller mistake
// (-32002), mirroring the Win32 server (McpServer.cpp BuildTerminalClose).
func (s *Server) callTerminalClose(_ context.Context, raw json.RawMessage) (any, *rpcError) {
if s.cfg.Hub == nil {
return nil, errf(CodeInternal, "server device registry is not configured")
}
var args terminalCloseArgs
if rerr := decodeArgs(raw, &args); rerr != nil {
return nil, rerr
}
if args.ID == "" {
return nil, errf(CodeInvalidParams, "Missing required parameter: id")
}
if !isDecimalID(args.ID) {
return nil, errf(CodeInvalidParams, "Invalid id: expected a decimal host id string")
}
if args.SessionID == "" {
return nil, errf(CodeInvalidParams, "Missing required parameter: session_id")
}
if sess := s.sessions.get(args.ID); sess != nil {
if sess.id != args.SessionID {
return nil, errf(CodeOffline, "Terminal session_id mismatch: %s", args.SessionID)
}
// Wakes any terminal_exec still waiting on the command; it delivers the
// bytes buffered so far (done=true, exit_code=-1) before it returns.
s.sessions.closeSessionIf(args.ID, sess)
}
return toolResult{
Content: []contentItem{{Type: "text", Text: "closed"}},
StructuredContent: terminalCloseOutput{Closed: true},
}, nil
}
// callTerminalExec runs one command or polls the output of the previous one.
//
// A call without session_id reuses the device's existing MCP session or opens
// one implicitly, so the model never needs a separate open/close round trip.
// A timeout never destroys the session: the command keeps running on the
// target and the next call with only session_id continues from the delivered
// cursor (design §6.6).
func (s *Server) callTerminalExec(ctx context.Context, raw json.RawMessage) (any, *rpcError) {
if s.cfg.Hub == nil {
return nil, errf(CodeInternal, "server device registry is not configured")
}
var args terminalExecArgs
if rerr := decodeArgs(raw, &args); rerr != nil {
return nil, rerr
}
if args.ID == "" {
return nil, errf(CodeInvalidParams, "Missing required parameter: id")
}
if !isDecimalID(args.ID) {
return nil, errf(CodeInvalidParams, "Invalid id: expected a decimal host id string")
}
command := strings.TrimSpace(args.Command)
isPoll := command == ""
if isPoll && args.SessionID == "" {
return nil, errf(CodeInvalidParams,
"Missing required parameter: session_id (polling needs the session token)")
}
// Polling never writes to the target, so a host that went offline can still
// drain the output already buffered for its ended shell. Everything that
// touches the device (platform gates, validation, opening) is command-only.
var posix bool
if !isPoll {
main := s.cfg.Hub.MainConn(args.ID)
if main == nil {
return nil, errf(CodeOffline, "Host not found or offline: %s", args.ID)
}
platform := main.GetInfo().ClientType
posix = platform == "LNX" || platform == "APK"
if platform == "MAC" {
return nil, errf(CodeUnsupported,
"terminal_exec is only supported on Windows, Linux and Android hosts")
}
if platform == "APK" &&
!protocol.SupportsCap(s.cfg.Hub.Capability(args.ID), protocol.ClientCapTerminal) {
return nil, errf(CodeUnsupported,
"Android client is too old for terminal_exec: the APK has no COMMAND_SHELL handler, upgrade the client first")
}
// Validate before opening a shell: a rejected command must not reserve
// the device's single terminal slot.
if containsControlChar(command) {
return nil, errf(CodeInvalidParams,
"Command contains a control character (newline/tab); send one line per call")
}
if posix && hasPosixBackgroundAmpersand(command) {
return nil, errf(CodeInvalidParams,
"Background execution (&) breaks output capture; use && to chain commands or run it in a separate session")
}
}
timeout := termTimeout(args.TimeoutMS)
maxOut := termMaxOutput(args.MaxOutputBytes)
started := time.Now()
sess, reused, rerr := s.terminalSessionFor(args.ID, args.SessionID)
if rerr != nil {
return nil, rerr
}
if !isPoll {
if rerr := s.waitTermReady(ctx, sess, timeout); rerr != nil {
// A shell that ended with undrained output is kept so the next
// session_id poll can still collect its tail; say so, since the
// caller cannot see the session behind an implicit open.
if sess.isClosed() && sess.hasPending() {
return nil, errf(rerr.Code,
"%s. Its output is still buffered; call terminal_exec with only session_id %s to collect it",
rerr.Message, sess.id)
}
// A shell that never came up would otherwise hold the device's single
// terminal slot until an idle sweep; release it now (MFC erases too).
s.sessions.closeSessionIf(args.ID, sess)
return nil, rerr
}
}
sess.mu.Lock()
isPTY := sess.isPTY
sess.mu.Unlock()
if !isPoll && !isPTY {
s.sessions.closeSessionIf(args.ID, sess)
return nil, errf(CodeUnsupported,
"The client on host %s uses the legacy non-PTY shell; this server only supports PTY sessions (ConPTY / POSIX PTY). Upgrade the client",
args.ID)
}
var p *pendingCmd
if isPoll {
p, rerr = sess.pollPending()
if rerr != nil {
return nil, rerr
}
} else {
nonce := newTermNonce()
cmdLine, sentLine := buildSentinelLines(true, posix, command, nonce)
p, rerr = sess.beginCommand(nonce, cmdLine, sentLine)
if rerr != nil {
return nil, rerr
}
// A first command can race the shell's own startup; writing before the
// prompt appears makes the driver echo the input a second time.
if posix {
s.waitTermBootstrap(ctx, sess, timeout)
}
if !sess.isClosed() {
if err := s.sessions.send(args.ID, buildTerminalWire(posix, cmdLine, sentLine)); err != nil {
sess.abortCommand(p)
return nil, errf(CodeSendFailed, "Failed to send command to host: %v", err)
}
}
}
out, rerr := s.awaitAndDeliver(ctx, sess, p, maxOut, timeout)
if rerr != nil {
return nil, rerr
}
// An ended shell's session outlives it only until its last bytes are
// delivered (sessionTable.closed keeps it); drop it now without touching the
// hub, which may already belong to a new viewer.
if out.Done && sess.isClosed() && !sess.hasPending() {
s.sessions.forget(args.ID, sess)
}
out.SessionID = sess.id
out.IsPTY = isPTY
out.Reused = reused
out.ElapsedMS = time.Since(started).Milliseconds()
return terminalExecResult(out), nil
}
// terminalSessionFor resolves the session: an explicit id must match the
// device's MCP session; without one, an existing session is reused, otherwise
// a new shell is opened.
func (s *Server) terminalSessionFor(deviceID, sessionID string) (*termSession, bool, *rpcError) {
if sessionID != "" {
sess := s.sessions.get(deviceID)
if sess == nil {
return nil, true, errf(CodeOffline,
"Terminal session not found: %s (pass a command without session_id to open a new one)", sessionID)
}
if sess.id != sessionID {
return nil, true, errf(CodeOffline, "Terminal session_id mismatch: %s", sessionID)
}
return sess, true, nil
}
if sess := s.sessions.get(deviceID); sess != nil {
return sess, true, nil
}
sess, err := s.sessions.open(deviceID)
if err == nil {
return sess, false, nil
}
switch {
case errors.Is(err, hub.ErrTerminalBusy):
// The holder is the web console: an existing MCP session is reused above,
// so there is no MCP session_id to hand out or close here.
return nil, false, errf(CodeBusy,
"Device busy: the terminal on host %s is held by the web console (a human viewer); there is no MCP session_id to close — wait for the viewer to disconnect", deviceID)
case errors.Is(err, hub.ErrDeviceOffline):
return nil, false, errf(CodeOffline, "Host not found or offline: %s", deviceID)
case errors.Is(err, errNoDeviceHub):
return nil, false, errf(CodeInternal, "server device registry is not configured")
case errors.Is(err, errSessionClosed):
return nil, false, errf(CodeBusy,
"Device busy: the terminal session for host %s closed while opening; retry", deviceID)
default:
return nil, false, errf(CodeSendFailed, "Failed to open terminal on host: %v", err)
}
}
// waitTermReady waits for OnTerminalReady. Failing here means no shell exists to
// command, so the caller releases the slot.
func (s *Server) waitTermReady(ctx context.Context, sess *termSession, timeout time.Duration) *rpcError {
deadline := time.Now().Add(timeout)
stop := wakeOn(ctx, sess, deadline)
defer stop()
sess.mu.Lock()
defer sess.mu.Unlock()
for !sess.ready && !sess.closed && ctx.Err() == nil && time.Now().Before(deadline) {
sess.cond.Wait()
}
if sess.ready && !sess.closed {
return nil
}
if sess.closed {
reason := sess.closeReason
if reason == "" {
reason = "closed"
}
return errf(CodeOffline, "Terminal session ended while starting: %s", reason)
}
if ctx.Err() != nil {
return errf(CodeTimeout, "Request cancelled while waiting for the shell to start")
}
return errf(CodeTimeout,
"Timeout waiting for shell to start (the client may not support remote shell, or the host is unresponsive)")
}
// waitTermBootstrap waits for the shell's first screen so the input is echoed
// once, not twice. The wait is bounded by the call's own timeout as well as the
// bootstrap cap (MFC uses min(timeoutMs, 2000)); a timeout is not an error: the
// command is still written.
func (s *Server) waitTermBootstrap(ctx context.Context, sess *termSession, timeout time.Duration) {
deadline := time.Now().Add(min(timeout, termBootstrapWait))
stop := wakeOn(ctx, sess, deadline)
defer stop()
sess.mu.Lock()
defer sess.mu.Unlock()
for !sess.sawOutput && !sess.closed && ctx.Err() == nil && time.Now().Before(deadline) {
sess.cond.Wait()
}
}
// awaitAndDeliver waits for the command to finish (or the call's deadline) and
// returns the next window of output. The session survives either outcome; only
// its delivered cursor moves.
func (s *Server) awaitAndDeliver(ctx context.Context, sess *termSession, p *pendingCmd,
maxOut int, timeout time.Duration) (terminalExecOutput, *rpcError) {
deadline := time.Now().Add(timeout)
sess.mu.Lock()
p.deadline = deadline
sess.mu.Unlock()
stop := wakeOn(ctx, sess, deadline)
defer stop()
sess.mu.Lock()
defer sess.mu.Unlock()
for !p.done && !sess.closed && ctx.Err() == nil && time.Now().Before(deadline) {
sess.cond.Wait()
}
if ctx.Err() != nil {
// The HTTP client is gone; the command keeps running (design §6.6). The
// caller never saw a result, so the message has to carry the session id
// it needs to poll or close the shell.
return terminalExecOutput{}, errf(CodeTimeout,
"Request cancelled; the command is still running on session_id=%s — poll terminal_exec with that session_id (empty command) or release it with terminal_close", sess.id)
}
var out terminalExecOutput
out.Done = p.done || sess.closed
if p.done && !sess.closed {
code := p.exitCode
out.ExitCode = &code
} else if out.Done {
code := -1 // shell exited or was closed: the real code is unknown
out.ExitCode = &code
}
base := sess.baseLocked()
if base > sess.delivered {
// The ring evicted bytes this command produced but never delivered.
p.lost += base - sess.delivered
sess.delivered = base
}
end := sess.total
if p.done {
end = min(p.outputEnd, sess.total)
}
if sess.delivered > end {
sess.delivered = end
}
window, truncated := readDeliveryWindow(sess, sess.delivered, end, maxOut)
sess.delivered += uint64(len(window))
sess.lastUsed = time.Now()
finalChunk := out.Done && !truncated
out.Stdout = cleanTerminalOutput(window, sess.isPTY, p.firstChunk,
p.cmdLine, p.sentLine, p.nonce, finalChunk)
// The PTY echoes the input exactly once, so the flag may only fall after a
// window actually carried bytes: a call that timed out before the echo
// arrived must not leave the echo for the next poll to print.
if len(window) > 0 {
p.firstChunk = false
}
out.Truncated = truncated
out.DroppedBytes = p.lost
// The identity check matters when a command was started after the previous
// one finished but before this call could collect its last window: that
// waiter must not clear the new command's pending entry.
if out.Done && sess.delivered >= end && sess.pending == p {
// Fully delivered: the session is idle again. Keeping the pending entry
// would make the next command answer "busy" forever.
sess.pending = nil
sess.cond.Broadcast()
}
return out, nil
}
// readDeliveryWindow returns the next window of raw output starting at from,
// bounded by maxOut and, when truncated, backed up to the last newline within
// termTruncBackup bytes. It never returns bytes past end (the sentinel start
// when the command finished).
func readDeliveryWindow(sess *termSession, from, end uint64, maxOut int) ([]byte, bool) {
if from >= end {
return nil, false
}
want := end - from
n := int(min(want, uint64(maxOut)))
window, _, _ := sess.readLocked(from, n)
truncated := want > uint64(n)
if truncated {
floor := 0
if len(window) > termTruncBackup {
floor = len(window) - termTruncBackup
}
for i := len(window); i > floor; i-- {
if window[i-1] == '\n' {
window = window[:i]
break
}
}
}
return window, truncated
}
// ----- session state machine ------------------------------------------------
// beginCommand marks the session busy with a new command. The output cursor
// starts at the current end of the stream, so earlier prompt/output bytes are
// never delivered as this command's result.
func (s *termSession) beginCommand(nonce, cmdLine, sentLine string) (*pendingCmd, *rpcError) {
s.mu.Lock()
defer s.mu.Unlock()
if s.closed {
return nil, errf(CodeOffline, "Terminal session ended: %s", s.closeReason)
}
if !s.ready {
return nil, errf(CodeOffline, "Terminal session is not ready yet: %s", s.id)
}
if s.pending != nil {
if !s.pending.done {
return nil, errf(CodeBusy, "Device busy: another terminal_exec is already running for this session")
}
end := min(s.pending.outputEnd, s.total)
if s.delivered < end {
return nil, errf(CodeBusy,
"Device busy: the previous command finished but its output is not fully drained; call terminal_exec with only session_id to collect the rest first")
}
// The finished command has no bytes left to collect (a waiter timed out
// after the sentinel was seen). Start the new command instead of making
// the caller poll for nothing; a stale waiter still holding the old
// pointer is fenced by the identity check in awaitAndDeliver.
s.pending = nil
}
now := time.Now()
p := &pendingCmd{
sentinel: "__MCP_DONE_" + nonce + "__",
nonce: nonce,
cmdLine: cmdLine,
sentLine: sentLine,
start: s.total,
scanPos: s.total,
busySince: now,
firstChunk: true,
}
s.pending = p
s.delivered = s.total
s.lastUsed = now
s.cond.Broadcast()
return p, nil
}
// pollPending returns the command already in flight, including the tail of one
// whose shell has ended (the session stays reachable until the bytes are
// delivered). Polling an idle session is a caller mistake: it would otherwise
// wait out the whole timeout.
func (s *termSession) pollPending() (*pendingCmd, *rpcError) {
s.mu.Lock()
defer s.mu.Unlock()
if s.pending == nil {
if s.closed {
return nil, errf(CodeOffline, "Terminal session ended: %s", s.closeReason)
}
return nil, errf(CodeOffline,
"Terminal session is idle: no command is running; pass command to execute one")
}
return s.pending, nil
}
// hasPending reports whether a command still owns the session. Its output may
// be undrained even when the shell has already ended.
func (s *termSession) hasPending() bool {
s.mu.Lock()
defer s.mu.Unlock()
return s.pending != nil
}
// abortCommand clears a command whose bytes could not be written, so the
// session does not stay busy for a command that never existed.
func (s *termSession) abortCommand(p *pendingCmd) {
s.mu.Lock()
defer s.mu.Unlock()
if s.pending == p {
s.pending = nil
s.cond.Broadcast()
}
}
func (t *sessionTable) send(deviceID string, data []byte) error {
if t.hub == nil {
return errNoDeviceHub
}
return t.hub.SendToTerminal(deviceID, data)
}
// isClosed reports the session's terminal state. Its fields are immutable
// once set, so this is race-free with the lock held briefly.
func (s *termSession) isClosed() bool {
s.mu.Lock()
defer s.mu.Unlock()
return s.closed
}
// wakeOn broadcasts on the session's condition when ctx ends, the deadline
// passes, or the returned stop function is called. sync.Cond has no timeout or
// cancellation, so every waiter pairs it with this helper.
func wakeOn(ctx context.Context, sess *termSession, deadline time.Time) func() {
timer := time.NewTimer(time.Until(deadline))
done := make(chan struct{})
go func() {
select {
case <-ctx.Done():
case <-timer.C:
case <-done:
}
sess.mu.Lock()
sess.cond.Broadcast()
sess.mu.Unlock()
}()
return func() {
timer.Stop()
close(done)
}
}
// terminalExecResult wraps the output in the MCP result shape. The text item
// carries stdout; a second compact-JSON item carries the status fields so a
// client that only reads content still sees done/exit_code/truncated.
func terminalExecResult(out terminalExecOutput) toolResult {
text := out.Stdout
if text == "" {
if out.Done {
text = "(无输出)"
} else {
text = "(暂无新输出,命令仍在运行,继续轮询)"
}
}
status := map[string]any{
"done": out.Done,
"session_id": out.SessionID,
"truncated": out.Truncated,
}
if out.ExitCode != nil {
status["exit_code"] = *out.ExitCode
}
if out.DroppedBytes > 0 {
status["dropped_bytes"] = out.DroppedBytes
}
statusJSON, err := json.Marshal(status)
if err != nil {
statusJSON = []byte("{}")
}
return toolResult{
Content: []contentItem{
{Type: "text", Text: text},
{Type: "text", Text: string(statusJSON)},
},
StructuredContent: out,
IsError: false,
}
}
func termTimeout(ms int) time.Duration {
if ms <= 0 || ms > termMaxTimeoutMS {
ms = termDefaultTimeoutMS
}
return time.Duration(ms) * time.Millisecond
}
func termMaxOutput(n int) int {
if n < termMinMaxOutput || n > termMaxMaxOutput {
return termDefaultMaxOutput
}
return n
}
// termNonceFallback numbers nonces when crypto/rand is unavailable. The nonce
// only has to be unique enough that output cannot contain the marker.
var termNonceFallback atomic.Uint32
func newTermNonce() string {
var b [4]byte
if _, err := rand.Read(b[:]); err == nil {
return hex.EncodeToString(b[:])
}
return fmt.Sprintf("%08x", termNonceFallback.Add(1))
}
+769
View File
@@ -0,0 +1,769 @@
package mcp
import (
"context"
"encoding/json"
"fmt"
"net"
"strings"
"testing"
"time"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/connection"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/hub"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/protocol"
)
// termRig is a live MCP server plus a hub whose device's shell answers every
// open request immediately. Tests drive the shell by feeding OnTerminalData
// packets, i.e. exactly what cmd/main.go delivers from the TCP read loop.
type termRig struct {
t *testing.T
s *Server
h *hub.Hub
main *connection.Context
sub *connection.Context
writes chan []byte
opened chan struct{}
stop chan struct{}
}
func newTermRig(t *testing.T, clientType, capability string, isPTY bool) *termRig {
t.Helper()
h := hub.New()
main := &connection.Context{RemoteAddr: "10.0.0.1:4000"}
main.Info.ClientType = clientType
// The hub closes the shell sub-conn 500 ms after teardown; a real net.Conn
// keeps that path from dereferencing nil.
shellConn, peer := net.Pipe()
t.Cleanup(func() { _ = shellConn.Close(); _ = peer.Close() })
sub := &connection.Context{RemoteAddr: "10.0.0.1:4001", Conn: shellConn}
rig := &termRig{
t: t, h: h, main: main, sub: sub,
writes: make(chan []byte, 64),
opened: make(chan struct{}, 4),
stop: make(chan struct{}),
}
h.SetSender(func(ctx *connection.Context, data []byte) error {
switch ctx {
case main:
if len(data) == 1 && data[0] == protocol.CommandShell {
select {
case rig.opened <- struct{}{}:
default:
}
}
case sub:
select {
case rig.writes <- append([]byte(nil), data...):
default:
}
}
return nil
})
h.Register(&hub.Device{ID: "1001", PeerIP: "10.0.0.1", Capability: capability}, main)
rig.s = New(Config{Token: testToken, Hub: h})
t.Cleanup(func() { close(rig.stop) })
// Subscribe like cmd/main.go does, so OnTerminalReady/Data/Closed flow.
unsub := h.Subscribe(rig.s)
t.Cleanup(unsub)
t.Cleanup(rig.s.Close)
// The device answers COMMAND_SHELL by opening a shell sub-connection. The
// loop keeps answering, so a test can close a session and reopen at once.
go func() {
for {
select {
case <-rig.opened:
h.BindTerminalConn("1001", sub, isPTY)
case <-rig.stop:
return
}
}
}()
return rig
}
type termCall struct {
out terminalExecOutput
err *rpcError
}
func (r *termRig) callAsync(args string) <-chan termCall {
ch := make(chan termCall, 1)
go func() {
res, rerr := r.s.callTerminalExec(context.Background(), json.RawMessage(args))
if rerr != nil {
ch <- termCall{err: rerr}
return
}
tr, ok := res.(toolResult)
if !ok {
ch <- termCall{err: errf(CodeInternal, "unexpected result type %T", res)}
return
}
out, ok := tr.StructuredContent.(terminalExecOutput)
if !ok {
ch <- termCall{err: errf(CodeInternal, "unexpected structured content %T", tr.StructuredContent)}
return
}
ch <- termCall{out: out}
}()
return ch
}
func (r *termRig) wait(ch <-chan termCall) termCall {
r.t.Helper()
select {
case c := <-ch:
return c
case <-time.After(5 * time.Second):
r.t.Fatal("timed out waiting for the tool call")
return termCall{}
}
}
// nextCommandWire returns the next write to the shell that carries a sentinel
// and the nonce embedded in it.
func (r *termRig) nextCommandWire() (wire, nonce string) {
r.t.Helper()
deadline := time.After(5 * time.Second)
for {
select {
case b := <-r.writes:
s := string(b)
i := strings.Index(s, "__MCP_DONE_")
if i < 0 {
continue
}
rest := s[i+len("__MCP_DONE_"):]
j := strings.Index(rest, "__")
if j <= 0 {
continue
}
return s, rest[:j]
case <-deadline:
r.t.Fatal("timed out waiting for the command wire")
return "", ""
}
}
}
func (r *termRig) feed(text string) {
r.s.OnTerminalData("1001", termPacket(text))
}
// callClose runs terminal_close directly on the handler, bypassing the HTTP
// layer's device lock (which the handler must ignore anyway).
func (r *termRig) callClose(args string) (terminalCloseOutput, *rpcError) {
r.t.Helper()
res, rerr := r.s.callTerminalClose(context.Background(), json.RawMessage(args))
if rerr != nil {
return terminalCloseOutput{}, rerr
}
tr, ok := res.(toolResult)
if !ok {
r.t.Fatalf("unexpected close result type %T", res)
}
if len(tr.Content) != 1 || tr.Content[0].Text != "closed" {
r.t.Fatalf("close content = %+v", tr.Content)
}
out, ok := tr.StructuredContent.(terminalCloseOutput)
if !ok {
r.t.Fatalf("unexpected close structured content %T", tr.StructuredContent)
}
return out, nil
}
// runToCompletion runs one command through the rig to its sentinel.
func (r *termRig) runToCompletion(command, output string) termCall {
r.t.Helper()
ch := r.callAsync(fmt.Sprintf(`{"id":"1001","command":%q,"timeout_ms":5000}`, command))
_, nonce := r.nextCommandWire()
r.feed("@" + "echo off & " + command + "\r\n" + output + "\r\n__MCP_DONE_" + nonce + "__0\r\n")
res := r.wait(ch)
if res.err != nil || !res.out.Done {
r.t.Fatalf("runToCompletion(%q) = %+v / %v", command, res.out, res.err)
}
return res
}
func TestTerminalExecRunsCommand(t *testing.T) {
rig := newTermRig(t, "", "", true)
ch := rig.callAsync(`{"id":"1001","command":"echo hello","timeout_ms":5000}`)
wire, nonce := rig.nextCommandWire()
if !strings.HasPrefix(wire, "@echo off & echo hello\r\necho __MCP_DONE_"+nonce+"__%errorlevel%\r\n") {
t.Fatalf("wire = %q", wire)
}
// ConPTY: the first line is the echoed command; the real output follows.
rig.feed("@echo off & echo hello\r\nhello\r\n__MCP_DONE_" + nonce + "__0\r\n")
res := rig.wait(ch)
if res.err != nil {
t.Fatalf("call failed: %v", res.err)
}
out := res.out
if out.Stdout != "hello" || !out.Done || out.ExitCode == nil || *out.ExitCode != 0 {
t.Fatalf("out = %+v", out)
}
if !out.IsPTY || out.Reused || out.Truncated || out.DroppedBytes != 0 {
t.Fatalf("flags = %+v", out)
}
if !strings.HasPrefix(out.SessionID, "s-") {
t.Fatalf("session id = %q", out.SessionID)
}
if out.ElapsedMS < 0 {
t.Fatalf("elapsed = %d", out.ElapsedMS)
}
}
func TestTerminalExecTimeoutThenPoll(t *testing.T) {
rig := newTermRig(t, "", "", true)
ch := rig.callAsync(`{"id":"1001","command":"ping -n 30 127.0.0.1","timeout_ms":100}`)
_, nonce := rig.nextCommandWire()
res := rig.wait(ch)
if res.err != nil {
t.Fatalf("first call: %v", res.err)
}
if res.out.Done || res.out.Stdout != "" {
t.Fatalf("timeout result = %+v", res.out)
}
sid := res.out.SessionID
rig.feed("part1\r\n")
ch = rig.callAsync(fmt.Sprintf(`{"id":"1001","session_id":%q,"timeout_ms":100}`, sid))
res = rig.wait(ch)
if res.err != nil {
t.Fatalf("poll 1: %v", res.err)
}
if res.out.Done || res.out.Stdout != "part1\n" {
t.Fatalf("poll 1 = %+v", res.out)
}
if res.out.SessionID != sid {
t.Fatalf("poll 1 session id = %q, want %q", res.out.SessionID, sid)
}
rig.feed("part2\r\n__MCP_DONE_" + nonce + "__3\r\n")
ch = rig.callAsync(fmt.Sprintf(`{"id":"1001","session_id":%q,"timeout_ms":1000}`, sid))
res = rig.wait(ch)
if res.err != nil {
t.Fatalf("poll 2: %v", res.err)
}
if !res.out.Done || res.out.Stdout != "part2" || res.out.ExitCode == nil || *res.out.ExitCode != 3 {
t.Fatalf("poll 2 = %+v", res.out)
}
// The command is drained; polling an idle session is a caller mistake.
ch = rig.callAsync(fmt.Sprintf(`{"id":"1001","session_id":%q,"timeout_ms":100}`, sid))
res = rig.wait(ch)
if res.err == nil || res.err.Code != CodeOffline || !strings.Contains(res.err.Message, "idle") {
t.Fatalf("idle poll = %+v", res.err)
}
}
func TestTerminalExecBusyWhileRunning(t *testing.T) {
rig := newTermRig(t, "", "", true)
ch := rig.callAsync(`{"id":"1001","command":"ping -n 30 127.0.0.1","timeout_ms":50}`)
_, nonce := rig.nextCommandWire()
if res := rig.wait(ch); res.err != nil || res.out.Done {
t.Fatalf("first call = %+v / %v", res.out, res.err)
}
ch = rig.callAsync(`{"id":"1001","command":"echo again","timeout_ms":100}`)
res := rig.wait(ch)
if res.err == nil || res.err.Code != CodeBusy {
t.Fatalf("busy call = %+v", res.err)
}
// Finish the first command so cleanup does not tear down a running shell.
rig.feed("__MCP_DONE_" + nonce + "__0\r\n")
}
func TestTerminalExecRejectsNonPTY(t *testing.T) {
rig := newTermRig(t, "", "", false)
ch := rig.callAsync(`{"id":"1001","command":"echo hi","timeout_ms":1000}`)
res := rig.wait(ch)
if res.err == nil || res.err.Code != CodeUnsupported || !strings.Contains(res.err.Message, "PTY") {
t.Fatalf("non-PTY = %+v", res.err)
}
if rig.s.sessions.get("1001") != nil {
t.Fatal("rejected session still in the table")
}
if rig.h.HasTerminalSession("1001") {
t.Fatal("rejected session still holds the hub lease")
}
}
func TestTerminalExecUnknownSession(t *testing.T) {
rig := newTermRig(t, "", "", true)
ch := rig.callAsync(`{"id":"1001","session_id":"s-abcdef","timeout_ms":100}`)
res := rig.wait(ch)
if res.err == nil || res.err.Code != CodeOffline || !strings.Contains(res.err.Message, "not found") {
t.Fatalf("unknown session = %+v", res.err)
}
}
func TestTerminalExecRejectsBadArgs(t *testing.T) {
rig := newTermRig(t, "", "", true)
cases := []string{
`{"id":"1001","timeout_ms":100}`, // poll without session_id
`{"id":"1001","command":"a\nb","timeout_ms":100}`, // control char
`{"command":"echo hi","timeout_ms":100}`, // missing id
`{"id":"abc","command":"echo hi","timeout_ms":100}`, // id not decimal
}
for _, args := range cases {
ch := rig.callAsync(args)
res := rig.wait(ch)
if res.err == nil || res.err.Code != CodeInvalidParams {
t.Fatalf("%s: %+v", args, res.err)
}
}
select {
case b := <-rig.writes:
t.Fatalf("rejected command was written to the shell: %q", b)
default:
}
}
func TestTerminalExecAPKCapabilityGate(t *testing.T) {
rig := newTermRig(t, "APK", "0400", true) // no CLIENT_CAP_TERMINAL (0x8000)
ch := rig.callAsync(`{"id":"1001","command":"echo hi","timeout_ms":100}`)
res := rig.wait(ch)
if res.err == nil || res.err.Code != CodeUnsupported || !strings.Contains(res.err.Message, "too old") {
t.Fatalf("APK gate = %+v", res.err)
}
}
func TestTerminalExecAPKWithTerminalCap(t *testing.T) {
rig := newTermRig(t, "APK", "8400", true) // 0x8000 | 0x0400
ch := rig.callAsync(`{"id":"1001","command":"echo hi","timeout_ms":5000}`)
wire, nonce := rig.nextCommandWire()
// POSIX PTY: PS1 is cleared first and the sentinel uses $?.
if !strings.HasPrefix(wire, "PS1=\r\necho hi\r\necho __MCP_DONE_"+nonce+"__$?\r\n") {
t.Fatalf("POSIX wire = %q", wire)
}
rig.feed("PS1=\r\necho hi\r\nhi\r\n__MCP_DONE_" + nonce + "__0\r\n")
res := rig.wait(ch)
if res.err != nil {
t.Fatalf("APK exec: %v", res.err)
}
if res.out.Stdout != "hi" || !res.out.Done {
t.Fatalf("APK out = %+v", res.out)
}
}
func TestTerminalExecMACRejected(t *testing.T) {
rig := newTermRig(t, "MAC", "", true)
ch := rig.callAsync(`{"id":"1001","command":"echo hi","timeout_ms":100}`)
res := rig.wait(ch)
if res.err == nil || res.err.Code != CodeUnsupported {
t.Fatalf("MAC = %+v", res.err)
}
}
func TestTerminalExecTruncatesOnLineBoundary(t *testing.T) {
rig := newTermRig(t, "", "", true)
ch := rig.callAsync(`{"id":"1001","command":"dump","timeout_ms":5000,"max_output_bytes":1024}`)
_, nonce := rig.nextCommandWire()
var payload strings.Builder
for i := 0; i < 300; i++ {
fmt.Fprintf(&payload, "line-%03d-xxxxxxxxxxxxxx\r\n", i)
}
payload.WriteString("__MCP_DONE_" + nonce + "__0\r\n")
rig.feed(payload.String())
var got strings.Builder
const wantLines = 300
for i := 0; i < 100; i++ {
res := rig.wait(ch)
if res.err != nil {
t.Fatalf("window %d: %v", i, res.err)
}
got.WriteString(res.out.Stdout)
if res.out.ExitCode == nil || *res.out.ExitCode != 0 {
t.Fatalf("window %d exit = %+v", i, res.out)
}
if !res.out.Done {
t.Fatalf("window %d: command should already be done", i)
}
if !res.out.Truncated {
break
}
if len(res.out.Stdout) > 1024 {
t.Fatalf("window %d exceeded max_output_bytes: %d", i, len(res.out.Stdout))
}
ch = rig.callAsync(fmt.Sprintf(
`{"id":"1001","session_id":%q,"timeout_ms":5000,"max_output_bytes":1024}`, res.out.SessionID))
}
lines := strings.Split(strings.TrimRight(got.String(), "\n"), "\n")
if len(lines) != wantLines {
t.Fatalf("got %d lines, want %d", len(lines), wantLines)
}
for i, line := range lines {
if want := fmt.Sprintf("line-%03d-xxxxxxxxxxxxxx", i); line != want {
t.Fatalf("line %d = %q, want %q", i, line, want)
}
}
}
// A shell that dies mid-command keeps its undelivered output in the session:
// the device is offline, but the next poll must still collect the tail.
func TestTerminalExecDrainsAfterClose(t *testing.T) {
rig := newTermRig(t, "", "", true)
ch := rig.callAsync(`{"id":"1001","command":"ping -n 30 127.0.0.1","timeout_ms":50}`)
_, _ = rig.nextCommandWire()
first := rig.wait(ch)
if first.err != nil || first.out.Done {
t.Fatalf("first call = %+v / %v", first.out, first.err)
}
sid := first.out.SessionID
rig.feed("partial output\r\n")
// The device goes away: the hub releases the shell, then the main conn.
rig.h.CloseTerminalSession("1001")
rig.h.Unregister("1001")
ch = rig.callAsync(fmt.Sprintf(`{"id":"1001","session_id":%q,"timeout_ms":1000}`, sid))
res := rig.wait(ch)
if res.err != nil {
t.Fatalf("drain poll: %v", res.err)
}
if res.out.Stdout != "partial output" || !res.out.Done {
t.Fatalf("drain = %+v", res.out)
}
if res.out.ExitCode == nil || *res.out.ExitCode != -1 {
t.Fatalf("closed exit code = %+v", res.out.ExitCode)
}
if res.out.SessionID != sid {
t.Fatalf("session id = %q, want %q", res.out.SessionID, sid)
}
// Fully delivered: the ended session is released, so the offline host now
// reports it as gone instead of serving it forever.
ch = rig.callAsync(fmt.Sprintf(`{"id":"1001","session_id":%q,"timeout_ms":100}`, sid))
res = rig.wait(ch)
if res.err == nil || res.err.Code != CodeOffline || !strings.Contains(res.err.Message, "not found") {
t.Fatalf("post-drain poll = %+v", res.err)
}
}
// Closing with more than max_output_bytes buffered must still deliver every
// line across polls, even though the shell is gone after the first window.
func TestTerminalExecCloseKeepsTruncatedTail(t *testing.T) {
rig := newTermRig(t, "", "", true)
ch := rig.callAsync(`{"id":"1001","command":"dump","timeout_ms":50}`)
_, _ = rig.nextCommandWire()
first := rig.wait(ch)
if first.err != nil || first.out.Done {
t.Fatalf("first call = %+v / %v", first.out, first.err)
}
sid := first.out.SessionID
var payload strings.Builder
for i := 0; i < 100; i++ {
fmt.Fprintf(&payload, "line-%03d-xxxxxxxx\r\n", i)
}
rig.feed(payload.String())
rig.h.CloseTerminalSession("1001")
var got strings.Builder
ch = rig.callAsync(fmt.Sprintf(
`{"id":"1001","session_id":%q,"timeout_ms":1000,"max_output_bytes":1024}`, sid))
for i := 0; i < 20; i++ {
res := rig.wait(ch)
if res.err != nil {
t.Fatalf("window %d: %v", i, res.err)
}
got.WriteString(res.out.Stdout)
if !res.out.Done {
t.Fatalf("window %d should be done: %+v", i, res.out)
}
if res.out.ExitCode == nil || *res.out.ExitCode != -1 {
t.Fatalf("window %d exit = %+v", i, res.out.ExitCode)
}
if !res.out.Truncated {
break
}
ch = rig.callAsync(fmt.Sprintf(
`{"id":"1001","session_id":%q,"timeout_ms":1000,"max_output_bytes":1024}`, sid))
}
lines := strings.Split(strings.TrimRight(got.String(), "\n"), "\n")
if len(lines) != 100 {
t.Fatalf("got %d lines, want 100", len(lines))
}
for i, line := range lines {
if want := fmt.Sprintf("line-%03d-xxxxxxxx", i); line != want {
t.Fatalf("line %d = %q, want %q", i, line, want)
}
}
}
// The PTY echo can arrive after the command call timed out. The poll must still
// recognise it as the echo and not print the command line as output.
func TestTerminalExecPollStripsLateEcho(t *testing.T) {
rig := newTermRig(t, "", "", true)
ch := rig.callAsync(`{"id":"1001","command":"echo hello","timeout_ms":50}`)
_, nonce := rig.nextCommandWire()
first := rig.wait(ch)
if first.err != nil || first.out.Done || first.out.Stdout != "" {
t.Fatalf("first = %+v / %v", first.out, first.err)
}
rig.feed("@echo off & echo hello\r\nhello\r\n__MCP_DONE_" + nonce + "__0\r\n")
ch = rig.callAsync(fmt.Sprintf(`{"id":"1001","session_id":%q,"timeout_ms":1000}`, first.out.SessionID))
res := rig.wait(ch)
if res.err != nil {
t.Fatalf("poll: %v", res.err)
}
if res.out.Stdout != "hello" || !res.out.Done {
t.Fatalf("poll = %+v, want the echo removed", res.out)
}
}
// A finished command with nothing left to collect must not answer "busy": its
// stale pending entry is dropped and the new command runs.
func TestTerminalExecCommandAfterDrainedFinish(t *testing.T) {
rig := newTermRig(t, "", "", true)
ch := rig.callAsync(`{"id":"1001","command":"slow","timeout_ms":50}`)
_, nonce := rig.nextCommandWire()
rig.feed("early\r\n")
first := rig.wait(ch)
if first.err != nil || first.out.Done || first.out.Stdout != "early\n" {
t.Fatalf("first = %+v / %v", first.out, first.err)
}
// The sentinel arrives after the call returned; everything it ends was
// already delivered, so the session is effectively idle.
rig.feed("__MCP_DONE_" + nonce + "__0\r\n")
ch = rig.callAsync(`{"id":"1001","command":"echo next","timeout_ms":5000}`)
_, nonce2 := rig.nextCommandWire()
rig.feed("next-out\r\n__MCP_DONE_" + nonce2 + "__0\r\n")
res := rig.wait(ch)
if res.err != nil {
t.Fatalf("next command: %v", res.err)
}
if res.out.Stdout != "next-out" || !res.out.Done {
t.Fatalf("next command = %+v", res.out)
}
}
// A command naming a session that already ended must not destroy the tail it
// still holds; the caller is told to poll instead.
func TestTerminalExecEndedSessionAsksForPoll(t *testing.T) {
rig := newTermRig(t, "", "", true)
ch := rig.callAsync(`{"id":"1001","command":"ping -n 30 127.0.0.1","timeout_ms":50}`)
_, _ = rig.nextCommandWire()
first := rig.wait(ch)
if first.err != nil || first.out.Done {
t.Fatalf("first = %+v / %v", first.out, first.err)
}
sid := first.out.SessionID
rig.feed("tail\r\n")
rig.h.CloseTerminalSession("1001")
ch = rig.callAsync(fmt.Sprintf(
`{"id":"1001","session_id":%q,"command":"echo again","timeout_ms":200}`, sid))
if res := rig.wait(ch); res.err == nil ||
!strings.Contains(res.err.Message, sid) || !strings.Contains(res.err.Message, "session_id") {
t.Fatalf("command on an ended session = %+v, want a pointer to drain it by id", res.err)
}
ch = rig.callAsync(fmt.Sprintf(`{"id":"1001","session_id":%q,"timeout_ms":1000}`, sid))
res := rig.wait(ch)
if res.err != nil {
t.Fatalf("drain after ended command: %v", res.err)
}
if res.out.Stdout != "tail" || !res.out.Done {
t.Fatalf("drain = %+v", res.out)
}
}
// The POSIX bootstrap wait is capped by the call's own timeout, not always 2 s.
func TestTerminalExecBootstrapHonoursCallTimeout(t *testing.T) {
rig := newTermRig(t, "APK", "8400", true) // POSIX: the bootstrap wait applies
start := time.Now()
ch := rig.callAsync(`{"id":"1001","command":"echo hi","timeout_ms":300}`)
_, _ = rig.nextCommandWire()
res := rig.wait(ch)
if res.err != nil {
t.Fatalf("call: %v", res.err)
}
if elapsed := time.Since(start); elapsed > 1500*time.Millisecond {
t.Fatalf("bootstrap ignored the call timeout: %v", elapsed)
}
}
// terminal_close releases the MCP-owned session and is idempotent: a second
// close (or a close after a reap) still answers closed instead of an error.
func TestTerminalCloseIsIdempotent(t *testing.T) {
rig := newTermRig(t, "", "", true)
sid := rig.runToCompletion("echo hello", "hello").out.SessionID
out, rerr := rig.callClose(fmt.Sprintf(`{"id":"1001","session_id":%q}`, sid))
if rerr != nil || !out.Closed {
t.Fatalf("close = %+v / %v", out, rerr)
}
if rig.s.sessions.get("1001") != nil {
t.Fatal("closed session still in the table")
}
if rig.h.HasTerminalSession("1001") {
t.Fatal("closed session still holds the hub lease")
}
out, rerr = rig.callClose(fmt.Sprintf(`{"id":"1001","session_id":%q}`, sid))
if rerr != nil || !out.Closed {
t.Fatalf("second close = %+v / %v", out, rerr)
}
}
func TestTerminalCloseRejectsMismatchedSession(t *testing.T) {
rig := newTermRig(t, "", "", true)
rig.runToCompletion("echo hello", "hello")
_, rerr := rig.callClose(`{"id":"1001","session_id":"s-000000"}`)
if rerr == nil || rerr.Code != CodeOffline || !strings.Contains(rerr.Message, "mismatch") {
t.Fatalf("mismatched close = %+v", rerr)
}
if rig.s.sessions.get("1001") == nil {
t.Fatal("mismatched close removed the session")
}
}
func TestTerminalCloseRejectsBadArgs(t *testing.T) {
rig := newTermRig(t, "", "", true)
for _, args := range []string{
`{"session_id":"s-abcdef"}`, // missing id
`{"id":"abc","session_id":"s-abcdef"}`, // id not decimal
`{"id":"1001"}`, // missing session_id
} {
if _, rerr := rig.callClose(args); rerr == nil || rerr.Code != CodeInvalidParams {
t.Fatalf("%s: %+v", args, rerr)
}
}
}
// A terminal_close that lands while terminal_exec is waiting must wake that
// call: it delivers the bytes buffered so far and reports the shell gone.
func TestTerminalCloseInterruptsRunningCommand(t *testing.T) {
rig := newTermRig(t, "", "", true)
ch := rig.callAsync(`{"id":"1001","command":"ping -n 30 127.0.0.1","timeout_ms":5000}`)
_, _ = rig.nextCommandWire()
rig.feed("partial output\r\n")
sess := rig.s.sessions.get("1001")
if sess == nil {
t.Fatal("session missing while the command runs")
}
if out, rerr := rig.callClose(fmt.Sprintf(`{"id":"1001","session_id":%q}`, sess.id)); rerr != nil || !out.Closed {
t.Fatalf("close = %+v / %v", out, rerr)
}
res := rig.wait(ch)
if res.err != nil {
t.Fatalf("exec after close: %v", res.err)
}
if res.out.Stdout != "partial output" || !res.out.Done {
t.Fatalf("exec after close = %+v, want the buffered tail", res.out)
}
if res.out.ExitCode == nil || *res.out.ExitCode != -1 {
t.Fatalf("exit code = %+v, want -1", res.out.ExitCode)
}
if rig.s.sessions.get("1001") != nil {
t.Fatal("closed session still in the table")
}
}
// With no waiter, close discards the tail but still releases the device slot:
// the next poll reports the session gone rather than serving stale bytes.
func TestTerminalCloseWithoutWaiterReleasesSlot(t *testing.T) {
rig := newTermRig(t, "", "", true)
ch := rig.callAsync(`{"id":"1001","command":"ping -n 30 127.0.0.1","timeout_ms":100}`)
_, _ = rig.nextCommandWire()
first := rig.wait(ch)
if first.err != nil || first.out.Done {
t.Fatalf("first call = %+v / %v", first.out, first.err)
}
sid := first.out.SessionID
rig.feed("orphan\r\n")
if out, rerr := rig.callClose(fmt.Sprintf(`{"id":"1001","session_id":%q}`, sid)); rerr != nil || !out.Closed {
t.Fatalf("close = %+v / %v", out, rerr)
}
if rig.s.sessions.get("1001") != nil {
t.Fatal("closed session still in the table")
}
if rig.h.HasTerminalSession("1001") {
t.Fatal("closed session still holds the hub lease")
}
ch = rig.callAsync(fmt.Sprintf(`{"id":"1001","session_id":%q,"timeout_ms":100}`, sid))
res := rig.wait(ch)
if res.err == nil || res.err.Code != CodeOffline || !strings.Contains(res.err.Message, "not found") {
t.Fatalf("poll after close = %+v", res.err)
}
}
// A closed session must not keep the device slot: the very next command opens
// a fresh shell immediately.
func TestTerminalCloseAllowsImmediateReopen(t *testing.T) {
rig := newTermRig(t, "", "", true)
sid := rig.runToCompletion("echo one", "one").out.SessionID
if _, rerr := rig.callClose(fmt.Sprintf(`{"id":"1001","session_id":%q}`, sid)); rerr != nil {
t.Fatalf("close: %v", rerr)
}
start := time.Now()
res := rig.runToCompletion("echo two", "two")
if elapsed := time.Since(start); elapsed > time.Second {
t.Fatalf("reopen took %v, want under 1s", elapsed)
}
if res.out.SessionID == sid {
t.Fatalf("reopen reused the closed session id %q", sid)
}
if res.out.Stdout != "two" {
t.Fatalf("reopen output = %q", res.out.Stdout)
}
}
// terminal_close only knows MCP's own table: a shell the web console holds has
// no MCP session, so the call is a no-op for the hub lease.
func TestTerminalCloseLeavesBrowserSessionAlone(t *testing.T) {
rig := newTermRig(t, "", "", true)
if err := rig.h.OpenTerminalSession("1001"); err != nil {
t.Fatalf("browser open: %v", err)
}
if out, rerr := rig.callClose(`{"id":"1001","session_id":"s-abcdef"}`); rerr != nil || !out.Closed {
t.Fatalf("close = %+v / %v", out, rerr)
}
if !rig.h.HasTerminalSession("1001") {
t.Fatal("terminal_close released a browser-held lease")
}
}
// The HTTP layer must not make terminal_close wait on the per-device lock:
// an in-flight terminal_exec holds it for the whole call timeout.
func TestTerminalCloseIgnoresDeviceLock(t *testing.T) {
rig := newTermRig(t, "", "", true)
rig.runToCompletion("echo hello", "hello") // the session stays open after a finished command
sess := rig.s.sessions.get("1001")
if sess == nil {
t.Fatal("session missing")
}
if _, ok := rig.s.locks.tryAcquire("1001", "terminal_exec"); !ok {
t.Fatal("could not take the device lock")
}
defer rig.s.locks.release("1001")
if _, rerr := rig.s.callTool(context.Background(), json.RawMessage(
fmt.Sprintf(`{"name":"terminal_close","arguments":{"id":"1001","session_id":%q}}`, sess.id))); rerr != nil {
t.Fatalf("close through tools/call: %v", rerr)
}
if rig.s.sessions.get("1001") != nil {
t.Fatal("close through tools/call did not release the session")
}
}
+56 -2
View File
@@ -37,6 +37,28 @@ func GbkToUTF8(data []byte) string {
return cleanString(buf.String())
}
// UTF8ToGBK converts a Go string to the GBK bytes a client-side C string field
// expects. Every platform's file manager works on GBK on the wire: Windows uses
// the ANSI APIs (CP936), and the POSIX clients convert with iconv before
// sending (`gbkToUtf8` in common/FileManager.h). Bytes that GBK cannot
// represent are replaced; callers that care should check the round trip.
func UTF8ToGBK(s string) []byte {
if s == "" {
return nil
}
var buf bytes.Buffer
w := transform.NewWriter(&buf, simplifiedchinese.GBK.NewEncoder())
if _, err := w.Write([]byte(s)); err != nil {
// Unrepresentable input: fall back to the raw UTF-8 bytes, which is
// exactly what the C++ iconv helper does on failure.
return []byte(s)
}
if err := w.Close(); err != nil {
return []byte(s)
}
return buf.Bytes()
}
// Utf8CleanString trims at the first NUL and strips non-printables — the
// UTF-8 counterpart of GbkToUTF8 for clients that have the CLIENT_CAP_UTF8
// capability bit. Decoding as GBK in that case would mangle multi-byte
@@ -69,6 +91,17 @@ const (
ClientCapV2 uint32 = 0x0001 // CLIENT_CAP_V2 — V2 file transfer
ClientCapUTF8 uint32 = 0x0002 // CLIENT_CAP_UTF8 — UTF-8 protocol strings (activeWindow, key-log titles, ...)
ClientCapScreenPreview uint32 = 0x0004 // CLIENT_CAP_SCREEN_PREVIEW
ClientCapC2CPaths uint32 = 0x0008 // CLIENT_CAP_C2C_PATHS — path-list driven host-to-host transfer
// Bits 0x0010 (C2C recv ack), 0x0020 (protocol switch) and 0x0040
// (embedded anchor) are not consumed by the Go server yet. They are simply
// skipped by the constants below.
ClientCapVirtualDesktop uint32 = 0x0080 // CLIENT_CAP_VIRTUAL_DESKTOP — whole virtual desktop capture
ClientCapWindowInfo uint32 = 0x0100 // CLIENT_CAP_WINDOW_INFO — window enumeration / rects
ClientCapScreenRegion uint32 = 0x0200 // CLIENT_CAP_SCREEN_REGION — region/window/monitor capture
// CLIENT_CAP_TERMINAL is only declared by recent Android builds: Windows
// and Linux always had COMMAND_SHELL but never advertise it, so this bit
// must only gate the APK path (common/commands.h:151).
ClientCapTerminal uint32 = 0x8000 // CLIENT_CAP_TERMINAL — PTY shell sub-connection
)
// SupportsCap returns true when the client's reported capability hex string
@@ -104,6 +137,8 @@ func DecodeClientString(data []byte, capability, clientType string) string {
const (
// Server -> Client commands
CommandActived byte = 0 // COMMAND_ACTIVED
CommandListDrive byte = 1 // COMMAND_LIST_DRIVE - open the file-manager sub-conn and list drives
CommandListFiles byte = 2 // COMMAND_LIST_FILES - [cmd][path\0] on the file-manager sub-conn
CommandScreenSpy byte = 16 // COMMAND_SCREEN_SPY - start screen capture
CommandScreenControl byte = 20 // COMMAND_SCREEN_CONTROL - mouse/keyboard input (MSG64 batches)
CommandScreenGetClipboard byte = 24 // COMMAND_SCREEN_GET_CLIPBOARD - request remote clipboard (single byte)
@@ -113,6 +148,9 @@ const (
CommandUninstall byte = 63 // TOKEN_UNINSTALL - uninstall the host agent (single byte)
CommandTerminalRsize byte = 81 // CMD_TERMINAL_RESIZE - [cmd:1][cols:2 LE][rows:2 LE]
CmdRestoreConsole byte = 82 // CMD_RESTORE_CONSOLE - RDP session "归位": switch back to the console session and restart capture
CommandSendFileV2 byte = 85 // COMMAND_SEND_FILE_V2 - one V2 file chunk (77-byte packed header + name + data)
CommandFileCompleteV2 byte = 91 // COMMAND_FILE_COMPLETE_V2 - end of one V2 file, carries its SHA-256
CmdDownFilesV2 byte = 94 // CMD_DOWN_FILES_V2 - [cmd][targetDir\0][path\0][\0] on the file-manager sub-conn
CommandScreenKeyframeReq byte = 169 // COMMAND_SCREEN_KEYFRAME_REQ - force the client to emit an IDR immediately
CommandBye byte = 204 // COMMAND_BYE - disconnect
CommandHeartbeat byte = 216 // CMD_HEARTBEAT_ACK
@@ -121,17 +159,33 @@ const (
TokenAuth byte = 100 // TOKEN_AUTH - authorization required
TokenHeartbeat byte = 101 // TOKEN_HEARTBEAT
TokenLogin byte = 102 // TOKEN_LOGIN - login packet
TokenDriveList byte = 103 // TOKEN_DRIVE_LIST - file-manager sub-conn first packet, drive records
TokenFileList byte = 104 // TOKEN_FILE_LIST - one directory's entries, [token] + records
TokenBitmapInfo byte = 115 // TOKEN_BITMAPINFO - screen sub-connection header
TokenFirstScreen byte = 116 // TOKEN_FIRSTSCREEN - raw BGRA baseline frame (NOT H264)
TokenNextScreen byte = 117 // TOKEN_NEXTSCREEN - non-keyframe H264 (P-frame)
TokenClipboardText byte = 118 // TOKEN_CLIPBOARD_TEXT - remote clipboard text [118][UTF-8][NUL]
TokenShellStart byte = 128 // TOKEN_SHELL_START - legacy cmd-pipe shell sub-conn open
TokenKeyframe byte = 134 // TOKEN_KEYFRAME - H264 IDR (sent on GOP boundary)
// TOKEN_FILE_LIST_ERROR is the modern clients' structured "cannot list this
// directory" reply: [token:1][win32err:4 LE]. Legacy clients send nothing,
// which the server can only report as a timeout.
TokenFileListError byte = 171 // TOKEN_FILE_LIST_ERROR - directory listing failed
// TOKEN_DOWNLOAD_ERROR is the file-manager sub-conn's "nothing to send"
// reply to CMD_DOWN_FILES_V2: [token:1][win32err:4 LE]. The transfer sub-conn
// is not created in that case, so this is the only failure signal.
TokenDownloadError byte = 173 // TOKEN_DOWNLOAD_ERROR - download request rejected
TokenTerminalStart byte = 232 // TOKEN_TERMINAL_START - modern PTY shell sub-conn open
TokenTerminalClose byte = 233 // TOKEN_TERMINAL_CLOSE - shell exited / close ack
TokenConnAuth byte = 246 // TOKEN_CONN_AUTH - sub-connection identity handshake
CmdCursorImage byte = 93 // CMD_CURSOR_IMAGE - custom cursor bitmap (Phase 5+ feature)
CmdSockDllLoader byte = 210 // SOCKET_DLLLOADER - shellcode/memory-DLL loader requests the full DLL payload
// COMMAND_SCREEN_PREVIEW_REQ / TOKEN_SCREEN_PREVIEW_RSP are a main-connection
// RPC pair: the client captures, scales and JPEG-encodes a frame itself. It
// opens no sub-connection and holds no screen-session slot, so it can run
// alongside a live screen viewer (design §7.1).
CommandScreenPreviewReq byte = 247 // COMMAND_SCREEN_PREVIEW_REQ - [cmd:1][reqId:2][maxWidth:2][quality:1][reserved:2]
TokenScreenPreviewRsp byte = 248 // TOKEN_SCREEN_PREVIEW_RSP - [token:1][reqId:2][status:1][format:1][w:2][h:2][bytes:4][reserved:3][data]
CmdCursorImage byte = 93 // CMD_CURSOR_IMAGE - custom cursor bitmap (Phase 5+ feature)
CmdSockDllLoader byte = 210 // SOCKET_DLLLOADER - shellcode/memory-DLL loader requests the full DLL payload
)
// HeartbeatACK (CMD_HEARTBEAT_ACK) response layout — mirrors the HeartbeatACK
+59 -1
View File
@@ -1,6 +1,13 @@
package protocol
import "testing"
import (
"go/ast"
"go/parser"
"go/token"
"strconv"
"strings"
"testing"
)
func TestSignMessageHMACVector(t *testing.T) {
// Standard HMAC-SHA256 sanity vector. Anchors that SignMessage matches
@@ -45,3 +52,54 @@ func TestIsH264KeyframeBasic(t *testing.T) {
t.Fatal("non-H264 bytes should not match")
}
}
// TestCommandTokenConstantsAreUnique guards the command/token byte values in
// commands.go against a silent collision. The tokens are matched against the
// first byte of every inbound packet, so two names sharing a value means the
// wrong handler eats the packet — an added file-manager token that reuses
// TOKEN_LOGIN's value would swallow the device's login. Constants outside the
// Command*/Token*/Cmd* families are skipped: the file also defines field
// offsets, which legitimately repeat small numbers (offset 1 in two packets).
func TestCommandTokenConstantsAreUnique(t *testing.T) {
fset := token.NewFileSet()
file, err := parser.ParseFile(fset, "commands.go", nil, 0)
if err != nil {
t.Fatalf("parse commands.go: %v", err)
}
seen := make(map[int64]string)
ast.Inspect(file, func(n ast.Node) bool {
spec, ok := n.(*ast.ValueSpec)
if !ok {
return true
}
for i, name := range spec.Names {
// A name without its own expression repeats the previous value.
if i >= len(spec.Values) || !isCommandTokenName(name.Name) {
continue
}
lit, ok := spec.Values[i].(*ast.BasicLit)
if !ok || lit.Kind != token.INT {
continue
}
v, err := strconv.ParseInt(lit.Value, 0, 64)
if err != nil {
continue
}
if prev, dup := seen[v]; dup {
t.Errorf("%s and %s both use %d", prev, name.Name, v)
continue
}
seen[v] = name.Name
}
return true
})
if len(seen) < 20 {
t.Fatalf("only %d command/token constants scanned; did commands.go change shape?", len(seen))
}
}
func isCommandTokenName(name string) bool {
return strings.HasPrefix(name, "Command") ||
strings.HasPrefix(name, "Token") ||
strings.HasPrefix(name, "Cmd")
}
+13 -250
View File
@@ -1,57 +1,21 @@
package web
import (
"bufio"
"encoding/json"
"os"
"strings"
"time"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/auditquery"
)
// Audit-log query support for the admin-only "Audit Log" page.
//
// The server reads its own JSON-lines audit file (logs/audit.log) back to the
// browser. Records are already redacted at write time (see logger.AuditAt), so
// returning raw lines is safe as long as we never widen what is written.
//
// Only the CURRENT audit file is searched. Rotated files (audit-*.log[.gz])
// are deliberately out of scope: they need gzip support and a separate index,
// and the UI is meant for recent-window triage ("what happened just now").
const (
auditQueryDefaultLimit = 100
auditQueryMaxLimit = 500
auditQueryMaxOffset = 10000
// The scanner itself (file tail, filters, paging) lives in package
// auditquery so the MCP get_audit_log tool can share it; this file keeps only
// the WebSocket command handler and the reply shaping specific to the UI.
// auditQueryScanBudget bounds how much of the audit file a single query
// reads. The tail is read when the file is larger, so the newest records
// (what operators actually triage) are always covered and a multi-GB log
// cannot stall the WS goroutine.
auditQueryScanBudget = 32 << 20 // 32 MB
)
// auditQueryRequest is the JSON body of the `query_audit` command.
type auditQueryRequest struct {
From string `json:"from"` // RFC3339 ("2026-10-18T10:00:00Z"), optional
To string `json:"to"` // RFC3339, optional
Event string `json:"event"` // exact ("web.login.failure"), prefix ("web." / "web.*"), or ""
Actor string `json:"actor"` // exact, case-insensitive
IP string `json:"ip"` // exact
DeviceID string `json:"device_id"`
Keyword string `json:"keyword"` // case-insensitive substring of the raw record
WarnOnly bool `json:"warn_only"` // only level=warn records
Limit int `json:"limit"`
Offset int `json:"offset"` // skip the newest N matching records
}
// auditQueryResult is the internal result of scanning the audit file.
type auditQueryResult struct {
Events []map[string]any
Total int // matching records in the scanned window
FileExists bool
FileSize int64
ScannedBytes int64
Truncated bool // the file was larger than auditQueryScanBudget
}
// auditQueryMaxLimit caps the page size of the audit page. It is tighter than
// auditquery.MaxLimit (the protocol-wide cap the MCP tool uses) because the
// admin table is meant to be paged, not downloaded.
const auditQueryMaxLimit = 500
// handleQueryAudit implements the admin-only audit query command. The reply is
// `{cmd:"audit_result", ok, events, total, ...}`; events are newest-first.
@@ -60,13 +24,13 @@ func (h *wsHub) handleQueryAudit(c *wsClient, raw []byte) {
if !h.requireAdmin(c, raw, replyCmd) {
return
}
var in auditQueryRequest
var in auditquery.Query
if err := json.Unmarshal(raw, &in); err != nil {
c.queue(mustJSON(map[string]any{"cmd": replyCmd, "ok": false, "msg": "Invalid request"}))
return
}
in.Limit = clampAuditLimit(in.Limit)
in.Offset = clampAuditOffset(in.Offset)
in.Limit = auditquery.ClampLimit(in.Limit, auditQueryMaxLimit)
in.Offset = auditquery.ClampOffset(in.Offset)
path := h.log.AuditPath()
if path == "" {
@@ -81,7 +45,7 @@ func (h *wsHub) handleQueryAudit(c *wsClient, raw []byte) {
return
}
res, err := queryAuditLog(path, in)
res, err := auditquery.Scan(path, in)
if err != nil {
h.audit(c, true, auditQuery, map[string]any{
"ok": false,
@@ -125,204 +89,3 @@ func (h *wsHub) handleQueryAudit(c *wsClient, raw []byte) {
"truncated": res.Truncated,
}))
}
func clampAuditLimit(n int) int {
if n <= 0 {
return auditQueryDefaultLimit
}
if n > auditQueryMaxLimit {
return auditQueryMaxLimit
}
return n
}
func clampAuditOffset(n int) int {
if n < 0 {
return 0
}
if n > auditQueryMaxOffset {
return auditQueryMaxOffset
}
return n
}
// queryAuditLog scans path for audit records matching q. The returned events
// are the newest limit records after skipping offset, in newest-first order.
func queryAuditLog(path string, q auditQueryRequest) (auditQueryResult, error) {
res := auditQueryResult{Events: []map[string]any{}}
f, err := os.Open(path)
if err != nil {
if os.IsNotExist(err) {
// No audit record has been written yet (lumberjack creates the file
// lazily). An empty result is correct, not an error.
return res, nil
}
return res, err
}
defer f.Close()
info, err := f.Stat()
if err != nil {
return res, err
}
res.FileExists = true
res.FileSize = info.Size()
// For very large files, scan only the tail; the newest matches live there.
start := int64(0)
if info.Size() > auditQueryScanBudget {
start = info.Size() - auditQueryScanBudget
if _, err := f.Seek(start, 0); err != nil {
return res, err
}
res.Truncated = true
}
from, hasFrom := parseAuditTime(q.From)
to, hasTo := parseAuditTime(q.To)
keep := q.Offset + q.Limit
ring := make([]map[string]any, keep)
filled := 0
sc := bufio.NewScanner(f)
// Sanitized values are capped at 4096 bytes each; a record with many
// fields stays well under 1 MB. Allow headroom rather than aborting the
// whole query on one long line.
sc.Buffer(make([]byte, 64*1024), 4*1024*1024)
first := true
for sc.Scan() {
line := sc.Text()
if start > 0 && first {
// Seeking into the middle of the file lands mid-line. Drop that
// partial record.
first = false
continue
}
first = false
res.ScannedBytes += int64(len(line)) + 1
line = strings.TrimSpace(line)
if line == "" {
continue
}
var rec map[string]any
if err := json.Unmarshal([]byte(line), &rec); err != nil {
continue // tolerate a torn line instead of failing the page
}
if _, ok := rec["event"].(string); !ok {
continue
}
// Only audit records belong on the page. The dedicated file contains
// nothing else, but a hand-edited or mixed file must not surface
// ordinary operational lines here.
if rec["audit"] != true {
continue
}
if !auditRecordMatches(rec, line, q, from, hasFrom, to, hasTo) {
continue
}
// Ring buffer of the last `keep` matches (file order is chronological).
ring[res.Total%keep] = rec
if filled < keep {
filled++
}
res.Total++
}
if err := sc.Err(); err != nil {
return res, err
}
// Newest first, skipping Offset. The match with 0-based index i lives at
// ring[i%keep] as long as i >= Total-filled.
for i := res.Total - 1 - q.Offset; i >= 0 && i >= res.Total-filled; i-- {
res.Events = append(res.Events, ring[i%keep])
if len(res.Events) >= q.Limit {
break
}
}
return res, nil
}
// auditRecordMatches applies the non-time and time filters to one record.
// line is the raw JSON line, used for the keyword substring search.
func auditRecordMatches(rec map[string]any, line string, q auditQueryRequest, from time.Time, hasFrom bool, to time.Time, hasTo bool) bool {
if q.Event != "" && !auditEventFilterMatches(q.Event, auditStringField(rec, "event")) {
return false
}
if q.Actor != "" && !strings.EqualFold(auditStringField(rec, "actor"), q.Actor) {
return false
}
if q.IP != "" && auditStringField(rec, "ip") != q.IP {
return false
}
if q.DeviceID != "" && auditStringField(rec, "device_id") != q.DeviceID {
return false
}
if q.WarnOnly && auditStringField(rec, "level") != "warn" {
return false
}
if q.Keyword != "" && !strings.Contains(strings.ToLower(line), strings.ToLower(q.Keyword)) {
return false
}
if hasFrom || hasTo {
t, ok := parseAuditTime(auditStringField(rec, "time"))
if !ok {
return false // cannot prove it is in range
}
if hasFrom && t.Before(from) {
return false
}
if hasTo && t.After(to) {
return false
}
}
return true
}
// auditEventFilterMatches supports three forms so the UI stays simple:
//
// "web.login.failure" exact
// "web.*" prefix (trailing "*")
// "web." prefix (trailing ".")
func auditEventFilterMatches(filter, event string) bool {
switch {
case strings.HasSuffix(filter, "*"):
return strings.HasPrefix(event, strings.TrimSuffix(filter, "*"))
case strings.HasSuffix(filter, "."):
return strings.HasPrefix(event, filter)
default:
return event == filter
}
}
func auditStringField(rec map[string]any, key string) string {
s, _ := rec[key].(string)
return s
}
// parseAuditTime accepts the formats operators and browsers realistically send.
// Layouts without an explicit zone are parsed as UTC; the frontend always sends
// Date.toISOString(), so the RFC3339 path is what production uses.
func parseAuditTime(s string) (time.Time, bool) {
s = strings.TrimSpace(s)
if s == "" {
return time.Time{}, false
}
layouts := []string{
time.RFC3339Nano,
time.RFC3339,
"2006-01-02T15:04:05",
"2006-01-02T15:04",
"2006-01-02 15:04:05",
"2006-01-02",
}
for _, layout := range layouts {
if t, err := time.Parse(layout, s); err == nil {
return t, true
}
}
return time.Time{}, false
}
+5 -185
View File
@@ -2,17 +2,20 @@ package web
import (
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/auditquery"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/hub"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/logger"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/wsauth"
)
// The scanner has its own tests in package auditquery; this file covers the
// WebSocket command handler and its reply shape.
// newAuditTestHubWithoutAuditFile builds a hub whose logger has no dedicated
// audit file, mirroring a server started with YAMA_AUDIT_LOG=off.
func newAuditTestHubWithoutAuditFile(t *testing.T, dir string) (*wsHub, string) {
@@ -43,189 +46,6 @@ func readQueuedJSON(t *testing.T, c *wsClient) map[string]any {
}
}
// writeAuditFixture writes JSON-lines audit records (oldest first) and returns
// the file path. Times are UTC RFC3339 so the tests are timezone-independent.
func writeAuditFixture(t *testing.T, records []map[string]any) string {
t.Helper()
path := filepath.Join(t.TempDir(), "audit.log")
var b strings.Builder
for _, rec := range records {
line, err := json.Marshal(rec)
if err != nil {
t.Fatalf("marshal fixture: %v", err)
}
b.Write(line)
b.WriteByte('\n')
}
if err := os.WriteFile(path, []byte(b.String()), 0o644); err != nil {
t.Fatalf("write fixture: %v", err)
}
return path
}
func auditFixtureRecords() []map[string]any {
at := func(hhmm string) string {
tm, err := time.Parse("2006-01-02T15:04", "2026-10-18T"+hhmm)
if err != nil {
panic(err)
}
return tm.Format(time.RFC3339)
}
return []map[string]any{
{"level": "info", "time": at("10:00"), "audit": true, "event": "web.login.success", "actor": "admin", "ip": "203.0.113.1"},
{"level": "warn", "time": at("10:01"), "audit": true, "event": "web.login.failure", "actor": "alice", "ip": "203.0.113.2", "reason": "invalid_credentials"},
{"level": "info", "time": at("10:02"), "audit": true, "event": "remote.screen.start", "actor": "admin", "role": "admin", "ip": "203.0.113.1", "device_id": "dev1"},
{"level": "info", "time": at("10:03"), "audit": true, "event": "admin.user.delete", "actor": "admin", "ip": "203.0.113.1", "target": "bob"},
}
}
func runAuditQuery(t *testing.T, path string, q auditQueryRequest) auditQueryResult {
t.Helper()
q.Limit = clampAuditLimit(q.Limit)
q.Offset = clampAuditOffset(q.Offset)
res, err := queryAuditLog(path, q)
if err != nil {
t.Fatalf("queryAuditLog: %v", err)
}
return res
}
func eventNames(res auditQueryResult) []string {
out := make([]string, 0, len(res.Events))
for _, e := range res.Events {
out = append(out, auditStringField(e, "event"))
}
return out
}
func TestAuditQueryNoFilterNewestFirst(t *testing.T) {
path := writeAuditFixture(t, auditFixtureRecords())
res := runAuditQuery(t, path, auditQueryRequest{Limit: 100})
if res.Total != 4 || len(res.Events) != 4 {
t.Fatalf("total=%d events=%d, want 4/4", res.Total, len(res.Events))
}
got := eventNames(res)
want := []string{"admin.user.delete", "remote.screen.start", "web.login.failure", "web.login.success"}
if strings.Join(got, ",") != strings.Join(want, ",") {
t.Fatalf("events = %v, want %v", got, want)
}
}
func TestAuditQueryEventFilters(t *testing.T) {
path := writeAuditFixture(t, auditFixtureRecords())
cases := []struct {
filter string
want []string
}{
{"web.", []string{"web.login.failure", "web.login.success"}},
{"web.*", []string{"web.login.failure", "web.login.success"}},
{"web.login.failure", []string{"web.login.failure"}},
{"remote.*", []string{"remote.screen.start"}},
}
for _, tc := range cases {
res := runAuditQuery(t, path, auditQueryRequest{Event: tc.filter, Limit: 100})
got := eventNames(res)
if strings.Join(got, ",") != strings.Join(tc.want, ",") {
t.Errorf("filter %q → %v, want %v", tc.filter, got, tc.want)
}
}
}
func TestAuditQueryFieldFilters(t *testing.T) {
path := writeAuditFixture(t, auditFixtureRecords())
from, _ := time.Parse(time.RFC3339, "2026-10-18T10:01:00Z")
to, _ := time.Parse(time.RFC3339, "2026-10-18T10:02:00Z")
cases := []struct {
name string
q auditQueryRequest
want []string
}{
{"actor case-insensitive", auditQueryRequest{Actor: "ALICE", Limit: 100}, []string{"web.login.failure"}},
{"ip", auditQueryRequest{IP: "203.0.113.2", Limit: 100}, []string{"web.login.failure"}},
{"device", auditQueryRequest{DeviceID: "dev1", Limit: 100}, []string{"remote.screen.start"}},
{"warn only", auditQueryRequest{WarnOnly: true, Limit: 100}, []string{"web.login.failure"}},
{"keyword target", auditQueryRequest{Keyword: "BOB", Limit: 100}, []string{"admin.user.delete"}},
{"time range", auditQueryRequest{
From: from.Format(time.RFC3339), To: to.Format(time.RFC3339), Limit: 100,
}, []string{"remote.screen.start", "web.login.failure"}},
}
for _, tc := range cases {
res := runAuditQuery(t, path, tc.q)
got := eventNames(res)
if strings.Join(got, ",") != strings.Join(tc.want, ",") {
t.Errorf("%s → %v, want %v", tc.name, got, tc.want)
}
}
}
func TestAuditQueryOffsetAndLimit(t *testing.T) {
path := writeAuditFixture(t, auditFixtureRecords())
res := runAuditQuery(t, path, auditQueryRequest{Limit: 2, Offset: 1})
if res.Total != 4 {
t.Fatalf("total = %d, want 4", res.Total)
}
got := eventNames(res)
want := []string{"remote.screen.start", "web.login.failure"}
if strings.Join(got, ",") != strings.Join(want, ",") {
t.Fatalf("events = %v, want %v", got, want)
}
// Offsetting past the end yields no events but keeps the total.
res = runAuditQuery(t, path, auditQueryRequest{Limit: 2, Offset: 4})
if res.Total != 4 || len(res.Events) != 0 {
t.Fatalf("offset past end: total=%d events=%v", res.Total, eventNames(res))
}
}
func TestAuditQuerySkipsNonAuditAndTornLines(t *testing.T) {
path := filepath.Join(t.TempDir(), "audit.log")
content := `{"event":"device.online","actor":"x"}
not json at all
{"level":"info","time":"2026-10-18T10:00:00Z","audit":true,"event":"web.login.success","actor":"admin"}`
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
t.Fatal(err)
}
res := runAuditQuery(t, path, auditQueryRequest{Limit: 100})
if res.Total != 1 || len(res.Events) != 1 {
t.Fatalf("total=%d events=%v, want the single valid record", res.Total, eventNames(res))
}
}
func TestAuditQueryMissingFile(t *testing.T) {
res := runAuditQuery(t, filepath.Join(t.TempDir(), "does-not-exist.log"), auditQueryRequest{Limit: 10})
if res.FileExists {
t.Error("FileExists = true for a missing file")
}
if res.Total != 0 || len(res.Events) != 0 {
t.Errorf("total=%d events=%v, want empty", res.Total, eventNames(res))
}
if res.Events == nil {
t.Error("Events is nil; JSON would encode null instead of []")
}
}
func TestAuditQueryClampsPaging(t *testing.T) {
if got := clampAuditLimit(0); got != auditQueryDefaultLimit {
t.Errorf("limit(0) = %d, want default %d", got, auditQueryDefaultLimit)
}
if got := clampAuditLimit(-3); got != auditQueryDefaultLimit {
t.Errorf("limit(-3) = %d, want default %d", got, auditQueryDefaultLimit)
}
if got := clampAuditLimit(9999); got != auditQueryMaxLimit {
t.Errorf("limit(9999) = %d, want max %d", got, auditQueryMaxLimit)
}
if got := clampAuditLimit(50); got != 50 {
t.Errorf("limit(50) = %d, want 50", got)
}
if got := clampAuditOffset(-5); got != 0 {
t.Errorf("offset(-5) = %d, want 0", got)
}
if got := clampAuditOffset(1 << 30); got != auditQueryMaxOffset {
t.Errorf("offset(huge) = %d, want max %d", got, auditQueryMaxOffset)
}
}
func TestQueryAuditHandlerAdminOnly(t *testing.T) {
wh, _, _ := auditTestHub(t)
viewer, tok := auditTestClient(wh, "viewer")
@@ -265,7 +85,7 @@ func TestQueryAuditHandlerReturnsEvents(t *testing.T) {
var names []string
for _, e := range events {
if m, ok := e.(map[string]any); ok {
names = append(names, auditStringField(m, "event"))
names = append(names, auditquery.StringField(m, "event"))
}
}
joined := strings.Join(names, ",")
+32 -4
View File
@@ -36,14 +36,23 @@ type Server struct {
allowedOrigins []string // for WS Origin allowlist; empty = same-origin only
loginIPLimit *wsauth.RateLimiter
loginUserLimit *wsauth.RateLimiter
trustForwardedFor bool // honor X-Forwarded-For (behind trusted proxy only)
basePath string // web UI mount prefix (e.g. "/remoter"); "" = domain root
brandName string // white-label title; "" = "SimpleRemoter" (official branding)
sso SSODetector // nil = SSO disabled
trustForwardedFor bool // honor X-Forwarded-For (behind trusted proxy only)
basePath string // web UI mount prefix (e.g. "/remoter"); "" = domain root
brandName string // white-label title; "" = "SimpleRemoter" (official branding)
sso SSODetector // nil = SSO disabled
mcp mcpEndpoint // nil = no /mcp route
sweepDone chan struct{} // closes to stop the login-limiter sweeper
sweepStopOnce sync.Once
}
// mcpEndpoint is the part of *mcp.Server the web server mounts. Expressed as
// an interface so web does not depend on the mcp package (the endpoint owns
// its own auth and protocol; web only routes to it).
type mcpEndpoint interface {
Handle(http.ResponseWriter, *http.Request)
Enabled() bool
}
// Config tunes the server's exposed-on-public-HTTPS hardening knobs.
// All fields are optional; zero values pick reasonable defaults.
type Config struct {
@@ -109,6 +118,15 @@ func (s *Server) WithConfig(cfg Config) *Server {
return s
}
// WithMCP attaches the MCP endpoint under /mcp (basePath-aware via mount).
// When the endpoint reports itself disabled (no bearer token) the route is not
// registered and /mcp 404s, matching "no token = feature off". Safe to call
// before Start.
func (s *Server) WithMCP(m mcpEndpoint) *Server {
s.mcp = m
return s
}
// Start launches the server in a goroutine and returns immediately.
// If port is 0, returns nil without starting anything.
func (s *Server) Start() error {
@@ -129,6 +147,16 @@ func (s *Server) Start() error {
mux.HandleFunc("/api/devices", s.requireBearer(s.handleDevices))
mux.HandleFunc("/sso", s.handleSSO)
mux.HandleFunc("/ws", s.ws.serve)
// MCP is its own protocol with its own static bearer token; it does not go
// through requireBearer (that validates browser sessions). Mounted inside
// the mux so basePath stripping applies like every other route.
if s.mcp != nil {
if s.mcp.Enabled() {
mux.HandleFunc("/mcp", s.mcp.Handle)
} else {
s.log.Info("MCP endpoint disabled: YAMA_MCP_TOKEN not set")
}
}
mux.HandleFunc("/static/xterm.js", staticHandler(xtermJS, "application/javascript; charset=utf-8"))
mux.HandleFunc("/static/xterm.css", staticHandler(xtermCSS, "text/css; charset=utf-8"))
mux.HandleFunc("/static/xterm-fit.js", staticHandler(xtermFitJS, "application/javascript; charset=utf-8"))
+2 -2
View File
@@ -265,7 +265,7 @@ $auditFiltered = Rpc '' $null 'get_audit_log' @{ type = 'zzz-no-such-type'; limi
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
$st = $status.result.structuredContent
Check 'get_server_status 正常返回' ($status.error -eq $null -and $null -ne $st)
$basePort = 6544
if ($Base -match ':(\d+)(/|$)') { $basePort = [int]$Matches[1] }
@@ -806,7 +806,7 @@ if (-not $longCall) {
([int]$jr.error.code -eq -32800)) $body
# 交叉核对:get_server_status 的 sessions.pending 应回到 0,主机能再次正常调用
$st2 = (Rpc '' $null 'get_server_status' @{}).result.structuredContent.status
$st2 = (Rpc '' $null 'get_server_status' @{}).result.structuredContent
Check '取消后 get_server_status 无挂起(sessions.pending=0)' `
([int]$st2.sessions.pending -eq 0) ("pending=" + $st2.sessions.pending)
if (HasTool 'list_processes') {
+32 -12
View File
@@ -14,7 +14,8 @@ inputSchema、outputSchema,以及运行时不可见的开关元信息(`gate`
| `mcp/tools.json` | 工具清单本体(生成产物,勿手工编辑) |
| `tools/mcp_tools/dump_tools.py` | 从运行中的服务端抓 `tools/list` |
| `tools/mcp_tools/make_tools_json.py` | 把抓取结果转成 `tools.json`(含 gate / platforms 表) |
| `tools/mcp_tools/verify_tools.py` | 校验 `tools.json` 与服务端是否一致 |
| `tools/mcp_tools/verify_tools.py` | 校验 `tools.json` 与服务端是否一致(含 Go 端 `--subset`) |
| `tools/mcp_tools/gen_go_tools.py` | 从 `tools.json` 抽取 Go 端 9 个工具,生成 `server/go/mcp/tools_minimal.json` |
| `tools/mcp_tools/check_platform_table.py` | 校验 `tools.json` 的 `platforms` 与 C++ `kToolPlatforms` 一致 |
## 更新流程
@@ -87,14 +88,17 @@ python tools/mcp_tools/verify_tools.py --live mcp/tools.json
| 命令分支 | `client/`、`linux/main.cpp`、`macos/main.mm`、`android/app/src/main/cpp/main.cpp` |
| 能力位 | `common/commands.h` 的 `LOGIN_INFOR::DefaultCaps()`;Linux 另在 `linux/main.cpp:RefreshLoginCaps` 追加 `SCREEN_PREVIEW` |
当前分布(61 个工具):
当前分布(54 个工具):
| platforms | 数量 | 典型工具 |
|---|---|---|
| `win+lnx+mac+apk` | 10 | 只读写服务端本地数据:`list_online_hosts` / `get_audit_log` / `mcp_*` |
| `win+lnx+mac` | 6 | 进程列表、文件列取、日志、V2 文件传输、`copy_files_c2c` |
| `win+lnx` | 12 | `remote_*` 全族、`get_screenshot`、`get_activity_history`、`exec_command` / `terminal_*` / `kill_process` |
| `win` | 33 | 服务 / 注册表 / 键日志 / 文件写 / **`list_windows`** / `get_foreground_window` / `host_*` / `chat_*` / `power_action` |
| `win+lnx+mac+apk` | 9 | 只读写服务端本地数据:`list_hosts` / `get_host_detail` / `get_client_log` / `get_audit_log` / `get_server_status` / `mcp_*` / `host_set_remark` / `host_set_watch_level` |
| `win+lnx+apk` | 11 | `remote_*` 全族、`exec_command` / `terminal_*`、`get_screenshot`、`get_activity_history` |
| `win+lnx+mac` | 6 | 进程列表、文件列取 / V2 文件传输(含 `read_file`)、`copy_files_c2c` |
| `win+lnx` | 2 | `http_probe`、`kill_process` |
| `win+apk` | 6 | `remote_block_input`、`uninstall_host`、`chat_*` 全族 |
| `win` | 19 | 服务 / 注册表 / 键日志 / 文件搜索与写入 / **`list_windows`** / `get_foreground_window` / `host_inspect` / `host_control_*` / `operate_window` / 网络连接 / `power_action` |
| `apk` | 1 | `remote_lock_screen` |
**注意 `exec_command` / `terminal_*` / `kill_process` 不在 `win+lnx+mac` 组**:
macOS 客户端其实有对应实现(`macos/main.mm:753` 的 `ShellworkingThread` 跑 PTY,
@@ -106,8 +110,9 @@ macOS 客户端其实有对应实现(`macos/main.mm:753` 的 `ShellworkingThre
`SystemManager.h:38` 和 macOS 的 `SystemManager.mm:39` 都有 `COMMAND_WSLIST`
的 `case` 分支,看起来是支持的。但 `BuildListWindows` 把命令发在**主连接**上
(`McpServer.cpp:2931`),而这两个平台的主循环只处理 `COMMAND_SYSTEM`
(起 SystemManager 子连接),`WSLIST` 在子连接里才被处理——走不到。实测 Linux
上直接超时 `-32001`。那两个 `case` 是给 SystemDlg 窗口管理用的,不是 MCP 这条路径。
(起 SystemManager 子连接),`WSLIST` 在子连接里才被处理——走不到。关掉平台门禁
(`McpPlatformGuard=0`)时实测 Linux 上直接超时 `-32001`;默认门禁开启时,这张表
会先拦下并返回 `-32005`。那两个 `case` 是给 SystemDlg 窗口管理用的,不是 MCP 这条路径。
Windows 是在主循环里处理的(`client/KernelManager.cpp:1491`),所以正常。
### 平台优先级(产品定位)
@@ -191,11 +196,26 @@ python tools/mcp_tools/check_platform_table.py
## 与 Go 服务端的关系
`impl` 字段就是给 Go 端裁剪用的:标 `mfc` 的工具表示 Go 端还没有对应能力。
Go 端补齐某个工具的底层命令后,把它改成 `both`。
Go 最小服务端(`server/go`,设计见 `docs/Mcp_Go_Minimal_Design.md`)实现 9 个工具。
它的 `tools/list` **不是手写的**:`gen_go_tools.py` 从 `tools.json` 原样抽取这 9 个工具
生成 `server/go/mcp/tools_minimal.json`,再由 `//go:embed` 编进二进制。
注意 Go 端目前只有 5 类客户端命令(`SCREEN_SPY` / `NEXT` / `SCREEN_CONTROL` /
`BYE` / `SHELL`),所以短期内 `impl: both` 的工具不会多。
改完 `tools.json` 之后:
```bash
# 重新生成嵌入副本(--check 只检查是否为最新,CI 友好)
python tools/mcp_tools/gen_go_tools.py
python tools/mcp_tools/gen_go_tools.py --check
# 抓 Go 端线上 tools/list,与 tools.json 逐字段比对
# 读写模式恰好 9 个;YAMA_MCP_READONLY=1 时恰好 7 个(隐藏 terminal_*)
python tools/mcp_tools/verify_tools.py --subset mcp/tools.json <token> <port>
python tools/mcp_tools/verify_tools.py --subset mcp/tools.json <token> <port> --readonly
```
`--subset` 与 `--live` 的差别:前者**名字集合必须恰好等于** 9(或 7),多一个少一个
都失败;后者只报双方差异。`impl` 字段的 `mfc` / `go` / `both` 目前仍是人工维护的
元信息,脚本不据此推断。
## 前置条件
+104
View File
@@ -0,0 +1,104 @@
#!/usr/bin/env python3
"""Generate server/go/mcp/tools_minimal.json from mcp/tools.json.
The Go server embeds its tools/list payload, so the nine tools it exposes must
be a byte-for-byte copy of the canonical schemas. This script extracts them
without hand-editing, preserving tools.json order, and keeps only the four
fields MCP publishes: name / description / inputSchema / outputSchema.
Usage:
python tools/mcp_tools/gen_go_tools.py # rewrite the embedded file
python tools/mcp_tools/gen_go_tools.py --check # exit 1 if it is stale
Run from anywhere; paths are resolved relative to this file.
"""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
# The nine tools of the Go minimal server (design §3.1). Order in the embedded
# file follows mcp/tools.json, not this list.
MINIMAL_TOOLS = (
"list_hosts",
"get_host_detail",
"get_screenshot",
"list_files",
"get_audit_log",
"get_server_status",
"terminal_exec",
"terminal_close",
"read_file",
)
OUTPUT_FIELDS = ("name", "description", "inputSchema", "outputSchema")
REPO_ROOT = Path(__file__).resolve().parents[2]
TOOLS_JSON = REPO_ROOT / "mcp" / "tools.json"
OUTPUT_JSON = REPO_ROOT / "server" / "go" / "mcp" / "tools_minimal.json"
def render() -> str:
with TOOLS_JSON.open(encoding="utf-8") as f:
doc = json.load(f)
tools = doc["tools"] if isinstance(doc, dict) else doc
by_name = {}
for tool in tools:
name = tool.get("name")
if name in by_name:
raise SystemExit(f"duplicate tool name in {TOOLS_JSON}: {name}")
by_name[name] = tool
missing = [n for n in MINIMAL_TOOLS if n not in by_name]
if missing:
raise SystemExit(f"tools missing from {TOOLS_JSON}: {', '.join(missing)}")
minimal = []
for tool in tools:
if tool["name"] not in MINIMAL_TOOLS:
continue
minimal.append({field: tool[field] for field in OUTPUT_FIELDS})
if len(minimal) != len(MINIMAL_TOOLS):
raise SystemExit(
f"expected {len(MINIMAL_TOOLS)} tools, got {len(minimal)}"
)
return json.dumps(minimal, ensure_ascii=False, indent=2) + "\n"
def main(argv: list[str]) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--check",
action="store_true",
help="do not write; exit 1 when tools_minimal.json is out of date",
)
args = parser.parse_args(argv)
want = render()
if args.check:
try:
current = OUTPUT_JSON.read_text(encoding="utf-8")
except FileNotFoundError:
print(f"FAIL {OUTPUT_JSON} is missing", file=sys.stderr)
return 1
if current != want:
print(
f"FAIL {OUTPUT_JSON} is stale; run gen_go_tools.py",
file=sys.stderr,
)
return 1
print(f"PASS {OUTPUT_JSON} matches mcp/tools.json")
return 0
OUTPUT_JSON.parent.mkdir(parents=True, exist_ok=True)
OUTPUT_JSON.write_text(want, encoding="utf-8", newline="\n")
print(f"wrote {OUTPUT_JSON} ({len(MINIMAL_TOOLS)} tools)")
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
+123 -18
View File
@@ -1,6 +1,6 @@
"""校验 tools.json 与 MCP 服务端的 tools/list 是否一致。
两种模式:
三种模式:
python verify_tools.py --offline mcp/tools.json tools_raw.json
对比 tools.json 与已保存的黄金样本(不联网)
@@ -9,6 +9,12 @@
token 省略时依次取环境变量 YAMA_MCP_TOKEN、注册表 McpToken;
port 省略时自动探测 6545(明文后端)/ 6544(TLS 前端)
python verify_tools.py --subset mcp/tools.json [token] [port] [--readonly]
校验 Go 服务端(server/go)的 MCP 端点:名字集合必须恰好是它实现的那
9 个工具(只读模式 7 个),且 description / inputSchema / outputSchema
与 tools.json 里的同名工具逐字段一致。Go 端把 tools_minimal.json 内嵌
进二进制,这一模式检查的就是线上真正发布的字节。
比对内容:name / description / inputSchema / outputSchema,逐字段深度比较,
外加工具顺序。gate / write / manage / impl 是 tools.json 独有的元信息,不参与比对;
例外是 gate == "!machine" 的降级工具——它们只在 McpMachine=0 时出现,不进本次比对。
@@ -19,6 +25,24 @@ import os
import ssl
import sys
# Go 最小服务端实现的 9 个工具(docs/Mcp_Go_Minimal_Design.md §3.1)。
# tools/list 恰好是这些,多一个少一个都算失败。
GO_MINIMAL_TOOLS = (
"list_hosts",
"get_host_detail",
"get_screenshot",
"list_files",
"get_audit_log",
"get_server_status",
"terminal_exec",
"terminal_close",
"read_file",
)
# YAMA_MCP_READONLY=1 时 Go 端隐藏的写工具(terminal_* 会创建/关闭会话)。
GO_READONLY_HIDDEN = ("terminal_exec", "terminal_close")
FIELDS = ("description", "inputSchema", "outputSchema")
def normalize(obj):
"""规范化:键排序后序列化,消除 JSON object 的键序差异。"""
@@ -91,11 +115,107 @@ def fetch_live(token, port=None):
sys.exit(f"连接失败 -> {last}")
def report_field_diffs(live_by_name, golden_by_name, names):
"""逐字段比较同名工具,返回差异处数;一个工具最多报一处。"""
diffs = 0
for name in names:
a, b = live_by_name[name], golden_by_name[name]
for f in FIELDS:
va, vb = normalize(a.get(f)), normalize(b.get(f))
if va != vb:
diffs += 1
print(f"!! {name}.{f} 不一致")
for i, (ca, cb) in enumerate(zip(va, vb)):
if ca != cb:
print(f" @{i}")
print(f" 服务端: ...{va[max(0,i-60):i+80]}...")
print(f" json : ...{vb[max(0,i-60):i+80]}...")
break
else:
print(f" 长度不同: {len(va)} vs {len(vb)}")
break
return diffs
def verify_subset(path, token, port, readonly):
"""Go 最小服务端:名字集合恰好是 GO_MINIMAL_TOOLS,schema 与 tools.json 一致。"""
expected = [n for n in GO_MINIMAL_TOOLS
if not (readonly and n in GO_READONLY_HIDDEN)]
tools_live, live_stats = fetch_live(token, port)
print(f"tools.json: {path}")
print(f"模式: {'只读(隐藏 ' + ' / '.join(GO_READONLY_HIDDEN) + ')' if readonly else '读写'}")
print(f"期望: {len(expected)} 个工具 / 服务端: {len(tools_live)} 个")
live_names = [t["name"] for t in tools_live]
expected_set, live_set = set(expected), set(live_names)
diffs = 0
extra = sorted(live_set - expected_set)
missing = [n for n in expected if n not in live_set]
if extra:
diffs += len(extra)
print(f"!! 服务端多出: {extra}")
if missing:
diffs += len(missing)
print(f"!! 服务端缺少: {missing}")
dupes = sorted({n for n in live_names if live_names.count(n) > 1})
if dupes:
diffs += len(dupes)
print(f"!! 服务端重复: {dupes}")
# 顺序一致性:tools/list 的数组顺序会影响模型的选择倾向
if not extra and not missing and not dupes:
order = [n for n in live_names if n in expected_set]
if order != expected:
diffs += 1
print("!! 工具顺序与 tools.json 不一致")
for i, (x, y) in enumerate(zip(order, expected)):
if x != y:
print(f" 首个差异 @{i}: 服务端={x} 期望={y}")
break
else:
print("工具顺序: 一致")
doc = json.load(open(path, encoding="utf-8"))
tools_json = doc["tools"] if isinstance(doc, dict) else doc
golden_by_name = {t["name"]: t for t in tools_json}
live_by_name = {t["name"]: t for t in tools_live}
comparable = []
for name in expected:
if name not in golden_by_name:
diffs += 1
print(f"!! tools.json 缺少工具 {name}")
elif name in live_by_name:
comparable.append(name)
diffs += report_field_diffs(live_by_name, golden_by_name, comparable)
print(f" 体积: 响应 {live_stats['response_bytes']} B / tools 数组 "
f"{live_stats['tools_array_bytes']} B")
if diffs == 0:
print(f"\nPASS: Go 服务端 {len(expected)} 个工具与 tools.json 完全一致")
return 0
print(f"\nFAIL: {diffs} 处差异")
return 1
def main():
args = sys.argv[1:]
if not args:
sys.exit(__doc__)
if args[0] == "--subset":
argv = [a for a in args[1:]]
readonly = "--readonly" in argv
argv = [a for a in argv if a != "--readonly"]
if not argv:
sys.exit("用法: python verify_tools.py --subset <tools.json> [token] [port] [--readonly]")
path = argv[0]
token = resolve_token(argv[1] if len(argv) > 1 else "")
port = int(argv[2]) if len(argv) > 2 else None
if not token:
sys.exit("未找到 McpToken(参数 / YAMA_MCP_TOKEN / 注册表 均无)")
return verify_subset(path, token, port, readonly)
if args[0] == "--offline":
if len(args) < 3:
sys.exit("用法: python verify_tools.py --offline <tools.json> <黄金样本.json>")
@@ -142,24 +262,9 @@ def main():
if only_json:
print(f"!! 仅 json 有: {only_json}")
FIELDS = ("description", "inputSchema", "outputSchema")
diffs = 0
for name in sorted(set(live_by_name) & set(json_by_name)):
a, b = live_by_name[name], json_by_name[name]
for f in FIELDS:
va, vb = normalize(a.get(f)), normalize(b.get(f))
if va != vb:
diffs += 1
print(f"!! {name}.{f} 不一致")
for i, (ca, cb) in enumerate(zip(va, vb)):
if ca != cb:
print(f" @{i}")
print(f" 服务端: ...{va[max(0,i-60):i+80]}...")
print(f" json : ...{vb[max(0,i-60):i+80]}...")
break
else:
print(f" 长度不同: {len(va)} vs {len(vb)}")
break # 一个工具报一次即可
FIELDS_SHARED = sorted(set(live_by_name) & set(json_by_name))
diffs += report_field_diffs(live_by_name, json_by_name, FIELDS_SHARED)
# 顺序一致性:tools/list 的数组顺序会影响模型的选择倾向
order_live = [t["name"] for t in tools_live]