Commit Graph
84 Commits
Author SHA1 Message Date
yuanyuanxianganddeepseek-flash b4cb34fea9 Fix: Stop MCP tool timeouts from popping MFC dialogs
A sub-connection's first packet doubles as the readiness packet: the file,
service, registry, process, log and terminal tools all get answered that way.
Once a tool has given up (timeout or failure) its pending entry is gone, so if
the client only gets around to sending that first packet afterwards,
MessageHandle cannot tell it apart from a human click and opens the matching
modeless dialog - a File Manager window appeared while timeouts were being
exercised on this machine.

The wait paths now record, per device, which first-packet token the abandoned
tool would have sent (MarkLateFirstPacketForTool from WaitPending,
WaitPendingRegistry, WaitPendingWrite, WaitFileTransferDone and
WaitTerminalReady), and every dialog-opening case consumes that marker before
falling back to the MFC path. The marker is one-shot, expires after five
minutes and is never set on the success path, so normal use is unaffected; the
worst case is that a single manual open on a host that just had an MCP timeout
is swallowed.

ClientMsg packets are dropped with a log line while a tool is pending for that
host: new clients still send the legacy popup message alongside the structured
failure token, which would otherwise put a modal box on the server UI during an
MCP call.

Co-Authored-By: deepseek-flash
2026-10-25 18:12:56 +01:00
yuanyuanxianganddeepseek-flash 3b1626f415 Feature: Turn client failure reports into branchable MCP errors
Wire the four new failure tokens into MessageHandle and translate them
in the tool builders, so the three previously silent failures now return
a code an agent can branch on: list_services on a non-elevated client is
-32010 in well under a second instead of a 20 s timeout, list_files and
list_registry distinguish a missing path or key (-32009) from an empty
one, and download_file no longer waits for the stall watchdog when the
remote path does not exist. Access denied gets its own code, -32010, and
the win32 code is kept in the message for every case.

TakeRegError fills both registry wait flags in one packet because a
failing client sends no subkey or value packet at all. OnDownloadError
sets the session error without cancelling the file-manager sub-connection,
which stays owned by ClearFileTransfer. ListRemoteTopLevelNames treats
"not found" as "directory not created yet" so uploading into a fresh
directory keeps working now that the client reports it.

Also converge the error codes that were overloaded: a multi-monitor host
is a capability limit, not a parameter mistake, so remote_open reports
-32005 instead of -32008. The tool wait timeout moves from a compile-time
constant to McpToolTimeoutMs in settings.ini (default 20000, clamped to
1-600 s), which makes it possible to tune without a rebuild.

The smoke test gains the three reproducible negatives.

Co-Authored-By: deepseek-flash
2026-10-25 17:59:21 +01:00
yuanyuanxianganddeepseek-flash eaa10cc7d3 Fix: Make the MCP command sentinel robust and fail stalled downloads fast
Re-verified every finding of the 2026-10-25 MCP test report against the source and
then end-to-end on the Debug instance, and fixed the ones that live on the server.

P1/P3/P4 share one root cause: the sentinel was appended to the command line, so any
command that swallows the rest of its line (rem, cmd /c, if, for) swallowed the
sentinel too and the call always timed out. On ConPTY clients the command and the
sentinel are now sent as two lines, the sentinel prints %errorlevel% (whose echoed
text is a literal template, not digits) so folding echo can no longer be mistaken
for the sentinel, and FindSentinel returns the real exit code (9009, 1, 0, ...)
instead of 0/1. Old non-PTY clients keep the single-line form, since their echo
skipping depends on the write length.

ConPTY also returns a rendered screen stream rather than a byte stream, so stripped
VT sequences leave duplicate text behind; output cleaning now cuts through the
echoed command line, strips the echoed sentinel line and erases any leftover
sentinel text by its per-command nonce. StripAnsi no longer leaves the backslash of
an OSC terminated by ST.

A terminal session destroyed by a timeout used to report the same "not found" text
as a typo in the session id; a 600s tombstone now says what happened instead.
download_file gets a stall watchdog: no data for 60s fails with a clear message and
releases the host, where a missing remote path used to hold the whole host for the
full 600s default timeout.

Also corrects the get_activity_history annotation (it does reach the remote host),
completes the -32007/-32008/-32009 error table, documents the sentinel design in
Mcp_Design.md 12.1, and corrects the report's claim that the tools blocked during a
transfer are local DB reads -- they are remote machine-manager fetches, and purely
server-local tools are unaffected.

Co-Authored-By: deepseek-flash
2026-10-25 17:09:39 +01:00
yuanyuanxianganddeepseek-flash 7c5bf3e73d Feature: Filter search_file results by size, mtime and slim fields
Add four optional arguments to search_file that narrow the match list
after the client has returned it: min_size and max_size in bytes,
modified_after in either YYYY-MM-DD or YYYY-MM-DD HH:MM:SS form, and
name_only to keep just path and name per entry. The client still runs
the same name-matched recursive search, so these filters cut the
response size and the reasoning work on our side, not the scan time on
the host -- the summary sentence says so and totalAll keeps the
pre-filter count so a too-narrow condition is obvious. Invalid values
(negative sizes, an inverted range, a malformed timestamp) are rejected
with -32602 before any packet goes out.

