Fix: Expose tool payloads in the content text block

List and query tools put only a human summary in content and kept the real
payload in structuredContent. Clients that hand just content to the model
(WorkBuddy does) therefore never saw a host id: search_hosts answered "1 host
matched" and every follow-up tool was out of reach, and guessed ids 1-3100
could never work because host ids are 64-bit snowflake values.

BuildResult now appends the serialized structuredContent as a second text
block, as the MCP spec recommends for tools with structured output. The append
sits in the single result choke point, so every tool in McpServer, McpMachine
and McpChat gains it, including future ones; empty action results such as
remote_mouse keep their bare "ok".

Tools whose text already carries the payload expose only the difference:
exec_command and terminal_exec add exit_code, get_keylog adds counters,
get_activity_history exposes records without the duplicated raw dump, and the
hosts file reader drops its copy of the content. The override rides in a $
key that BuildResult consumes and removes, so responses change only by the
extra block.

Verified on a Debug instance: list_all_hosts, search_hosts, get_server_status
and list_registry return parseable JSON in content[1] with ids intact, and
tools/mcp_smoke.ps1 -SkipHost passes 27/27 with four new assertions.

Co-Authored-By: deepseek-flash
This commit is contained in:
yuanyuanxianganddeepseek-flash committed 2026-10-26 14:12:50 +01:00
1 parent a7dd86ff0f
commit 27d40f5678
6 files changed
+153 -5

No files matched your search

