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
This commit is contained in:
yuanyuanxianganddeepseek-flash committed 2026-11-13 12:57:12 +01:00
1 parent 61b9031269
commit 31883edc09
6 files changed
+433 -32

No files matched your search

+266 -3
View File
@@ -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()
}