Files
SimpleRemoter/server/go/mcp/tools_term.go
T
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

618 lines
20 KiB
Go

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):
return nil, false, errf(CodeBusy,
"Device busy: the terminal for host %s is held by another viewer (web console or another MCP call); close it first", 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).
return terminalExecOutput{}, errf(CodeTimeout,
"Request cancelled; the command is still running, poll with session_id to collect its output")
}
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))
}