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:
1 parent
61b9031269
commit
31883edc09
6 files changed
+433
-32
No files matched your search
+147
-17
@@ -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")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user