The timestamp validator only accepted the ten-character form because
its shape loop never allowed the two colons, which rejected every
nineteen-character value; the loop now whitelists them.

Smoke tests cover the unchanged totalAll under a size filter, the slim
name_only payload and a rejected timestamp, for 33 checks when the
search path is supplied. Design notes are in section 11.4.

Co-Authored-By: deepseek-flash
2026-10-25 14:41:52 +01:00
yuanyuanxianganddeepseek-flash 929065e7be Feature: Filter the MCP host lists by group, OS and client type
list_online_hosts and list_all_hosts could only page, so finding "the
hosts in this group" or "the Linux ones" meant walking pages or falling
back to search_hosts, which has no client type filter and treats online
and offline hosts differently.

Both tools now accept group, os and client_type. They are substring
matches, combined with AND and case-insensitive over ASCII, matching the
semantics search_hosts already used, and the shared implementation keeps
the two tools from drifting apart. The filter runs before paging, so
total counts the matches and totalAll keeps the pre-filter size, and the
summary switches to the "matches" wording with a trailing line naming
the unfiltered size - a mistyped condition then shows up immediately
instead of silently returning nothing.

Offline hosts carry no clientType in their stored record, so a
client_type filter never matches them; the tool description says so and
points at os for that case.

Verified on the Debug instance: client_type=exe matches the single EXE
host while client_type=lnx matches nothing and still reports totalAll=1;
list_all_hosts with group=default matches all 3161 recorded hosts and
splits them into 1 online and 3160 offline, and os=zzz matches none. The
smoke test gains two checks and passes 28/28.

Co-Authored-By: deepseek-flash
2026-10-25 14:37:28 +01:00
yuanyuanxianganddeepseek-flash 5ce453797c Feature: Add a get_server_status tool to the MCP server
Answering "did my rebuild actually take effect" or "why was that tool
refused" used to mean reading list_online_hosts and get_audit_log and
inferring the rest. A single read-only call now returns the server's own
state: brand and version, the exe link time (taken from the file's last
write, which unlike __DATE__ reflects the whole build), how long the
process has been up, the address and port MCP is actually listening on,
every MCP switch, online and offline host counts, the number of sessions
in flight per family, and how many source IPs are currently blocked.

The bind and port are recorded by Start rather than re-read from the
configuration, so the tool reports what the listener really got. Session
counters take each subsystem's lock in turn and release it immediately,
so the numbers are an estimate of one moment, not a consistent snapshot.
Nothing sensitive is exposed: the token and the command whitelist never
appear, and the switches are reported as booleans only.

The tool is registered as read-only, non-destructive, idempotent and
server-local, which brings tools/list to 53 entries. The smoke test gains
three checks for it, including one that fails if a token-shaped field
ever appears in the output.

Verified on the Debug instance: the summary line reports version, uptime
and listener correctly, sessions.terminal goes 0 to 1 while a persistent
terminal is open and back to 0 after terminal_close, and the smoke test
passes 26/26.

Co-Authored-By: deepseek-flash
2026-10-25 14:35:19 +01:00
yuanyuanxianganddeepseek-flash ae37e812ee Feature: Page and filter the MCP audit log tool
get_audit_log used to hand back every entry in the main window's message
mirror on each call. The mirror is a 1000-entry ring buffer, so a busy
server returned a lot of text the caller never looked at, and there was
no way to ask for just the MCP entries or just the ones mentioning a
particular subject.

The tool now takes the same limit/offset pair as the other list tools
and two optional substring filters: type matches the type column and
keyword matches the message text, both case-insensitive. Filtering runs
before paging, so total counts the matches while totalAll keeps the size
of the whole mirror, and the summary line adds the pre-filter count when
a filter is in use so a typo is easy to spot. The GBK to UTF-8
conversion moved into the filter loop so the comparison happens between
strings in the same encoding, still under the dialog's critical section.

The output schema gains total/totalAll/offset/limit/hasMore, and the
smoke test now asserts the paging fields, the limit bound and an empty
result for a filter that cannot match, bringing it to 23 checks.

Verified on the Debug instance: limit=2 returns entries 1-2 then 3-4
with hasMore set, offset=999 reports the out-of-range text, type=mcp
matches the "MCP命令执行" entry, type=提示 matches both hint types and
keyword=监听 matches the listening-port line.

Co-Authored-By: deepseek-flash
2026-10-25 14:31:14 +01:00
yuanyuanxianganddeepseek-flash d9a1a9ebcb Fix: Record policy refusals in the MCP audit log
Every policy denial - read-only mode, one of the Mcp* switches turned
off, or a host that lacks the required capability - answers -32006. The
audit log only ever showed CALL_FAIL for those, which lumped them
together with parameter errors, offline hosts and timeouts, so after the
fact there was no way to tell "nobody called this" from "it was blocked
by policy".

