package mcp import ( "context" "encoding/binary" "encoding/json" "errors" "fmt" "strconv" "strings" "sync" "time" "github.com/yuanyuanxiang/SimpleRemoter/server/go/connection" "github.com/yuanyuanxiang/SimpleRemoter/server/go/hub" "github.com/yuanyuanxiang/SimpleRemoter/server/go/protocol" ) // 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 // TOKEN_DRIVE_LIST(103) — the sub-conn stays open // that sub : COMMAND_LIST_FILES(2) [path\0] // └─ TOKEN_FILE_LIST(104) or TOKEN_FILE_LIST_ERROR(171) // then the server closes the sub-conn (COMMAND_BYE + 500 ms) // // The sub-conn carries ConnAuth, so handleConnAuth has already pinned the // device's ClientID on its ctx and no pending-connection bookkeeping is needed // (design §5.3); the pending request is keyed by device and remembers which // ctx answered, which is also how late packets from a previous sub-conn are // told apart from the current one. const ( // fileListMaxEntries is the parse cap shared with the Win32 server: the // directory is parsed in full and paged afterwards, so total/hasMore stay // true; only a pathological directory is cut here, and structuredContent // then carries truncated=true and the summary says so. fileListMaxEntries = 100000 // fileRecordFixedLen is attr(1) + size(8) + FILETIME(8). fileRecordFixedLen = 17 // driveRecordFixedLen is letter(1) + type(1) + totalMB(4) + freeMB(4). driveRecordFixedLen = 10 // filetimeEpochDiff converts FILETIME (100 ns ticks since 1601-01-01) to // Unix seconds once divided by filetimeTicksPerSec. filetimeTicksPerSec = 10000000 filetimeEpochDiffSec = 11644473600 errorAccessDenied = 5 errorFileNotFound = 2 errorPathNotFound = 3 // 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 // fileRetireDelay is how long the sub-conn stays open after COMMAND_BYE, so the // client's read loop sees the goodbye before FIN (the hub uses the same 500 ms // for screen sub-conns). var fileRetireDelay = 500 * time.Millisecond // fileEventKind distinguishes the three packets a list_files call can receive. type fileEventKind byte const ( fileEventDriveList fileEventKind = iota + 1 // TOKEN_DRIVE_LIST fileEventFileList // TOKEN_FILE_LIST fileEventError // TOKEN_FILE_LIST_ERROR ) // fileEvent is one packet handed from the TCP read loop to the waiting call. // ctx identifies the sub-conn it arrived on; payload bytes are copied because // the read buffer is not ours to keep. type fileEvent struct { kind fileEventKind ctx *connection.Context payload []byte // drive records or file records (token byte removed) win32err uint32 // fileEventError only } // fileRequest is one in-flight list_files call. ch is buffered so the read loop // never blocks; sub records which sub-conn answered the drive-list phase and // rejects packets from any other connection for the same device. abandoned is // set by cancel so a packet that loses the race with the call's own return is // not queued into a channel nobody reads. type fileRequest struct { ch chan fileEvent mu sync.Mutex sub *connection.Context abandoned bool } func (r *fileRequest) subConn() *connection.Context { r.mu.Lock() defer r.mu.Unlock() return r.sub } // fileTable holds the single pending list_files per device. The per-device // call lock already serialises tools, so more than one entry cannot normally // exist; the table rejects it anyway rather than mis-routing replies. type fileTable struct { mu sync.Mutex byDevice map[string]*fileRequest } func newFileTable() *fileTable { return &fileTable{byDevice: make(map[string]*fileRequest)} } func (t *fileTable) begin(deviceID string) (*fileRequest, bool) { t.mu.Lock() defer t.mu.Unlock() if _, ok := t.byDevice[deviceID]; ok { return nil, false } r := &fileRequest{ch: make(chan fileEvent, 2)} t.byDevice[deviceID] = r return r, true } // cancel ends the request and returns the sub-conn it learned about, if any. // The caller retires that sub-conn: this is the single retirement point, so a // call that gives up while its drive-list packet is already queued (the timer // and the channel being ready at the same time, or the MCP request cancelled) // still closes the client's file-manager thread instead of leaking it. func (t *fileTable) cancel(deviceID string, r *fileRequest) *connection.Context { t.mu.Lock() if t.byDevice[deviceID] == r { delete(t.byDevice, deviceID) } t.mu.Unlock() r.mu.Lock() r.abandoned = true sub := r.sub r.mu.Unlock() return sub } // deliver routes one event to the pending call. It reports whether the event // was accepted; a packet from a connection other than the one that answered // the drive-list phase is a late packet from an earlier sub-conn and must be // ignored (the client sends a legacy one-byte TOKEN_FILE_LIST right after // TOKEN_FILE_LIST_ERROR, and back-to-back calls can overlap with it). func (t *fileTable) deliver(deviceID string, ev fileEvent) bool { t.mu.Lock() r := t.byDevice[deviceID] t.mu.Unlock() if r == nil { return false } r.mu.Lock() if r.abandoned { // The call already returned; let OnFilePacket treat the packet as an // orphan (a drive list) instead of queueing it for nobody. r.mu.Unlock() return false } switch ev.kind { case fileEventDriveList: if r.sub != nil && r.sub != ev.ctx { r.mu.Unlock() return false } if r.sub == nil { r.sub = ev.ctx } case fileEventError: // No client answers COMMAND_LIST_DRIVE with an error, but if one ever // does, adopt the connection and let the call translate the code // instead of dropping the packet and timing out. if r.sub == nil { r.sub = ev.ctx } if r.sub != ev.ctx { r.mu.Unlock() return false } default: if r.sub != ev.ctx { r.mu.Unlock() return false } } r.mu.Unlock() select { case r.ch <- ev: default: // The current phase already has an event queued; a duplicate is only // noise (the legacy empty TOKEN_FILE_LIST after an error packet). } return true } func (s *Server) registerFileTools() { s.handlers["list_files"] = s.callListFiles s.handlers["read_file"] = s.callReadFile } // OnFilePacket feeds one file-manager packet from a sub-connection to the // pending list_files call. It reports whether the packet belongs to this // protocol at all; cmd/main.go forwards only the three file-manager tokens. func (s *Server) OnFilePacket(ctx *connection.Context, data []byte) bool { if s == nil || len(data) == 0 { return false } switch data[0] { case protocol.TokenDriveList, protocol.TokenFileList, protocol.TokenFileListError: default: return false } deviceID := ctx.GetInfo().ClientID if deviceID == "" { return true } if s.cfg.Hub != nil { if main := s.cfg.Hub.MainConn(deviceID); main == ctx { // File-manager packets only ever arrive on the dedicated sub-conn; // a token that looks like one on the main connection is not ours. return true } } ev := fileEvent{ctx: ctx} switch data[0] { case protocol.TokenDriveList: ev.kind = fileEventDriveList ev.payload = append([]byte(nil), data[1:]...) case protocol.TokenFileList: ev.kind = fileEventFileList ev.payload = append([]byte(nil), data[1:]...) case protocol.TokenFileListError: ev.kind = fileEventError if len(data) >= 5 { ev.win32err = binary.LittleEndian.Uint32(data[1:5]) } } if s.files.deliver(deviceID, ev) { return true } // Nothing is waiting for this sub-conn: the call it belonged to already // timed out or finished. Retire it so the client does not leak its // file-manager thread, but only once the sub-conn has announced itself. // A live read_file keeps its file-manager sub-conn registered in the // transfer table (POSIX clients stream on it), so never close that one. if ev.kind == fileEventDriveList && !s.transfers.owns(ctx) { s.retireFileConn(ctx) } return true } // retireFileConn closes a file-manager sub-conn the way the hub retires screen // sub-conns: COMMAND_BYE so the client's IOCP loop exits through its clean // path, then a delayed Close so the goodbye is not overtaken by FIN. func (s *Server) retireFileConn(ctx *connection.Context) { if ctx == nil { return } if s.cfg.Hub != nil { _ = s.cfg.Hub.SendToConn(ctx, []byte{protocol.CommandBye}) } // Read the delay before spawning: tests shorten it between calls. delay := fileRetireDelay go func(c *connection.Context) { time.Sleep(delay) _ = c.Close() }(ctx) } // ----- get_screenshot-style argument / result shapes ------------------------- // 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"` Path string `json:"path"` Limit int `json:"limit"` Offset int `json:"offset"` } type driveEntry struct { Drive string `json:"drive"` Type uint64 `json:"type"` TypeName string `json:"typeName"` FileSystem string `json:"fileSystem"` TotalMB uint64 `json:"totalMB"` FreeMB uint64 `json:"freeMB"` } type fileEntry struct { Name string `json:"name"` IsDir bool `json:"isDir"` Size uint64 `json:"size"` Mtime int64 `json:"mtime"` } // openFileManagerConn asks the device for its file-manager sub-connection // (COMMAND_LIST_DRIVE on the main connection) and waits for the drive list. // On success it returns the sub-connection, the still-pending request (later // packets are matched against it) and the parsed drives; the caller owns both // and must call closeFileManagerConn when done. Every failure path retires the // sub-connection here, so a timed-out or rejected handshake leaves no orphan // file-manager thread on the client. func (s *Server) openFileManagerConn(ctx context.Context, deviceID string) (*connection.Context, *fileRequest, []driveEntry, *rpcError) { req, ok := s.files.begin(deviceID) if !ok { return nil, nil, nil, errf(CodeBusy, "Device busy: another file request is already pending for host %s", deviceID) } keep := false defer func() { if !keep { if sub := s.files.cancel(deviceID, req); sub != nil { s.retireFileConn(sub) } } }() if err := s.cfg.Hub.SendToDevice(deviceID, []byte{protocol.CommandListDrive}); err != nil { if errors.Is(err, hub.ErrDeviceOffline) { return nil, nil, nil, errf(CodeOffline, "Host not found or offline: %s", deviceID) } return nil, nil, nil, errf(CodeSendFailed, "Failed to ask the host for its file-manager channel: %v", err) } timer := time.NewTimer(fileListTimeout) defer timer.Stop() select { case ev := <-req.ch: switch ev.kind { case fileEventDriveList: keep = true return ev.ctx, req, parseDriveList(ev.payload), nil case fileEventError: return nil, nil, nil, errf(win32ErrorCode(ev.win32err), "Failed to open the file-manager channel on host %s (win32=%d)", deviceID, ev.win32err) default: return nil, nil, nil, errf(CodeInternal, "Unexpected file-manager reply while listing drives") } case <-timer.C: return nil, nil, nil, errf(CodeTimeout, "Timeout waiting for the host to open a file-manager channel (%s). Older clients that do not implement file browsing stay silent; retrying will not help.", fileListTimeout) case <-ctx.Done(): return nil, nil, nil, errf(CodeTimeout, "Request cancelled while waiting for the host's file-manager channel") } } // closeFileManagerConn ends the request and retires the sub-connection it // learned about. It is the single retirement point for that sub-conn: the // cancel below also covers a call that gave up while its drive-list packet was // already queued (the select taking the timer branch with both ready). func (s *Server) closeFileManagerConn(deviceID string, req *fileRequest) { if sub := s.files.cancel(deviceID, req); sub != nil { s.retireFileConn(sub) } } // 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") } var args listFilesArgs if rerr := decodeArgs(raw, &args); rerr != nil { return nil, rerr } // 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 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 toolResult{}, errf(CodeInvalidParams, "Invalid path: NUL and line breaks are not allowed") } if s.cfg.Hub.MainConn(args.ID) == nil { return toolResult{}, errf(CodeOffline, "Host not found or offline: %s", args.ID) } path := args.Path // The published contract (tools.json) is: no path lists drives, any path // lists that directory. MFC also folds "." and "/" into the drive list, // but that makes a POSIX root listing unreachable, so this server follows // the documented rule instead. listDrives := path == "" pathGBK := protocol.UTF8ToGBK(path) if len(pathGBK) >= 250 { // The client copies the path into a MAX_PATH buffer and appends "\\*.*". 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 toolResult{}, rerr } defer s.closeFileManagerConn(args.ID, req) if listDrives { return listFilesResult(args, drives, nil, false), nil } // Phase 2: reuse the same sub-conn for the directory itself. pkt := make([]byte, 0, 2+len(pathGBK)) pkt = append(pkt, protocol.CommandListFiles) pkt = append(pkt, pathGBK...) pkt = append(pkt, 0) if err := s.cfg.Hub.SendToConn(sub, pkt); err != nil { return toolResult{}, errf(CodeSendFailed, "Failed to send the directory request on the file-manager channel: %v", err) } timer := time.NewTimer(fileListTimeout) defer timer.Stop() select { case ev := <-req.ch: switch ev.kind { case fileEventFileList: files, truncated := parseFileList(ev.payload) return listFilesResult(args, nil, files, truncated), nil case fileEventError: return toolResult{}, fileWin32Error(ev.win32err, path) default: return toolResult{}, errf(CodeInternal, "Unexpected file-manager reply while listing a directory") } case <-timer.C: 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 toolResult{}, errf(CodeTimeout, "Request cancelled while waiting for the directory listing") } } // win32ErrorCode maps a client-reported Win32 error onto an MCP code the same // way the Win32 server does: 5 is a permission problem, 2/3 mean "no such // target", everything else is an internal failure carrying the raw code. func win32ErrorCode(win32err uint32) int { switch win32err { case errorAccessDenied: return CodePermission case errorFileNotFound, errorPathNotFound: return CodeNotFound default: return CodeInternal } } // fileWin32Error maps the client's win32 error onto MCP codes the same way the // Win32 server does: 5 is a permission problem, 2/3 mean "no such target", // everything else is an internal failure carrying the raw code. func fileWin32Error(win32err uint32, path string) *rpcError { subject := fmt.Sprintf("Failed to list %q", path) switch win32err { case errorAccessDenied: return errf(CodePermission, "%s: access denied (win32=%d)", subject, win32err) case errorFileNotFound, errorPathNotFound: return errf(CodeNotFound, "%s: target not found (win32=%d)", subject, win32err) default: return errf(CodeInternal, "%s: the host reported a failure (win32=%d)", subject, win32err) } } // parseDriveList decodes [letter][type][totalMB:4 LE][freeMB:4 LE][typeName\0][fs\0] // records until a zero letter (the client's end marker) or a truncated record. // Names are GBK on the wire for every platform. func parseDriveList(p []byte) []driveEntry { out := make([]driveEntry, 0, 8) off := 0 for off+driveRecordFixedLen <= len(p) && p[off] != 0 { letter := p[off] dtype := uint64(p[off+1]) total := uint64(binary.LittleEndian.Uint32(p[off+2:])) free := uint64(binary.LittleEndian.Uint32(p[off+6:])) off += driveRecordFixedLen typeName, n, ok := cString(p[off:]) if !ok { break } off += n + 1 fs, n, ok := cString(p[off:]) if !ok { break } off += n + 1 // Windows letters become "C:\". The POSIX clients report '/' as their // single root "drive"; return it as "/" so it can be passed straight // back as a path (MFC renders "/:\", which also works after the // client's path conversion, but "/" is the friendlier form). drive := string(letter) + ":\\" if letter == '/' { drive = "/" } out = append(out, driveEntry{ Drive: drive, Type: dtype, TypeName: protocol.GbkToUTF8(typeName), FileSystem: protocol.GbkToUTF8(fs), TotalMB: total, FreeMB: free, }) } return out } // parseFileList decodes [attr][name\0][sizeHi:4][sizeLo:4][ftLo:4][ftHi:4] // records. An empty name is the client's trailing zero padding; reaching the // entry cap stops the parse and reports truncation. func parseFileList(p []byte) ([]fileEntry, bool) { out := make([]fileEntry, 0, 64) off := 0 for off < len(p) { attr := p[off] off++ name, n, ok := cString(p[off:]) if !ok || n == 0 { break } // Cap check after a real record is seen: trailing zero padding (an empty // name) must not report truncation when the listing is exactly at the cap. if len(out) >= fileListMaxEntries { return out, true } off += n + 1 if off+fileRecordFixedLen-1 > len(p) { break } sizeHigh := uint64(binary.LittleEndian.Uint32(p[off:])) sizeLow := uint64(binary.LittleEndian.Uint32(p[off+4:])) ftLow := uint64(binary.LittleEndian.Uint32(p[off+8:])) ftHigh := uint64(binary.LittleEndian.Uint32(p[off+12:])) off += 16 ft := ftHigh<<32 | ftLow var mtime int64 if ft != 0 { mtime = int64(ft/filetimeTicksPerSec) - filetimeEpochDiffSec if mtime < 0 { mtime = 0 } } out = append(out, fileEntry{ Name: protocol.GbkToUTF8(name), IsDir: attr&0x10 != 0, Size: sizeHigh<<32 | sizeLow, Mtime: mtime, }) } return out, false } // cString returns the NUL-terminated field at the start of p. ok is false when // p runs out before the terminator (a truncated packet). func cString(p []byte) (name []byte, n int, ok bool) { for i, b := range p { if b == 0 { return p[:i], i, true } } return nil, 0, false } // listFilesResult applies the limit/offset window and builds the MCP envelope. // Only one of drives/files is non-nil; total/totalAll/hasMore describe the // full listing, not the returned page. truncated reports that the directory // held more entries than the parse cap, so the model is not told "that is all // there is". func listFilesResult(args listFilesArgs, drives []driveEntry, files []fileEntry, truncated bool) toolResult { limit := clampPageLimit(args.Limit) offset := max(args.Offset, 0) var structured map[string]any var text string var header []string var rows [][]string if drives != nil { total := len(drives) begin := min(offset, total) end := min(begin+limit, total) structured = map[string]any{ "drives": drives[begin:end], "total": total, "totalAll": total, "limit": limit, "offset": offset, "hasMore": end < total, } text = pageSummary(total, limit, offset, "个驱动器") header = []string{"drive", "typeName", "fileSystem", "totalMB", "freeMB"} rows = make([][]string, 0, end-begin) for _, d := range drives[begin:end] { rows = append(rows, []string{ d.Drive, d.TypeName, d.FileSystem, strconv.FormatUint(d.TotalMB, 10), strconv.FormatUint(d.FreeMB, 10), }) } } else { total := len(files) begin := min(offset, total) end := min(begin+limit, total) structured = map[string]any{ "files": files[begin:end], "total": total, "totalAll": total, "limit": limit, "offset": offset, "hasMore": end < total, "truncated": truncated, } text = pageSummary(total, limit, offset, "个条目") header = []string{"name", "isDir", "size", "mtime"} rows = make([][]string, 0, end-begin) for _, f := range files[begin:end] { rows = append(rows, []string{ f.Name, strconv.FormatBool(f.IsDir), strconv.FormatUint(f.Size, 10), strconv.FormatInt(f.Mtime, 10), }) } } if truncated { text += fmt.Sprintf("目录条目超过 %d 条,total 只是上限内的数量,请缩小目录范围。", fileListMaxEntries) } text = appendRows(text, header, rows) return newToolResult(text, structured) }