From 31883edc09c429aee96868531c885b1d6e537546 Mon Sep 17 00:00:00 2001 From: yuanyuanxiang <962914132@qq.com> Date: Fri, 13 Nov 2026 12:57:12 +0100 Subject: [PATCH] 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 --- server/go/mcp/filemgr.go | 164 ++++++++++++++++++--- server/go/mcp/filemgr_test.go | 269 +++++++++++++++++++++++++++++++++- server/go/mcp/filev2.go | 10 +- server/go/mcp/filev2_test.go | 3 +- server/go/mcp/server.go | 9 +- server/go/mcp/tools_term.go | 10 +- 6 files changed, 433 insertions(+), 32 deletions(-) diff --git a/server/go/mcp/filemgr.go b/server/go/mcp/filemgr.go index 9b75d63..50a5f83 100644 --- a/server/go/mcp/filemgr.go +++ b/server/go/mcp/filemgr.go @@ -16,7 +16,9 @@ import ( "github.com/yuanyuanxiang/SimpleRemoter/server/go/protocol" ) -// list_files drives the client's file-manager sub-connection (design §5.3): +// 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 @@ -49,9 +51,16 @@ const ( errorAccessDenied = 5 errorFileNotFound = 2 errorPathNotFound = 3 - batchUnsupportedHint = "batch (ids) is not implemented by this server build; call list_files once per id" + + // 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 @@ -276,8 +285,8 @@ func (s *Server) retireFileConn(ctx *connection.Context) { // ----- get_screenshot-style argument / result shapes ------------------------- -// listFilesArgs is the published inputSchema as Go. ids is advertised by the -// Win32 server for batch reads; this server rejects it explicitly. +// 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"` @@ -363,7 +372,8 @@ func (s *Server) closeFileManagerConn(deviceID string, req *fileRequest) { } } -// callListFiles lists drives (no path) or one directory level. +// 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") @@ -372,21 +382,141 @@ func (s *Server) callListFiles(ctx context.Context, raw json.RawMessage) (any, * if rerr := decodeArgs(raw, &args); rerr != nil { return nil, rerr } - if len(args.IDs) > 0 { - return nil, errf(CodeUnsupported, "%s", batchUnsupportedHint) + // 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 nil, errf(CodeInvalidParams, "Invalid id: expected a decimal host id string") + 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 nil, errf(CodeInvalidParams, "Invalid path: NUL and line breaks are not allowed") + return toolResult{}, errf(CodeInvalidParams, "Invalid path: NUL and line breaks are not allowed") } if s.cfg.Hub.MainConn(args.ID) == nil { - return nil, errf(CodeOffline, "Host not found or offline: %s", args.ID) + return toolResult{}, errf(CodeOffline, "Host not found or offline: %s", args.ID) } path := args.Path @@ -398,13 +528,13 @@ func (s *Server) callListFiles(ctx context.Context, raw json.RawMessage) (any, * pathGBK := protocol.UTF8ToGBK(path) if len(pathGBK) >= 250 { // The client copies the path into a MAX_PATH buffer and appends "\\*.*". - return nil, errf(CodeInvalidParams, + 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 nil, rerr + return toolResult{}, rerr } defer s.closeFileManagerConn(args.ID, req) @@ -418,7 +548,7 @@ func (s *Server) callListFiles(ctx context.Context, raw json.RawMessage) (any, * pkt = append(pkt, pathGBK...) pkt = append(pkt, 0) if err := s.cfg.Hub.SendToConn(sub, pkt); err != nil { - return nil, errf(CodeSendFailed, "Failed to send the directory request on the file-manager channel: %v", err) + return toolResult{}, errf(CodeSendFailed, "Failed to send the directory request on the file-manager channel: %v", err) } timer := time.NewTimer(fileListTimeout) @@ -430,16 +560,16 @@ func (s *Server) callListFiles(ctx context.Context, raw json.RawMessage) (any, * files, truncated := parseFileList(ev.payload) return listFilesResult(args, nil, files, truncated), nil case fileEventError: - return nil, fileWin32Error(ev.win32err, path) + return toolResult{}, fileWin32Error(ev.win32err, path) default: - return nil, errf(CodeInternal, "Unexpected file-manager reply while listing a directory") + return toolResult{}, errf(CodeInternal, "Unexpected file-manager reply while listing a directory") } case <-timer.C: - return nil, errf(CodeTimeout, + 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 nil, errf(CodeTimeout, "Request cancelled while waiting for the directory listing") + return toolResult{}, errf(CodeTimeout, "Request cancelled while waiting for the directory listing") } } diff --git a/server/go/mcp/filemgr_test.go b/server/go/mcp/filemgr_test.go index 41dcdff..fb45dd7 100644 --- a/server/go/mcp/filemgr_test.go +++ b/server/go/mcp/filemgr_test.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "encoding/binary" + "encoding/json" "net" "strings" "testing" @@ -59,7 +60,9 @@ func newFileRig(t *testing.T) *fileRig { // newSub builds a sub-connection context with the ClientID ConnAuth would pin. // The pipe gives Close something real to close; nothing writes to it. -func (r *fileRig) newSub() *connection.Context { +func (r *fileRig) newSub() *connection.Context { return r.newSubFor("1001") } + +func (r *fileRig) newSubFor(clientID string) *connection.Context { r.t.Helper() c1, c2 := net.Pipe() r.t.Cleanup(func() { _ = c1.Close(); _ = c2.Close() }) @@ -68,10 +71,48 @@ func (r *fileRig) newSub() *connection.Context { // earlier call, so the fake ones have to be numbered too. r.connID++ ctx := &connection.Context{ID: r.connID, Conn: c1, RemoteAddr: "10.0.0.1:4100"} - ctx.Info.ClientID = "1001" + ctx.Info.ClientID = clientID return ctx } +// registerDevice adds another online host so batch tests can fan out. +func (r *fileRig) registerDevice(id, peerIP string) *connection.Context { + r.t.Helper() + main := &connection.Context{RemoteAddr: peerIP + ":4000"} + main.Info.ClientID = id + main.Info.ClientType = "EXE" + r.h.Register(&hub.Device{ID: id, PeerIP: peerIP, Capability: "1"}, main) + return main +} + +// nextAny returns the next wire without asserting a destination. +func (r *fileRig) nextAny() fileWire { + r.t.Helper() + select { + case w := <-r.w: + return w + case <-time.After(5 * time.Second): + r.t.Fatal("no wire was sent") + return fileWire{} + } +} + +// nextIgnoringBye reads the next wire addressed to want, skipping COMMAND_BYE +// frames that retiring sub-connections send asynchronously. +func (r *fileRig) nextIgnoringBye(want *connection.Context) []byte { + r.t.Helper() + for { + w := r.nextAny() + if bytes.Equal(w.data, []byte{protocol.CommandBye}) { + continue + } + if w.ctx != want { + r.t.Fatalf("wire went to an unexpected connection (%p, want %p): %v", w.ctx, want, w.data) + } + return w.data + } +} + func (r *fileRig) next(want *connection.Context) []byte { r.t.Helper() select { @@ -242,7 +283,7 @@ func TestListFilesRejectsBadArguments(t *testing.T) { args string code int }{ - {"batch ids", `{"ids":["1001","1002"]}`, CodeUnsupported}, + {"id and ids", `{"id":"1001","ids":["1002"]}`, CodeInvalidParams}, {"missing id", `{}`, CodeInvalidParams}, {"non-decimal id", `{"id":"abc"}`, CodeInvalidParams}, {"numeric id", `{"id":1001}`, CodeInvalidParams}, @@ -761,3 +802,225 @@ func TestParseFileListAtCapIsNotTruncated(t *testing.T) { t.Fatalf("parsed %d entries, truncated=%v", len(files), truncated) } } + +// ----- batch (ids) ---------------------------------------------------------- + +// answerDirectoryCall drives one host through the two-phase file-manager +// handshake and answers it with the given entries. It returns after the file +// list was delivered, so the next host's drive request can be read. +func (r *fileRig) answerDirectoryCall(main *connection.Context, clientID string, path string, files ...fileRec) { + r.t.Helper() + if got := r.nextIgnoringBye(main); !bytes.Equal(got, []byte{protocol.CommandListDrive}) { + r.t.Fatalf("drive request wire = %v, want [%d]", got, protocol.CommandListDrive) + } + sub := r.newSubFor(clientID) + if !r.s.OnFilePacket(sub, driveListPacket(driveRec{'C', 3, 500000, 123456, "本地磁盘", "NTFS"})) { + r.t.Fatal("drive-list packet was not consumed") + } + got := r.next(sub) + if got[0] != protocol.CommandListFiles || !bytes.Equal(got[1:len(got)-1], protocol.UTF8ToGBK(path)) { + r.t.Fatalf("directory request wire = %v, want %d %q", got, protocol.CommandListFiles, path) + } + if !r.s.OnFilePacket(sub, fileListPacket(files...)) { + r.t.Fatal("file-list packet was not consumed") + } +} + +func TestListFilesBatch(t *testing.T) { + r := newFileRig(t) + main2 := r.registerDevice("1002", "10.0.0.2") + + ch := r.call(`{"ids":["1001","1002"],"path":"C:\\"}`) + r.answerDirectoryCall(r.main, "1001", `C:\`, fileRec{name: "a.txt", size: 3}) + r.answerDirectoryCall(main2, "1002", `C:\`, fileRec{name: "b.txt", size: 5}) + res := r.wait(ch) + if res.err != nil { + t.Fatalf("batch failed: %v", res.err) + } + + sc, ok := res.res.StructuredContent.(map[string]any) + if !ok { + t.Fatalf("structuredContent type = %T", res.res.StructuredContent) + } + if sc["tool"] != "list_files" { + t.Fatalf("tool = %v", sc["tool"]) + } + checkInt(t, sc, "total", 2) + checkInt(t, sc, "succeeded", 2) + checkInt(t, sc, "failed", 0) + checkInt(t, sc, "skipped", 0) + results, ok := sc["results"].([]map[string]any) + if !ok || len(results) != 2 { + t.Fatalf("results = %#v", sc["results"]) + } + for i, wantName := range []string{"a.txt", "b.txt"} { + if results[i]["id"] != []string{"1001", "1002"}[i] || results[i]["ok"] != true { + t.Fatalf("results[%d] = %#v", i, results[i]) + } + data, ok := results[i]["data"].(map[string]any) + if !ok { + t.Fatalf("results[%d].data type = %T", i, results[i]["data"]) + } + files, ok := data["files"].([]fileEntry) + if !ok || len(files) != 1 || files[0].Name != wantName { + t.Fatalf("results[%d].data.files = %#v", i, data["files"]) + } + } +} + +func TestListFilesBatchDeadlineSkipsRest(t *testing.T) { + r := newFileRig(t) + old, oldTimeout := listFilesBatchDeadline, fileListTimeout + listFilesBatchDeadline, fileListTimeout = -time.Second, time.Second + t.Cleanup(func() { listFilesBatchDeadline, fileListTimeout = old, oldTimeout }) + + res, rerr := r.s.callListFiles(context.Background(), []byte(`{"ids":["1001","1002"]}`)) + if rerr != nil { + t.Fatalf("batch failed: %v", rerr) + } + sc := res.(toolResult).StructuredContent.(map[string]any) + checkInt(t, sc, "total", 2) + checkInt(t, sc, "succeeded", 0) + checkInt(t, sc, "failed", 0) + checkInt(t, sc, "skipped", 2) + results := sc["results"].([]map[string]any) + for i, entry := range results { + if entry["ok"] != false || entry["skipped"] != true { + t.Fatalf("results[%d] = %#v", i, entry) + } + errObj, _ := entry["error"].(map[string]any) + if errObj["code"] != CodeTimeout { + t.Fatalf("results[%d].error = %#v", i, entry["error"]) + } + } + r.expectNothing() // nothing was attempted +} + +func TestListFilesBatchReportsBadID(t *testing.T) { + r := newFileRig(t) + res, rerr := r.s.callListFiles(context.Background(), []byte(`{"ids":["abc"]}`)) + if rerr != nil { + t.Fatalf("batch failed: %v", rerr) + } + sc := res.(toolResult).StructuredContent.(map[string]any) + checkInt(t, sc, "failed", 1) + entry := sc["results"].([]map[string]any)[0] + errObj, _ := entry["error"].(map[string]any) + if entry["ok"] != false || errObj["code"] != CodeInvalidParams { + t.Fatalf("entry = %#v", entry) + } + r.expectNothing() +} + +func TestListFilesBatchRejectsTooManyIDs(t *testing.T) { + r := newFileRig(t) + ids := make([]string, listFilesBatchMaxIDs+1) + for i := range ids { + ids[i] = "1" + } + body, _ := json.Marshal(map[string]any{"ids": ids}) + _, rerr := r.s.callListFiles(context.Background(), body) + if rerr == nil || rerr.Code != CodeInvalidParams { + t.Fatalf("error = %v, want -32602", rerr) + } +} + +func TestListFilesBatchAcceptsEmptyIDs(t *testing.T) { + // The schema's anyOf accepts ids alone, including an empty array; Win32 + // answers total=0 rather than calling it a missing id. + r := newFileRig(t) + res, rerr := r.s.callListFiles(context.Background(), []byte(`{"ids":[]}`)) + if rerr != nil { + t.Fatalf("batch failed: %v", rerr) + } + sc := res.(toolResult).StructuredContent.(map[string]any) + checkInt(t, sc, "total", 0) + checkInt(t, sc, "succeeded", 0) + if results := sc["results"].([]map[string]any); len(results) != 0 { + t.Fatalf("results = %#v", results) + } + r.expectNothing() +} + +func TestListFilesBatchReportsBusyHost(t *testing.T) { + r := newFileRig(t) + main2 := r.registerDevice("1002", "10.0.0.2") + if _, ok := r.s.locks.tryAcquire("1001", "get_screenshot"); !ok { + t.Fatal("could not take the device lock for the test") + } + defer r.s.locks.release("1001") + + ch := r.call(`{"ids":["1001","1002"],"path":"C:\\"}`) + r.answerDirectoryCall(main2, "1002", `C:\`, fileRec{name: "b.txt", size: 5}) + res := r.wait(ch) + if res.err != nil { + t.Fatalf("batch failed: %v", res.err) + } + + sc := res.res.StructuredContent.(map[string]any) + checkInt(t, sc, "succeeded", 1) + checkInt(t, sc, "failed", 1) + checkInt(t, sc, "skipped", 0) + results := sc["results"].([]map[string]any) + busy := results[0] + errObj, _ := busy["error"].(map[string]any) + if busy["ok"] != false || errObj["code"] != CodeBusy { + t.Fatalf("results[0] = %#v", busy) + } + if results[1]["ok"] != true { + t.Fatalf("results[1] = %#v", results[1]) + } + // The finished host retires its sub-conn with COMMAND_BYE; the locked host + // was never contacted. + if got := r.nextAny(); !bytes.Equal(got.data, []byte{protocol.CommandBye}) { + t.Fatalf("unexpected wire after the batch: %v", got.data) + } + r.expectNothing() +} + +func TestListFilesBatchRunningHostOutlivesDeadline(t *testing.T) { + // Win32's deadline only stops *starting* new hosts: the host already running + // gets its own timeout and is recorded as a normal success, not skipped or + // "cancelled". + r := newFileRig(t) + oldDeadline, oldTimeout := listFilesBatchDeadline, fileListTimeout + listFilesBatchDeadline, fileListTimeout = 50*time.Millisecond, 5*time.Second + t.Cleanup(func() { listFilesBatchDeadline, fileListTimeout = oldDeadline, oldTimeout }) + + ch := r.call(`{"ids":["1001","1002"],"path":"C:\\"}`) + if got := r.next(r.main); !bytes.Equal(got, []byte{protocol.CommandListDrive}) { + t.Fatalf("drive request wire = %v", got) + } + sub := r.newSub() + if !r.s.OnFilePacket(sub, driveListPacket(driveRec{'C', 3, 500000, 123456, "本地磁盘", "NTFS"})) { + t.Fatal("drive-list packet was not consumed") + } + if got := r.next(sub); got[0] != protocol.CommandListFiles { + t.Fatalf("directory request wire = %v", got) + } + time.Sleep(150 * time.Millisecond) // past the 50 ms batch deadline + if !r.s.OnFilePacket(sub, fileListPacket(fileRec{name: "a.txt", size: 3})) { + t.Fatal("file-list packet was not consumed") + } + + res := r.wait(ch) + if res.err != nil { + t.Fatalf("batch failed: %v", res.err) + } + sc := res.res.StructuredContent.(map[string]any) + checkInt(t, sc, "succeeded", 1) + checkInt(t, sc, "failed", 0) + checkInt(t, sc, "skipped", 1) + results := sc["results"].([]map[string]any) + if results[0]["ok"] != true { + t.Fatalf("results[0] = %#v", results[0]) + } + if results[1]["ok"] != false || results[1]["skipped"] != true { + t.Fatalf("results[1] = %#v", results[1]) + } + // The finished host retires its sub-conn with COMMAND_BYE; host 1002 got nothing. + if got := r.nextAny(); !bytes.Equal(got.data, []byte{protocol.CommandBye}) { + t.Fatalf("unexpected wire after the batch: %v", got.data) + } + r.expectNothing() +} diff --git a/server/go/mcp/filev2.go b/server/go/mcp/filev2.go index e61de9a..edfd4e5 100644 --- a/server/go/mcp/filev2.go +++ b/server/go/mcp/filev2.go @@ -310,7 +310,7 @@ func (t *transferSession) acceptChunk(ctx *connection.Context, transferID uint64 return } if flags&ffV2Directory != 0 { - t.fail(CodeInvalidParams, "Not a single regular file (directory or multiple matches): %s — use list_files / search_file to pick a specific file", t.remotePath) + t.fail(CodeInvalidParams, "Not a single regular file (directory or multiple matches): %s — use list_files to pick a specific file", t.remotePath) return } rel, ok := transferNameWithinDir(t.targetDir, nameStr) @@ -328,12 +328,14 @@ func (t *transferSession) acceptChunk(ctx *connection.Context, transferID uint64 // were the answer. totalFiles == 0 means "not reported": older senders // may leave it unset, and a single file is still the only valid read. if totalFiles > 1 { - t.fail(CodeInvalidParams, "Not a single regular file (directory or multiple matches): %s — use list_files / search_file to pick a specific file", t.remotePath) + t.fail(CodeInvalidParams, "Not a single regular file (directory or multiple matches): %s — use list_files to pick a specific file", t.remotePath) return } if fileSize > t.maxFileBytes { t.fail(CodeInvalidParams, - "File is larger than %d bytes: use download_file to fetch it (%s)", t.maxFileBytes, t.remotePath) + "File is larger than %d bytes: this minimal server has no download_file; read it in parts with "+ + "terminal_exec (type/tail/Get-Content) or use the Windows controller server (%s)", + t.maxFileBytes, t.remotePath) return } if offset != 0 { @@ -353,7 +355,7 @@ func (t *transferSession) acceptChunk(ctx *connection.Context, transferID uint64 t.haveFile = true } else if fileIndex != t.fileIndex { // A second file index means the remote path matched more than one file. - t.fail(CodeInvalidParams, "Not a single regular file (directory or multiple matches): %s — use list_files / search_file to pick a specific file", t.remotePath) + t.fail(CodeInvalidParams, "Not a single regular file (directory or multiple matches): %s — use list_files to pick a specific file", t.remotePath) return } diff --git a/server/go/mcp/filev2_test.go b/server/go/mcp/filev2_test.go index 21f0372..d173667 100644 --- a/server/go/mcp/filev2_test.go +++ b/server/go/mcp/filev2_test.go @@ -256,7 +256,8 @@ func TestReadFileSizeGate(t *testing.T) { if c.err == nil || c.err.Code != CodeInvalidParams { t.Fatalf("error = %+v, want -32602", c.err) } - if !strings.Contains(c.err.Message, "download_file") { + if !strings.Contains(c.err.Message, "no download_file") || + !strings.Contains(c.err.Message, "terminal_exec") { t.Fatalf("message = %q", c.err.Message) } } diff --git a/server/go/mcp/server.go b/server/go/mcp/server.go index 684d594..f6bf2a7 100644 --- a/server/go/mcp/server.go +++ b/server/go/mcp/server.go @@ -409,7 +409,8 @@ const serverInstructions = `这是 YAMA 服务端的 MCP 端点(Go 实现) 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 的 screen 模式按链路状况自适应缩放,max_width 省略时最大 1024;region/window/monitor 模式需要声明 CLIENT_CAP_SCREEN_REGION 的较新 Windows 客户端,否则返回 -32005。 -5) list_files / read_file 走文件传输通道;read_file 只接受单个普通文件且不超过 2 MiB,目录用 list_files,大文件分段读取。 -6) terminal_exec 需要客户端支持终端(CLIENT_CAP_TERMINAL),会在目标主机上创建持久会话;用完调用 terminal_close 释放,闲置会话由服务端回收。 -7) 列表与详情都是调用时刻的快照,主机可能在操作期间掉线;写操作前先读一次现状,动作后再复核。` +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) 列表与详情都是调用时刻的快照,主机可能在操作期间掉线;写操作前先读一次现状,动作后再复核。` diff --git a/server/go/mcp/tools_term.go b/server/go/mcp/tools_term.go index 0bebe55..694cad7 100644 --- a/server/go/mcp/tools_term.go +++ b/server/go/mcp/tools_term.go @@ -271,8 +271,10 @@ func (s *Server) terminalSessionFor(deviceID, sessionID string) (*termSession, b } 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 for host %s is held by another viewer (web console or another MCP call); close it first", deviceID) + "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): @@ -349,9 +351,11 @@ func (s *Server) awaitAndDeliver(ctx context.Context, sess *termSession, p *pend sess.cond.Wait() } if ctx.Err() != nil { - // The HTTP client is gone; the command keeps running (design §6.6). + // 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, poll with session_id to collect its output") + "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