The hooks all live in one place: the tools/call exit in the HTTP
handler now also reads error.code and error.message from the response it
already parses, and appends a CALL_DENIED event when the code is -32006.
The original CALL_FAIL line is still written, so its statistics keep
their old meaning, and the reason text is the fixed English sentence
each branch already returns - no tool arguments or user input reach the
log. Tool names taken from the request are flattened to a single line
first, both in the denied event and in the existing CALL_OK/CALL_FAIL
lines, so a crafted name cannot forge extra audit rows.

Also refresh the stale note in the design document that still called the
client search MAX_PATH overflow unfixed; the source was fixed in
8f718d9, but already-deployed clients still carry it, which is why the
smoke test keeps its search cases opt-in.

Verified on the Debug instance: with McpFileTransfer temporarily set to
0, download_file returns -32006 and the audit log gains the expected
CALL_DENIED line right after its CALL_FAIL; with the switch restored the
same call is CALL_OK again and no denied line appears. The read-only
smoke test passes 20/20.

Co-Authored-By: deepseek-flash
2026-10-25 14:28:16 +01:00
yuanyuanxianganddeepseek-flash 16f23e164c Fix: Clear the file transfer session when its sub-connection drops
A file transfer session holds raw pointers to its file-manager and
stream sub-connections, but nothing on the offline path looked at them.
OfflineProc cleans up terminal, remote-control and chat sessions and
skipped file transfers entirely, so a client that disconnected in the
middle of a transfer left the session pointing at a context that went
back to the connection pool. When the tool thread timed out it called
CancelIO on that stale pointer, which could cancel somebody else's
connection.

Add a context-to-device table next to the sessions, kept under the same
mutex and erased by ClearFileTransfer so a recycled pointer is never
mistaken for a live one. OfflineProc now calls
OnFileTransferContextClosed, which drops both pointers. A dropped
stream sub-connection means the transfer cannot complete, so it also
fails the session with error 1003 and wakes the waiting thread; the
file-manager sub-connection only issues the command and its loss is not
treated as a failure of the transfer itself.

Verified against the debug client: killing it 1.2 s into a 500 MB
download returns "Connection lost: the transfer sub-connection closed"
after about 1 s instead of waiting out timeout_ms, and the server stays
up. After the client restarts, two consecutive downloads and one upload
still work.

Co-Authored-By: deepseek-flash
2026-10-25 14:20:13 +01:00
yuanyuanxianganddeepseek-flash 39f0928de7 Fix: Finish a directory-only download instead of waiting for the timeout
The completion check compared filesDone against totalFiles minus
directoryCount and only ran on COMMAND_FILE_COMPLETE_V2. The client
sends no COMPLETE for directory entries, so a download of an empty
directory, or of a tree that holds only subdirectories, had zero
expected files and could never satisfy the check. The call sat there
until timeout_ms expired (600 s by default) and then reported 1002.

Mark the session done as soon as the directory entries account for
every entry the client declared. Verified with the debug client: an
empty directory returns in 0.2 s with zero files, a tree of nested
subdirectories returns in 0.2 s with the directories created, and a
directory holding three files still downloads them with the same
sizes and hashes as before.

Co-Authored-By: deepseek-flash
2026-10-25 14:16:46 +01:00
yuanyuanxianganddeepseek-flash abe7e99a77 Feature: Harden the MCP transport and add non-destructive host tools
Cap MCP request bodies at 2 MB, set a 15 s idle read timeout and a 60 s
write timeout, and give httplib an explicit 32-thread pool: long tools
such as chat_wait hold a worker for up to 55 s, and the default pool of
8 to 15 left other callers queued.

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

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

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

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

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

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

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

Co-Authored-By: deepseek-flash
2026-10-25 13:59:17 +01:00
yuanyuanxianganddeepseek-flash ac5b174b5f Feature: Add offline hosts, batch reads and MCP hardening
Expose hosts the server already knows about. list_all_hosts enumerates
both live contexts and the historical records in the client list, with
authStatus as a three-state string instead of a boolean. search_hosts
now honours online=false instead of returning an empty list, while the
default stays online-only so existing callers see the same results.
get_host_detail falls back to the last known record for an offline host
rather than failing with -32002.

Let read-only tools take an ids array of up to 50 hosts in one call.
The batch path reuses the single-host dispatcher and pages per host, so
behaviour cannot drift; write tools reject ids with -32602 so a mistake
cannot fan out across machines.

Add get_keylog behind its own McpKeylog switch. It drives the client's
existing keylogger sub-connection, accumulates the streamed text for a
bounded window and byte cap, then closes the sub-connection and returns
UTF-8 lines. The client pushes its buffered history first, so a result
contains both history and fresh keystrokes; the tool description says so.

