Fix(mcp): put listing rows and host ids into text blocks

MCP clients that surface only content[].text saw just count summaries from
list_hosts and get_audit_log; the 64-bit host id lived only in
structuredContent. Without the id, read_file, get_host_detail and
terminal_exec cannot be addressed, so the tools were unusable from those
clients.

Append a tab-separated table after the summary for every list-shaped local
tool: list_hosts (id first, then name/ip/group/os/online/clientType/
last_seen), get_audit_log (time/type/msg), list_files (drives and directory
entries) and get_host_detail (compact host JSON; id/ok/detail rows for a
batch call). Only the returned page is rendered, cells are flattened to one
line, and the truncation note stays on its own line before the table.

structuredContent is unchanged and remains the authoritative copy. Tests
cover row contents, paging, escaping and truncation ordering; a live run
against a Debug client confirmed the id is now visible in text. The MFC
server needs no equivalent change: BuildResult already appends the full
structuredContent as a second text item, so text-only clients there already
receive host ids. Go's envelope emits a single text item, which is why the
rows go into it.

Co-Authored-By: deepseek-flash
This commit is contained in:
yuanyuanxianganddeepseek-flash committed 2026-11-13 11:25:57 +01:00
1 parent 70556391dd
commit 3d18b2119a
5 files changed
+197 -4

No files matched your search