+37 -3
View File
@@ -165,7 +165,7 @@ MCP 是 JSON-RPC 2.0。MVP 只需实现以下方法:
{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"list_online_hosts","arguments":{}}}
```
响应(结构化输出:`structuredContent` 承载主机数组,`content` 附带可读摘要):
响应(结构化输出:`structuredContent` 承载主机数组,`content` 是可读摘要 + 同一份结构的紧凑 JSON):
```json
{"jsonrpc":"2.0","id":3,"result":{
"structuredContent":{
@@ -175,10 +175,14 @@ MCP 是 JSON-RPC 2.0。MVP 只需实现以下方法:
"activeWindow":"WeChat","online":true,"group":"default","screen":"1:1920x1080","clientType":"EXE"}
]
},
"content":[{"type":"text","text":"共 1 台主机在线。"}],
"content":[
{"type":"text","text":"共 1 台主机在线。"},
{"type":"text","text":"{\"hosts\":[{\"id\":\"123\",\"name\":\"DESKTOP-ABC\",...}]}"}
],
"isError":false
}}
```
第二个文本块来自 §14:规范要求返回 `structuredContent` 时也把序列化 JSON 放进 TextContent,否则只读 `content` 的客户端拿不到 `id`。
#### 3.3.4 可选实现
@@ -456,7 +460,7 @@ void CMcpSettingsDlg::OnBnClickedBtnSave()
- ✅ **生效方式**:MCP 启用/端口/绑定/token 的改动均需重启服务端生效,对话框保存后弹窗提醒「重启程序生效」。
- ✅ **取数方案**:C(抽公共函数 `BuildHostJson`,MCP 与 WebService 平级复用)。
- ✅ **返回字段**:全量,含实时信息(`rtt` / `activeWindow`),支持 AI 监督场景。
- ✅ **序列化**:`structuredContent` + `outputSchema`,`content` 附带可读摘要。
- ✅ **序列化**:`structuredContent` + `outputSchema`,`content` 附带可读摘要(2026-10-26 起再追加一份紧凑 JSON,见 §14)。
---
@@ -801,3 +805,33 @@ ECDSA 这条是 MS Software KSP 唯一可行的一条,其余几条均已实测
**证书链**:Schannel 的握手在进程外完成,建链时只查系统证书库——fullchain 里的中间证书塞进叶证书自带的内存库或 `paCred` 数组都不会被下发(实测只发叶证书,缺中间证书的客户端建链失败)。因此加载身份时把 fullchain 第 2 张起的证书补进「当前用户\中间证书颁发机构」库(`Cert:\CurrentUser\CA`,已在库中则跳过;.NET 的 `SslStreamCertificateContext` 也是这么做的),Schannel 建好链后随握手下发。证书文件因此可以、也建议写成「叶证书 + 中间证书」的 fullchain(Let's Encrypt 的 `fullchain.pem` 即如此)。副作用:进程所在账户的 CA 库里会多出这些中间证书(公开信息,留在库里无害)。
## 14. 增补(2026-10-26:结果外露 —— `content` 同时携带结构化 JSON)
### 14.1 问题
改造前,列表/查询类工具的 `content` 只有一句可读摘要(“共 1 台主机匹配。”),真正的载荷(`hosts[]`、`processes[]`、`files[]`、`session_id`……)只在 `structuredContent` 里。MCP 规范(Tools → Structured Content)明确建议:**返回 `structuredContent` 的工具应同时把序列化后的 JSON 放进一个 `TextContent` 块**,正是为了这种只把 `content` 交给模型的客户端。实测 WorkBuddy 就属这类:它把 `search_hosts` 的结果格式化成“共 1 台主机匹配”交给模型,`id` 完全不可见,于是后续 `get_host_detail` / `exec_command` / 终端 / 远程控制全部无从下手(用户侧表现为模型去猜 1–3100 的 id,而主机 id 是 64 位雪花值,如 `986530101822679521`,猜测不可能命中)。
### 14.2 实现
- `McpInternal::BuildResult` 统一收口:结果里 `structuredContent` 为非空对象/数组时,追加一个 `{type:"text", text:"<紧凑JSON>"}` 块到 `content` 末尾。所有工具(含 `McpMachine.cpp` / `McpChat.cpp` 的 `BuildStructuredResult` 漏斗)自动生效,新增工具无需额外处理;空 `{}`(`remote_mouse` 这类动作结果)不追加。
- 正文已经承载同一份载荷的工具用 `SetStructuredTextPayload(result, payload)` 只外露差异部分,避免同一内容在上下文里出现两三次:
| 工具 | 外露的文本块 |
|---|---|
| `exec_command` / `terminal_exec` | `{"exit_code":N}`(stdout 已在正文里) |
| `get_keylog` | `id` / `duration_ms` / `bytes` / `lineCount` / `truncated`(行内容已在正文里,最多 16 KB) |
| `get_activity_history` | `{"records":[…]}`(`activityHistory` 与 `records` 是同一份数据的两种形态) |
| `host_get_hosts_file` | `lines` + 元数据(不再重复 `content` 原文) |
- 控制键以 `$structuredTextPayload` 成员的形式挂在 result 上,`BuildResult` 消费后立即 `removeMember`,不会出现在响应里。
- 列表类工具本就有 `limit/offset` 分页,补出来的 JSON 与 `structuredContent` 同量级,不会失控。
### 14.3 验证
Debug 实例(`Bin\Yama_x64d.exe`,临时端口)实测:`list_all_hosts` 的 `content[1]` 含完整主机 JSON(`id` / `ip` / `last_seen` …),`get_server_status` 的 `content[1]` 是 `{"status":{…}}`,`search_hosts` 空结果时是 `{"hasMore":false,"hosts":[],…}`;`content[0]` 的既有摘要文案一字未改。
### 14.4 影响面
- 响应体积:列表类工具约翻倍(分页上限内),执行类工具只多一个退出码字段。
- 既有断言不受影响:摘要仍在 `content[0]`,内部批量工具(`ids` 批量调用)仍只读 `content[0].text` 并另取 `structuredContent`。
+41
View File
@@ -30,11 +30,52 @@ std::string JsonToString(const Json::Value& v) {
return Json::writeString(b, v);
}
// 结果外露控制键:SetStructuredTextPayload 写入,BuildResult 消费后移除,
// 不会出现在响应里。'$' 前缀确保与任何业务字段不冲突。
static const char kStructuredTextPayloadKey[] = "$structuredTextPayload";
void AppendStructuredText(Json::Value& result, const Json::Value& payload) {
if (!payload.isObject() && !payload.isArray())
return; // null/标量载荷没有可外露的结构
if (payload.empty())
return; // 动作类结果(remote_mouse 等的 {})无内容可补
Json::Value content = result.isMember("content") ? result["content"]
: Json::Value(Json::arrayValue);
if (!content.isArray())
content = Json::Value(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
item["text"] = JsonToString(payload); // 紧凑 JSON,可被模型原样解析
content.append(item);
result["content"] = content;
}
void AppendStructuredText(Json::Value& result) {
if (!result.isMember("structuredContent"))
return;
AppendStructuredText(result, result["structuredContent"]);
}
void SetStructuredTextPayload(Json::Value& result, const Json::Value& payload) {
result[kStructuredTextPayloadKey] = payload;
}
std::string BuildResult(const Json::Value& id, const Json::Value& result) {
Json::Value resp(Json::objectValue);
resp["jsonrpc"] = "2.0";
resp["id"] = id;
resp["result"] = result;
// resp["result"] 本来就是深拷贝,直接在上面补文本块,不多拷一次。
Json::Value& out = resp["result"];
if (out.isMember(kStructuredTextPayloadKey)) {
Json::Value payload = out[kStructuredTextPayloadKey];
out.removeMember(kStructuredTextPayloadKey);
AppendStructuredText(out, payload);
} else {
AppendStructuredText(out);
}
return JsonToString(resp);
}
+22
View File
@@ -27,6 +27,28 @@ std::string JsonToString(const Json::Value& v);
std::string BuildResult(const Json::Value& id, const Json::Value& result);
std::string BuildError(const Json::Value& id, int code, const std::string& msg);
// ===== 结果外露(content 文本块)=====
//
// MCP 规范(Tools > Structured Content)要求:返回 structuredContent 的工具,
// 应同时把序列化后的 JSON 放进一个 TextContent 块。有些客户端(如 WorkBuddy)
// 只把 content 交给模型、完全忽略 structuredContent——不补这一块,模型就拿不到
// id / session_id / pid 这类串联下一跳的关键字段,只能看到「共 N 台主机匹配」。
//
// 因此 BuildResult 默认给每个带非空 structuredContent 的结果追加一个文本块
// (紧凑 JSON)。工具的正文已经承载同一份载荷时,用 SetStructuredTextPayload
// 指定只外露哪部分,避免同一份内容在上下文里出现两三次:
//
// exec_command / terminal_exec → {"exit_code":N} (stdout 已在正文里)
// get_keylog → 行数/字节数等元数据(行已在正文里)
// get_activity_history → {"records":[…]}
// host_get_hosts_file → 去掉 content 的 sc (原文已在 lines 里)
void AppendStructuredText(Json::Value& result, const Json::Value& payload); // 内部用
void AppendStructuredText(Json::Value& result); // 内部用
// 本次结果只外露 payload(BuildResult 消费后移除,不出现在响应里)。
// payload 为空对象/空数组时本次不追加文本块。
void SetStructuredTextPayload(Json::Value& result, const Json::Value& payload);
// 仅 ASCII 小写化;不区分大小写的子串匹配
std::string ToLowerAscii(const std::string& s);
bool ContainsCI(const std::string& haystack, const std::string& needle);
+9 -2
View File
@@ -276,9 +276,13 @@ Json::Value ActionOutputSchema() {
}
std::string BuildStructuredResult(const Json::Value& id, const Json::Value& sc,
const std::string& text) {
const std::string& text,
const Json::Value* textPayload = nullptr) {
Json::Value result(Json::objectValue);
result["structuredContent"] = sc;
// 默认由 BuildResult 把 structuredContent 原样外露到 content;工具可指定更小的
// 载荷(例如 hosts 文件只外露 lines,不再重复 content 原文)。
if (textPayload) SetStructuredTextPayload(result, *textPayload);
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
@@ -2000,7 +2004,10 @@ static std::string BuildHostGetHostsFile(const Json::Value& id, const Json::Valu
std::string summary = std::string(u8"hosts 文件 ") + std::to_string(contentLen) + u8" 字节" +
(truncated ? u8"(已截断)" : "");
return BuildStructuredResult(id, sc, summary);
// 正文外露 lines + 元数据即可;sc 里的 content 是同一份原文,别再重复一遍。
Json::Value textPayload = sc;
textPayload.removeMember("content");
return BuildStructuredResult(id, sc, summary, &textPayload);
}
// ============================================================================
+25
View File
@@ -2280,6 +2280,12 @@ std::string BuildGetActivityHistory(const Json::Value& id, const Json::Value& ar
structuredContent["activityHistory"] = text;
result["structuredContent"] = structuredContent;
// 正文外的 JSON 块只放 records:activityHistory 是同一份数据的原文,
// 整包外露等于同样内容出现三遍。
Json::Value textPayload(Json::objectValue);
textPayload["records"] = records;
SetStructuredTextPayload(result, textPayload);
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
@@ -2905,6 +2911,11 @@ std::string BuildExecCommand(const Json::Value& id, const Json::Value& args, CMy
structuredContent["exit_code"] = exitCode;
result["structuredContent"] = structuredContent;
// stdout 已在正文里,正文外的 JSON 块只补退出码(只读 content 的客户端也能看到)。
Json::Value textPayload(Json::objectValue);
textPayload["exit_code"] = exitCode;
SetStructuredTextPayload(result, textPayload);
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
@@ -3451,6 +3462,11 @@ std::string BuildTerminalExec(const Json::Value& id, const Json::Value& args, CM
structuredContent["exit_code"] = exitCode;
result["structuredContent"] = structuredContent;
// 同 exec_command:stdout 在正文里,正文外只补退出码。
Json::Value textPayload(Json::objectValue);
textPayload["exit_code"] = exitCode;
SetStructuredTextPayload(result, textPayload);
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
@@ -5630,6 +5646,15 @@ std::string BuildGetKeylog(const Json::Value& id, const Json::Value& args, CMy20
Json::Value result(Json::objectValue);
result["structuredContent"] = structuredContent;
// 行内容已随正文外露(joined 最多 16 KB),正文外只补元数据,不再重复整份行记录。
Json::Value textPayload(Json::objectValue);
textPayload["id"] = std::to_string(devId);
textPayload["duration_ms"] = durationMs;
textPayload["bytes"] = (Json::Int)collected.size();
textPayload["lineCount"] = (int)lines.size();
textPayload["truncated"] = truncated;
SetStructuredTextPayload(result, textPayload);
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
+19
View File
@@ -86,6 +86,18 @@ function HasPaging($obj) {
return $true
}
# 结果外露(docs/Mcp_Design.md §14):content 末尾必须有一个可解析的 JSON 文本块,
# 内容与 structuredContent 对应。只读 content 的客户端(WorkBuddy)靠它拿到 id。
function HasJsonText($rpc) {
if ($null -eq $rpc -or $null -eq $rpc.result) { return $false }
$c = @($rpc.result.content)
if ($c.Count -lt 2) { return $false }
$last = $c[$c.Count - 1]
if ($last.type -ne 'text' -or [string]::IsNullOrEmpty($last.text)) { return $false }
try { $null = $last.text | ConvertFrom-Json } catch { return $false }
return $true
}
Write-Host "MCP smoke test -> $Base"
if (-not $Token) {
Write-Host "缺少 token:请设置环境变量 YAMA_MCP_TOKEN 或传 -Token。" -ForegroundColor Red
@@ -153,9 +165,15 @@ Check 'list_online_hosts 过滤后 totalAll 仍是全部在线数' ([int]$noMatc
$all = Rpc '' $null 'list_all_hosts' @{ limit = 5 }
Check 'list_all_hosts 带分页字段' (HasPaging $all.result.structuredContent)
Check 'list_all_hosts 的 content 附带结构化 JSON' (HasJsonText $all)
$allJson = $null
if (HasJsonText $all) { $allJson = $all.result.content[-1].text | ConvertFrom-Json }
Check 'content 的 JSON 里能取到主机 id(串联下一跳)' ($null -eq $allJson -or
@($allJson.hosts).Count -eq 0 -or [string]$allJson.hosts[0].id -ne '')
$found = Rpc '' $null 'search_hosts' @{ query = ''; limit = 5 }
Check 'search_hosts 正常返回' ($found.error -eq $null -and (HasPaging $found.result.structuredContent))
Check 'search_hosts 的 content 附带结构化 JSON' (HasJsonText $found)
$audit = Rpc '' $null 'get_audit_log' @{ limit = 5 }
Check 'get_audit_log 正常返回' ($audit.error -eq $null)
@@ -172,6 +190,7 @@ if ($Base -match ':(\d+)(/|$)') { $basePort = [int]$Matches[1] }
Check 'get_server_status 版本/端口/开关齐全' `
([string]$st.version -ne '' -and [int]$st.port -eq $basePort -and $null -ne $st.switches -and $null -ne $st.sessions)
Check 'get_server_status 不含 token' (($st | ConvertTo-Json -Depth 6) -notmatch '(?i)token')
Check 'get_server_status 的 content 附带结构化 JSON' (HasJsonText $status)
if (-not $HostId) {
$first = @($sc.hosts)[0]