Harden the endpoint. Failed bearer checks are counted per source IP and
ten failures within a minute block the IP for fifteen minutes. Auth
failures and tool calls append to logs\mcp_audit.log with metadata only:
no token, no arguments, no response bodies, and rotation at 5 MB. Loopback
sources are audited but never blocked, because the built-in frp tunnel
makes every remote request arrive from 127.0.0.1 and banning that address
would lock out legitimate clients along with the attacker.

Give list-style tools one pagination contract (limit/offset plus
total/totalAll/hasMore) and fix the generated schemas so id and ids are
genuine alternatives: the stale required:[id] left over from the
single-host schema would otherwise reject ids-only calls.

Co-Authored-By: deepseek-flash
2026-10-25 12:44:45 +01:00
yuanyuanxianganddeepseek-flash c99a1c375e Feature: Add MCP tools for remote chat with the client user
Add chat_open, chat_send, chat_wait and chat_close to the MCP tool set,
behind a new McpChat switch that defaults to off and is independent of
the read-only switch. The tools reuse the existing client chat link: the
main connection sends COMMAND_CHAT, the client opens a sub-connection
with TOKEN_CONN_AUTH and TOKEN_CHAT_START, the server answers with
COMMAND_NEXT_CHAT, and both directions then carry raw CP936 text.

Sessions are per host and held in shared pointers under their own mutex,
so a waiting chat_wait survives a close or a dropped sub-connection, and
chat_send is serialised per session. Text is converted strictly between
UTF-8 and CP936: invalid UTF-8, characters GBK cannot represent (emoji,
accented letters) and messages over the client's 4000-byte buffer are
rejected with -32602 instead of being mangled. A one-second settle delay
after the sub-connection binds keeps the first message from reaching the
client before its chat window exists.

The routing hooks run before the host-management hooks in MessageHandle
and clear the route in OfflineProc before the context leaves the list. A
five-second tombstone absorbs a late TOKEN_CHAT_START after a timeout, so
a failed chat_open does not pop the MFC chat dialog. Idle sessions are
swept on every tool call, and audit entries record the session id and
byte counts only, never message bodies.

The settings dialog gains the chat checkbox and the translated labels
for all three languages, and the strict UTF-8 to CP936 helpers move from
McpMachine.cpp to McpInternal so both tool families can share them.

Co-Authored-By: deepseek-flash
2026-10-23 11:19:21 +02:00
yuanyuanxianganddeepseek-flash 38cd207f5d Feature: Add host management and connection management MCP tools
Expose the online-list TLS column through list_online_hosts, search_hosts
and get_host_detail. The value comes from the flag the client reports at
login, so old clients always read false.

Add list_network_connections and kill_network_connection on top of the
connection manager sub-connection protocol. The kill path matches the
original 110-byte record instead of rebuilding addresses, supports a dry
run, refuses UDP/IPv6 targets, and verifies that the quadruple really
disappeared instead of assuming success.

Add a host_* family backed by the machine manager protocol: ten read
tools covering every tab of the host management dialog, and four
recoverable write tools for process freeze/thaw, window restore/hide/
maximize/minimize, service start/stop/pause/continue/restart, and
scheduled task run/stop. Every write re-reads the snapshot before sending
and re-checks afterwards, reporting -32009 for stale targets rather than
acting blindly. The family is gated by McpMachine, the risky subset by
McpMachineDangerous, and writes additionally require read-only mode to
be off.

Route managed sub-connections from MessageHandle and OfflineProc, keep
the single-in-flight rule by sharing the pending table with a request
kind, and move the shared JSON/lock/encoding helpers into McpInternal so
both tool families use one implementation. Settings dialog, design docs
and en_US/zh_TW/de_DE translations are updated accordingly.

Co-Authored-By: deepseek-flash
2026-10-21 20:01:41 +02:00
yuanyuanxianganddeepseek-v4-pro 9eed43bc8d Feature: Add MCP device management-control tools (kill/window/service/power)
Add P7 management-control tools behind a single McpManage flag (plus
McpReadonly=0): kill_process, operate_window, control_service and
power_action. The write tools run a ready->confirm lifecycle on their
sub-connection, using a new followUp/followUpSent field to tell the two
arrivals of the same TOKEN_*LIST apart; the write command and the follow-up
refresh command go out as two separate Send2Client calls, with a new
WaitSendIdle() (context.h / Server.h) draining the outbound buffer in between
so the same buffer is never WSASend'd concurrently.

McpSettingsDlg gains a "management operations" checkbox (IDC_MCP_MANAGE), the
main toolbar gains an MCP entry button, and en/de/zh-TW strings are synced.
power_action is fire-and-forget over the main connection (no confirmation).

Verified end-to-end against a real Windows 10/VMware client: kill_process
returns remaining:[] and operate_window/control_service return ok:true with
their confirm packet arriving after an HTTP split. Verification surfaced a
prerequisite parser bug, fixed separately in a72e6eb, where HeaderParser
latched m_bShouldUnmask FALSE on HTTP continuation chunks and dropped the
confirm packet.