+20
View File
@@ -6,6 +6,7 @@ import (
"encoding/json"
"errors"
"fmt"
"strconv"
"strings"
"sync"
"time"
@@ -580,6 +581,8 @@ func listFilesResult(args listFilesArgs, drives []driveEntry, files []fileEntry,
var structured map[string]any
var text string
var header []string
var rows [][]string
if drives != nil {
total := len(drives)
begin := min(offset, total)
@@ -593,6 +596,14 @@ func listFilesResult(args listFilesArgs, drives []driveEntry, files []fileEntry,
"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)
@@ -606,9 +617,18 @@ func listFilesResult(args listFilesArgs, drives []driveEntry, files []fileEntry,
"hasMore": end < total,
}
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 条,只解析了前 %d 条。", fileListMaxEntries, fileListMaxEntries)
}
text = appendRows(text, header, rows)
return newToolResult(text, structured)
}
+17
View File
@@ -304,6 +304,10 @@ func TestListFilesDrives(t *testing.T) {
if !strings.Contains(c.res.Content[0].Text, "共 2 个驱动器") {
t.Fatalf("summary = %q", c.res.Content[0].Text)
}
if !strings.Contains(c.res.Content[0].Text, "drive\ttypeName\tfileSystem\ttotalMB\tfreeMB") ||
!strings.Contains(c.res.Content[0].Text, "C:\\\t本地磁盘\tNTFS\t500000\t123456") {
t.Fatalf("text = %q, want drive rows", c.res.Content[0].Text)
}
// A drive-only listing still leaves the sub-conn to be retired.
if got := r.next(sub); !bytes.Equal(got, []byte{protocol.CommandBye}) {
@@ -376,6 +380,15 @@ func TestListFilesDirectory(t *testing.T) {
!strings.Contains(c.res.Content[0].Text, "第 2-3 条") {
t.Fatalf("summary = %q", c.res.Content[0].Text)
}
if !strings.Contains(c.res.Content[0].Text, "name\tisDir\tsize\tmtime") ||
!strings.Contains(c.res.Content[0].Text, "a.txt\tfalse\t12345\t1700000000") ||
!strings.Contains(c.res.Content[0].Text, "中文文档.docx\tfalse\t5368709120\t1600000000") {
t.Fatalf("text = %q, want file rows for the returned page", c.res.Content[0].Text)
}
// The page window (offset 1) applies to the table as well.
if strings.Contains(c.res.Content[0].Text, "子目录") {
t.Fatalf("text = %q, offset-skipped entry leaked into the table", c.res.Content[0].Text)
}
if got := r.next(sub); !bytes.Equal(got, []byte{protocol.CommandBye}) {
t.Fatalf("retire wire = %v, want COMMAND_BYE", got)
@@ -713,6 +726,10 @@ func TestListFilesTruncationNote(t *testing.T) {
if !strings.Contains(c.res.Content[0].Text, "只解析了前") {
t.Fatalf("summary does not mention the cap: %q", c.res.Content[0].Text)
}
// The note must stay on its own line, before the table.
if !strings.Contains(c.res.Content[0].Text, "。\nname\tisDir\tsize\tmtime\n") {
t.Fatalf("truncation note glued to the table: %q", c.res.Content[0].Text)
}
}
func TestParseFileListEntryCap(t *testing.T) {
+100 -1
View File
@@ -195,6 +195,7 @@ func (s *Server) callListHosts(_ context.Context, raw json.RawMessage) (any, *rp
if total != totalAll {
text += fmt.Sprintf("过滤前共 %d 台。", totalAll)
}
text = appendHostRows(text, hosts)
return newToolResult(text, structured), nil
}
@@ -298,7 +299,7 @@ func (s *Server) callGetHostDetail(_ context.Context, raw json.RawMessage) (any,
if rerr != nil {
return nil, rerr
}
return newToolResult(hostSummary(host), map[string]any{"host": host}), nil
return newToolResult(hostDetailText(host), map[string]any{"host": host}), nil
}
func (s *Server) hostDetailBatch(ids []string) (any, *rpcError) {
@@ -339,6 +340,7 @@ func (s *Server) hostDetailBatch(ids []string) (any, *rpcError) {
}
text := fmt.Sprintf("批量调用 get_host_detail:共 %d 台,成功 %d 台,失败 %d 台。",
len(ids), succeeded, failed)
text = appendBatchRows(text, results)
return newToolResult(text, structured), nil
}
@@ -416,6 +418,58 @@ func hostSummary(h map[string]any) string {
return fmt.Sprintf("主机 %s (%s) 的详情。", name, ip)
}
// hostDetailText is the text block for one host: the summary line followed by
// the host object as compact JSON. Text-only MCP clients never surface
// structuredContent, so without this they would see neither the id nor any
// field of the host they just asked about.
func hostDetailText(h map[string]any) string {
summary := hostSummary(h)
b, err := json.Marshal(h)
if err != nil {
return summary
}
return summary + "\n" + string(b)
}
// appendHostRows renders the returned page as a tab-separated table. The host
// id comes first because every follow-up tool (read_file, get_host_detail,
// terminal_exec, ...) is addressed by it.
func appendHostRows(text string, hosts []map[string]any) string {
rows := make([][]string, 0, len(hosts))
for _, h := range hosts {
online, _ := h["online"].(bool)
rows = append(rows, []string{
tableText(h["id"]), tableText(h["name"]), tableText(h["ip"]),
tableText(h["group"]), tableText(h["os"]), strconv.FormatBool(online),
tableText(h["clientType"]), tableText(h["last_seen"]),
})
}
return appendRows(text,
[]string{"id", "name", "ip", "group", "os", "online", "clientType", "last_seen"},
rows)
}
// appendBatchRows lists each batch result on its own line: failures carry the
// error message, successes the full host JSON.
func appendBatchRows(text string, results []map[string]any) string {
rows := make([][]string, 0, len(results))
for _, r := range results {
ok, _ := r["ok"].(bool)
var detail string
if ok {
if data, _ := r["data"].(map[string]any); data != nil {
if b, err := json.Marshal(data["host"]); err == nil {
detail = string(b)
}
}
} else {
detail, _ = r["text"].(string)
}
rows = append(rows, []string{tableText(r["id"]), strconv.FormatBool(ok), detail})
}
return appendRows(text, []string{"id", "ok", "detail"}, rows)
}
// ----- get_server_status ----------------------------------------------------
func (s *Server) callGetServerStatus(_ context.Context, _ json.RawMessage) (any, *rpcError) {
@@ -510,6 +564,11 @@ func (s *Server) callGetAuditLog(_ context.Context, raw json.RawMessage) (any, *
if res.Truncated {
text += "(审计文件较大,仅扫描最近 32 MB。)"
}
rows := make([][]string, 0, len(entries))
for _, e := range entries {
rows = append(rows, []string{tableText(e["time"]), tableText(e["type"]), tableText(e["msg"])})
}
text = appendRows(text, []string{"time", "type", "msg"}, rows)
return newToolResult(text, structured), nil
}
@@ -547,6 +606,46 @@ func clampPageLimit(n int) int {
return n
}
// appendRows appends a tab-separated table to a summary line. The first
// column is always the addressable key (host id, file name, ...), because a
// text-only client sees only content[].text and needs the key for the next
// call. structuredContent remains the authoritative, exact copy.
func appendRows(text string, header []string, rows [][]string) string {
if len(rows) == 0 {
return text
}
var b strings.Builder
b.WriteString(text)
b.WriteByte('\n')
b.WriteString(strings.Join(header, "\t"))
for _, row := range rows {
b.WriteByte('\n')
for i, cell := range row {
if i > 0 {
b.WriteByte('\t')
}
b.WriteString(oneLine(cell))
}
}
return b.String()
}
// tableText extracts a string field. An absent field yields "", which oneLine
// renders as "-".
func tableText(v any) string {
s, _ := v.(string)
return s
}
// oneLine keeps a table cell on one line: a tab or newline inside a value
// would break the column layout. The exact value stays in structuredContent.
func oneLine(s string) string {
if s == "" {
return "-"
}
return strings.NewReplacer("\t", " ", "\r", " ", "\n", " ").Replace(s)
}
// pageSummary mirrors the Win32 server's summary line:
// 「共 N 台主机,本次返回第 1-100 条(还有更多,可用 offset 继续取)。」
func pageSummary(total, limit, offset int, unit string) string {
+36 -3
View File
@@ -201,6 +201,18 @@ func wantIDs(t *testing.T, hosts []map[string]any, want ...string) {
}
}
func TestAppendRowsSanitizesCells(t *testing.T) {
got := appendRows("head", []string{"a", "b"},
[][]string{{"x\ty", "line\nbreak"}, {"", ""}})
want := "head\na\tb\nx y\tline break\n-\t-"
if got != want {
t.Fatalf("appendRows = %q, want %q", got, want)
}
if got := appendRows("head", []string{"a"}, nil); got != "head" {
t.Fatalf("empty rows = %q, want unchanged summary", got)
}
}
func TestListHostsPoolsAndProjection(t *testing.T) {
f := newLocalFixture(t)
@@ -222,6 +234,14 @@ func TestListHostsPoolsAndProjection(t *testing.T) {
if !strings.Contains(text, "共 3 台主机") {
t.Fatalf("text = %q, want host count", text)
}
// Text-only MCP clients never see structuredContent, so the table in the
// text block must carry the id every follow-up call is addressed by.
if !strings.Contains(text, "id\tname\tip\tgroup\tos\tonline\tclientType\tlast_seen") {
t.Fatalf("text = %q, want host table header", text)
}
if !strings.Contains(text, "1001\tALPHA\t10.0.0.1\tdefault\tWindows 10\ttrue\tEXE\t-") {
t.Fatalf("text = %q, want ALPHA row with id first", text)
}
alpha := hosts[0]
if got := strField(t, alpha, "name"); got != "ALPHA" {
@@ -384,7 +404,11 @@ func TestListHostsPaging(t *testing.T) {
func TestGetHostDetailOnlineAndOffline(t *testing.T) {
f := newLocalFixture(t)
_, sc := mustCallLocal(t, f.srv, "get_host_detail", `{"id":"1001"}`)
text, sc := mustCallLocal(t, f.srv, "get_host_detail", `{"id":"1001"}`)
if !strings.Contains(text, "\n") || !strings.Contains(text, `"id":"1001"`) ||
!strings.Contains(text, `"name":"ALPHA"`) {
t.Fatalf("text = %q, want summary plus host JSON", text)
}
host, ok := sc["host"].(map[string]any)
if !ok {
t.Fatalf("host = %v", sc["host"])
@@ -457,7 +481,12 @@ func TestGetHostDetailOnlineAndOffline(t *testing.T) {
func TestGetHostDetailBatch(t *testing.T) {
f := newLocalFixture(t)
_, sc := mustCallLocal(t, f.srv, "get_host_detail", `{"ids":["1001","9999","2001"]}`)
text, sc := mustCallLocal(t, f.srv, "get_host_detail", `{"ids":["1001","9999","2001"]}`)
if !strings.Contains(text, "id\tok\tdetail") ||
!strings.Contains(text, "1001\ttrue\t{") ||
!strings.Contains(text, "9999\tfalse\t") {
t.Fatalf("text = %q, want one row per id", text)
}
if got := strField(t, sc, "tool"); got != "get_host_detail" {
t.Fatalf("tool = %q", got)
}
@@ -573,7 +602,11 @@ func TestGetAuditLog(t *testing.T) {
)
s := New(Config{Token: "test-token", AuditPath: path})
_, sc := mustCallLocal(t, s, "get_audit_log", `{}`)
text, sc := mustCallLocal(t, s, "get_audit_log", `{}`)
if !strings.Contains(text, "time\ttype\tmsg") ||
!strings.Contains(text, "2026-11-12T10:03:00Z\tdevice.online\t") {
t.Fatalf("text = %q, want audit rows", text)
}
entries, ok := sc["entries"].([]any)
if !ok || len(entries) != 4 {
t.Fatalf("entries = %v, want 4", sc["entries"])