Co-Authored-By: deepseek-v4-pro
2026-10-01 16:56:30 +02:00
yuanyuanxianganddeepseek-v4-pro 6bcd593b6d Feature: Add upload_file MCP tool (V2 protocol, main-connection upload)
Implement the P2 upload_file tool to push a local file or directory from the
master to an online Windows host over the existing V2 file-transfer protocol.
The server drives FileBatchTransferWorkerV2 synchronously on the main
connection through a headless callback, reuses the list_files chain for the
overwrite pre-check, and is gated by McpFileTransfer=1 plus McpReadonly=0.

The client main connection never initialized the file-transfer module, so
g_status stayed 0 and RecvFileChunkV2 silently dropped every chunk, truncating
uploads to zero bytes. Add a once-per-process lazy InitFileUpload in the
COMMAND_SEND_FILE_V2 handler that mirrors the FileManager init; the destructor
deliberately does not Uninit so g_status remains 1 across reconnects.

Update the design doc to record the client-side change and correct the
upload_file description to state that sha256 is not returned (V2 has no
receiver-to-sender ACK; integrity is checked client-side and logged only).

Co-Authored-By: deepseek-v4-pro
2026-08-31 22:43:16 +02:00
yuanyuanxianganddeepseek-v4-pro 5c77f5ce14 Feature: Add download_file MCP tool (V2 protocol, SHA-256 verified)
download_file pulls a remote file or directory back to the controller over
the existing V2 file-transfer protocol. It reuses COMMAND_LIST_DRIVE to open
the file-manager sub-link, then sends CMD_DOWN_FILES_V2 so the Windows client
streams COMMAND_SEND_FILE_V2 chunks and a per-file COMMAND_FILE_COMPLETE_V2
SHA-256 checksum over its own authenticated sub-connection. The server routes
those two packet types into a new per-device FileTransferSession whenever a
download is pending, so the headless path never opens the GUI progress dialog;
the C2C and existing GUI branches are left untouched.

Files are written under a normalized local_dir, and every chunk filename is
resolved and verified to stay inside local_dir (directories included) to block
.. traversal; overwrite=false skips existing files and counts them as skipped.
One transfer per host (mutually exclusive with the one-shot pending registry),
a dedicated McpFileTransfer=0-by-default gate surfaced in the settings dialog,
and audit logging complete the change. upload_file remains future work.

Co-Authored-By: deepseek-v4-pro
2026-08-30 13:19:51 +02:00
yuanyuanxianganddeepseek-v4-pro ac2855198b Fix: terminal_exec sentinel timeout on numeric timeout_ms and silent commands
Two independent bugs made MCP terminal tools time out despite the command
finishing.

First, timeout_ms is declared integer in the tool schemas but was parsed
through GetStringArg, which only reads JSON strings. A numeric value fell
through to the 20s default, so callers asking for a longer wait were cut off
at 20s. exec_command, terminal_open, terminal_exec and remote_open now parse
timeout_ms through GetIntArg, which accepts both JSON numbers and digit
strings, keeping the 1..600000 range guard.

Second, FindSentinel treated the __MCP_DONE_<nonce>__ marker as a line start
only when preceded by \n. Commands that produce no output (ping > nul,
Start-Sleep, tar -czf) echo their command line ending in \r, so the marker
never matched and the wait ran to timeout even though the command had
completed. The check now also accepts \r.

Co-Authored-By: deepseek-v4-pro
2026-08-30 13:19:22 +02:00
yuanyuanxianganddeepseek-v4-pro d55d40e7a2 Feature: Exclude human Web viewing from MCP remote control sessions
Complete the bidirectional mutual exclusion between MCP remote control
and human Web viewing (§8.2). Direction 1 (remote_open rejected while a
human session holds the screen sub-connection) already existed; this adds
direction 2: a human Web viewer is now rejected while an MCP session owns
the device.

Add a m_McpTriggeredDevices marker (mirroring m_MfcTriggeredDevices) that
is set when an MCP session is created (BeginScreenCtrlOpen) and cleared at
every session-erasure site (CloseScreenCtrlSession, SweepIdleScreenCtrl,
OnScreenControlClosed, EndScreenCtrlAction), so the marker cannot go stale
and permanently block humans. HandleConnect checks IsMcpTriggered before
mutating client state or starting the remote desktop.

Co-Authored-By: deepseek-v4-pro
2026-08-25 14:14:26 +02:00
yuanyuanxianganddeepseek-v4-pro 25a6e2d07a Feature: Add remote_clipboard MCP tool
Add the remote_clipboard tool to the MCP remote control surface, writing
text to the remote host's clipboard via COMMAND_SCREEN_SET_CLIPBOARD
through the established screen sub-connection. Input UTF-8 is converted
to GBK (ToAnsi, code page 936) to match the client's CF_TEXT/ANSI
clipboard path, mirroring the existing CScreenSpyDlg::SendServerClipboard
packet format. Pasting remains a separate step (remote_keyboard Ctrl+V).

Known MVP limitation, documented in the tool description: non-GBK
characters (e.g. emoji) are replaced by '?' on the CF_TEXT path.

Co-Authored-By: deepseek-v4-pro
2026-08-25 13:45:51 +02:00
yuanyuanxianganddeepseek-v4-pro 18259b8526 Feature: Add remote_mouse MCP tool
Add the remote_mouse tool to the MCP remote control surface, injecting
mouse events (move / down / up / click / right_click / middle_click /
drag / scroll) into an established remote_open session. Normalized 0..1
coordinates are mapped to physical pixels via the session's captured
resolution and clamped to screen bounds. Scroll follows the existing web
console's wheel sign convention (positive delta scrolls down) and is
vertical-only.

Extract BuildMouseMsg64 into WebService.h as a shared helper, reused by
both the web console's HandleMouse and the new MCP handler so the two
injection paths cannot drift.

Co-Authored-By: deepseek-v4-pro
2026-08-25 13:38:09 +02:00
yuanyuanxianganddeepseek-v4-pro f04d892ac8 Feature: Add remote_keyboard MCP tool (key_down / key_up / key_press / type)
Implement milestone M2b of the MCP remote-control design: inject keyboard
events through an existing screen sub-connection.

- Extract the MSG64 keyboard construction from WebService::HandleKey into a
  shared inline BuildKeyMsg64 helper in WebService.h, and have HandleKey use
  it (behaviour-preserving) so the Web and MCP paths cannot drift.
- Add BuildRemoteKeyboard with four actions: key_down / key_up / key_press
  (key name -> VK via MapKeyNameToVk, plus CTRL/ALT/SHIFT/WIN modifiers) and
  type (per-character VkKeyScanA mapping, ASCII only, newline/tab -> Enter/Tab).
  The batch is sent as one [COMMAND_SCREEN_CONTROL][MSG64*N] packet over the
  screen sub-connection under the existing Begin/EndScreenCtrlAction busy
  discipline, then audited via WM_SHOWERRORMSG.

Non-ASCII text is rejected (-32602) and must go through remote_clipboard +
Ctrl+V (milestone M4), matching the design's clipboard path for CJK input.

Co-Authored-By: deepseek-v4-pro
2026-08-25 13:22:00 +02:00
yuanyuanxianganddeepseek-v4-pro 09018e2b4d Improve: Harden MCP screen-ctrl session state machine for injection
Add the busy/closed flags to ScreenCtrlSession plus BeginScreenCtrlAction
/ EndScreenCtrlAction, mirroring the terminal's busy discipline so an
in-flight injection cannot race with session teardown (review finding #6).

While an injection is in flight (busy=true), OnScreenControlClosed marks the
session closed instead of erasing it (the injection thread, which still holds
subCtx, cleans up in EndScreenCtrlAction), SweepIdleScreenCtrl skips it, and
CloseScreenCtrlSession defers the erase. The subCtx is looked up under
m_ScreenCtrlMutex and the injection is sent outside the lock, matching the
established terminal pattern; the screen sub-connection's CONTEXT_OBJECT::Send2Client
already serializes internally via SendLock.

Co-Authored-By: deepseek-v4-pro
2026-08-25 13:04:05 +02:00
yuanyuanxianganddeepseek-v4-pro 6045baadb8 Feature: Add MCP remote_open/remote_close remote control sessions
Add M1 of MCP remote control (docs/Mcp_RemoteControl_Design.md): the
remote_open / remote_close tools plus the ScreenCtrlSession state machine.

remote_open establishes a hidden screen sub-connection by reusing
WebService::StartRemoteDesktop (COMMAND_SCREEN_SPY -> CScreenSpyDlg ->
RegisterScreenContext), polls for the sub-connection plus its physical
resolution (TOKEN_BITMAPINFO -> NotifyResolutionChange -> GetScreenSize),
then records the session (single device, single session, reverse-mapped
subCtx for OfflineProc cleanup) and returns {session_id, screen_w,
screen_h}. remote_close validates session_id and tears down the
sub-connection idempotently. A McpRemoteControl settings checkbox (default
off, requires McpReadonly=0) gates the tools; every open/close is audited
via WM_SHOWERRORMSG.

Gating: multi-monitor hosts are rejected with -32008 (phase 1 supports only
single monitor, where Observe=main screen and Act=virtual desktop coincide);
the monitor count comes from the client heartbeat RES_RESOLUTION ("N:W*H").

Known limitations (deferred to the injection milestones): mutual exclusion
with human remote-desktop viewing is one-directional in M1 (a human who
joins during an MCP session can tear it down on disconnect), and subCtx is
not yet dereferenced so no liveness re-check is needed until
remote_mouse/remote_keyboard.

Co-Authored-By: deepseek-v4-pro
2026-08-25 12:55:52 +02:00
yuanyuanxianganddeepseek-v4-pro 70dbb6b255 Feature: Add persistent remote terminal MCP tools
Add terminal_open / terminal_exec / terminal_close so an AI can hold one
shell session per Windows host and run a sequence of commands with cwd and
environment preserved, instead of the one-shot exec_command.

The persistent terminal is a separate full-command write capability gated by
McpTerminal (default off) plus McpReadonly=0, with no whitelist and full
audit. One device maps to one terminal session via the shared m_TermSessions
map; idle sessions are swept after 300s. terminal_exec rejects commands that
contain & or | (they corrupt the sentinel control-operator chain) as well as
control characters.

Also harden exec_command and terminal_exec against newline/CR injection, fix a
dangling subCtx after an abrupt shell disconnect, and refresh lastActiveAt on
command completion. Add en/zh-TW translations for the new UI strings and a
design document covering both exec_command and the persistent terminal.

Co-Authored-By: deepseek-v4-pro
2026-08-24 19:11:16 +02:00
yuanyuanxianganddeepseek-v4-pro 0ddbc1aced Feature: Add exec_command MCP tool
Add a one-shot exec_command MCP tool that runs a command on a remote
Windows host and returns stdout plus exit code, reusing the Web terminal
link (main-connection COMMAND_SHELL, a shell sub-connection, and a
sentinel command line located via rfind to tolerate ConPTY echo).

The sentinel marker is embedded in the command line ConPTY echoes back,
so it is only treated as hit when it starts a line (preceded by a newline
or the buffer start); this keeps the echoed marker from being mistaken
for the real sentinel when the echo packet arrives before the output.

Execution is gated at Web remote-desktop sensitivity: a read-only mode
(McpReadonly, default on, hides the tool) and a command whitelist
(McpCmdWhitelist) with built-in read-only prefixes. Shell metacharacters
(& | < > ^) are rejected before whitelist matching, and each execution is
recorded in the server audit log.

Extend the MCP settings dialog with the read-only checkbox and a
multi-line whitelist box (commas and newlines both accepted, normalized
to a comma-separated list on save), and add English and Traditional
Chinese mappings for the new UI and audit-log strings.

Co-Authored-By: deepseek-v4-pro
2026-08-23 23:23:20 +02:00
yuanyuanxianganddeepseek-v4-pro 8bd6f3b60a Feature: Add list_registry MCP tool
Add a read-only list_registry MCP tool for querying a remote Windows
host's registry. An empty path returns the five root keys; a path such as
HKEY_LOCAL_MACHINE plus subkeys returns that key's immediate subkeys and
values (name, type, and formatted data).

Client side: enumerate with KEY_READ instead of KEY_ALL_ACCESS and map the
full value-type set (REG_SZ, REG_DWORD, REG_BINARY, REG_EXPAND_SZ,
REG_MULTI_SZ, REG_QWORD, REG_NONE) so unknown types are no longer
mis-reported as REG_SZ. The registry manager now always sends both the
TOKEN_REG_PATH and TOKEN_REG_KEY packets (an empty packet when a part is
empty), making the two-packet reply deterministic for the server.

Server side: add the three-phase flow (COMMAND_REGEDIT, COMMAND_REG_FIND,
then PATH plus KEY) with per-host pending state, parse the fixed-width
wire format with bounds checks, format value data for JSON, and guard
registry paths against exceeding MAX_PATH to protect the client stack.

Co-Authored-By: deepseek-v4-pro
2026-08-23 10:37:55 +02:00
yuanyuanxianganddeepseek-v4-pro 8815c4f896 Feature: Add get_audit_log MCP tool
Expose the server main-window audit log (host online/offline, operation
results, alerts) as a read-only, no-arg, in-memory MCP tool. The log lives
in m_CList_Message, a CListCtrl that is only safe to touch on the UI
thread, so add a thread-safe mirror m_MessageLog (guarded by m_cs) and keep
it in sync at the four item-mutation sites: ShowMessage, OnShowErrMessage,
OnMsglogDelete and OnMsglogClear. The tool reads the mirror directly under
m_cs and returns up to MAX_MESSAGE_COUNT (1000) entries, newest first.

Co-Authored-By: deepseek-v4-pro
2026-08-21 20:33:59 +02:00
yuanyuanxianganddeepseek-v4-pro 5611ba621c Feature: Add list_services and get_client_log MCP tools
Add the two P2d read-only MCP tools, both one-shot sub-links (mode A') on
the existing single-flight pending registry.

list_services sends COMMAND_SERVICES; the client's CServicesManager emits
TOKEN_SERVERLIST on sub-link creation, parsed as 5 null-terminated fields per
record (display_name/service_name/binary_path/status/start_type) with
zero-padding termination. Services are Windows-only, so LNX/MAC hosts get
-32005 up front instead of a 20s timeout.

get_client_log sends COMMAND_QUERY_LOG; the client's CClientLogManager dumps
its full in-memory Logger ring buffer once, then pushes deltas every 3s. The
MCP path takes the first (full) TOKEN_REPORT_LOG and cancels the sub-link so
later deltas stop, while the MFC log dialog keeps receiving deltas on the
non-pending branch. Log text is client ANSI on Windows, decoded by clientType
like process/file names. MessageHandle intercepts both with
IsPending -> TakeMainResponse + CancelIO. Sync the design doc (P2d section +
verification notes; Linux get_client_log timeout is a client-version gap).

Co-Authored-By: deepseek-v4-pro
2026-08-19 14:28:10 +02:00
yuanyuanxianganddeepseek-v4-pro c6c6e1d5ef Improve: Add optional max_width to get_screenshot
The get_screenshot tool inherited the MFC thumbnail-preview profile, capping
the frame at 1024px wide (1280 on 4K source), which is too small for AI
vision/OCR of dense UI. Add an optional max_width argument that overrides the
width (clamped to the client's 64..1920 limit) while keeping the RTT-adaptive
jpegQuality. Omitted or 0 keeps the existing thumbnail profile; 1920 yields
near-native resolution (full 1080p on a 1080p source, 1920 wide on 4K). Sync
the design doc.

Co-Authored-By: deepseek-v4-pro
2026-08-19 13:41:38 +02:00
yuanyuanxianganddeepseek-v4-pro 61089e5fae Feature: Add list_files and get_screenshot MCP tools
Add the two P2c MCP tools on top of the P2b protocol. list_files lists
drives (COMMAND_LIST_DRIVE -> TOKEN_DRIVE_LIST) or a directory (follow-up
COMMAND_LIST_FILES -> TOKEN_FILE_LIST on the same one-shot sub-link);
get_screenshot reuses the screen-preview RPC with a per-host reqId
correlation so stale or MFC-preview responses fall through to the MFC
path untouched. Both share the P2b single-flight pending registry.

Fix file/process name encoding: the client reads process names, paths and
file names via the ANSI (A) APIs, so they are GBK on Windows regardless of
the CLIENT_CAP_UTF8 capability bit (which governs window titles only).
Decode by clientType (LNX/MAC = UTF-8, Windows = 936) rather than
GetClientEncoding, and convert the list_files path to the client ANSI code
page before sending. Sync Mcp_Phase2_Design.md with the P2c design and the
encoding correction.

Co-Authored-By: deepseek-v4-pro
2026-08-19 13:27:32 +02:00
yuanyuanxianganddeepseek-v4-pro 6ba6b0289d Feature: Add list_processes, list_windows and get_activity_history MCP tools
Add three read-only P2b MCP tools over the existing protocol. list_processes and list_windows trigger the client via COMMAND_SYSTEM / COMMAND_WSLIST on the main connection and receive TOKEN_PSLIST / TOKEN_WSLIST on a one-shot sub-link; get_activity_history uses the main-connection RPC COMMAND_QUERY_ACTIVITY -> TOKEN_REPORT_ACTIVITY. A per-host single-flight pending registry (m_Pending) with a 20s timeout correlates each response to its request and rejects a concurrent request for the same host with -32003. Parsers stop on the first empty record to ignore the client's LocalSize trailing zero padding, and window titles are decoded per the client UTF-8 capability bit. MessageHandle only adds if-guarded branches, so the MFC dialogs are untouched. Sync Mcp_Phase2_Design.md with the mode A'/A architecture, the verification notes, and the registry-backed config location.

Co-Authored-By: deepseek-v4-pro
2026-08-19 09:58:58 +02:00
yuanyuanxianganddeepseek-v4-pro 86c4f14cf4 Feature: Add search_hosts and get_host_detail MCP tools
Add two pure in-memory MCP tools over the online host list. search_hosts filters by name/remark, IP, group and OS (all optional, AND-combined, ASCII case-insensitive substring match); get_host_detail returns one online host by id and answers -32602 for a missing/non-numeric id and -32002 for an unknown or offline id. Sync Mcp_Phase2_Design.md with the second-review corrections and the P2a implementation.

Co-Authored-By: deepseek-v4-pro
2026-08-18 16:53:28 +02:00
yuanyuanxianganddeepseek-v4-pro 13052b7cae Feature: Add MCP (Model Context Protocol) server integration
Add an optional MCP server (JSON-RPC 2.0 over Streamable HTTP) exposing
an online-host listing tool, protected by a Bearer token. Disabled by
default; configured via a new "Extensions > MCP Settings" dialog.

- McpServer: httplib + JSON-RPC 2.0 dispatch (initialize/ping/tools/list/tools/call)
- McpSettingsDlg: runtime-created dialog for enable/port/bind/token
- HostJson: extract single-host JSON serialization shared with WebService
- FRP: expose MCP port (union with listening/Web ports) when bound to 0.0.0.0
- i18n: en_US / zh_TW translations

Co-Authored-By: deepseek-v4-pro
2026-08-16 14:37:11 +02:00