dknowc-dsh 1.0.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dknowc-dsh",
3
- "version": "1.0.0",
3
+ "version": "1.0.1",
4
4
  "description": "深知可信办公全家桶:深知可信咨询、深知可信搜索、深知公文写作(skill + MCP 转接),面向 DeepSeek Harness (dsh)",
5
5
  "type": "module",
6
6
  "main": "src/index.js",
@@ -30,4 +30,4 @@
30
30
  "patch": "./cordis.patch.yml"
31
31
  }
32
32
  }
33
- }
33
+ }
@@ -280,7 +280,7 @@ python3 <skillDir>/scripts/outline_reference.py "用户写作需求" --output ou
280
280
  1. 设计搜索方案,覆盖政策依据、数据支撑、参考案例等必要维度;不要把“表述参考型”设计为独立搜索项。
281
281
  2. 使用自然语言 query,按行政层级和素材类型拆分检索。
282
282
  3. 向用户展示搜索方案并停止,等待用户确认或调整。
283
- 4. 用户确认搜索方案后,必须调用深知可信工作台 MCP 工具 `mcp__dknowc__trusted_search` 执行深知搜索;如用户调整,按调整后的方案执行。每次调用把 MCP 返回保存为 JSON,再用 `scripts/adapt_mcp_result.py` 规范化为 `dkag_search.py --json-only` 同构的接口 JSON(保持后续合并、溯源报告脚本兼容)。搜索项的“搜索目的”作为 `purpose` 说明保留在规范化 JSON 中,用于后续知识专库链接外显文字;该内容不得展示给用户。
283
+ 4. 用户确认搜索方案后,必须调用深知可信工作台 MCP 工具 `mcp__dknowc__trusted_search` 执行深知搜索;如用户调整,按调整后的方案执行。每次调用把 MCP 返回保存为 JSON(注意 MCP 返回的实际字段是 `materials[]`(title/source/date/paragraph/url)与 `knowledge_base_url`(下划线命名),不是旧接口的 `data.检索文章`),再用 `scripts/adapt_mcp_result.py --mode search` 规范化为 `dkag_search.py --json-only` 同构的接口 JSON:`materials` 会被转换成 `data.检索文章`(中文键,含标题/来源/发布日期/源网址/摘要),`knowledge_base_url` 映射为 `knowledgeBase`,后续合并、溯源报告脚本直接兼容。搜索项的“搜索目的”作为 `purpose` 说明保留在规范化 JSON 中,用于后续知识专库链接外显文字;该内容不得展示给用户。
284
284
  - 多个搜索项必须默认串行执行:完成第 1 项并确认结果 JSON 写入后,再执行第 2 项,以此类推。
285
285
  - 不得使用并发、后台任务、并行命令、批量同时请求或多 Agent 同时调用搜索接口。
286
286
  - 只有用户明确要求提速并确认可接受并发风险,且平台和接口限流条件允许时,才可以并发搜索;否则一律串行。
@@ -291,7 +291,7 @@ python3 <skillDir>/scripts/outline_reference.py "用户写作需求" --output ou
291
291
  9. 用户确认素材后,再进入大纲或 Word 生成;正式写作任务不得把正文初稿作为聊天消息发出,直接生成 Word(执行过搜索时另附 HTML 可信溯源报告)。
292
292
  10. 执行过搜索时,正式公文正文不再内嵌来源角标、知识专库链接或溯源卡片;必须另行生成 `标题_可信溯源报告.html`,将完整正文写入 HTML,并把正文中的 `[1]`/`【1】`角标变成可点击的来源跳转。报告底部统一展示知识专库链接。凡通过深知可信搜索召回并写入正文的依据,默认按已完成可信检索和可溯源处理,不得使用“建议核对”“需人工核验”等削弱可信度的措辞。
293
293
  11. 可信溯源报告必须按 `reference/search_guide.md` 的固定流程生成:先整理结构化 JSON 到 `official-docs/input/标题_可信溯源报告.json`,再调用 `python3 <skillDir>/scripts/source_note_html.py ...` 输出 HTML。不得由模型手写完整 HTML,不得自行拼接 `<a>`、`onclick`、按钮、卡片或页面样式。
294
- 12. 整理 `materials` 时,凡来自深知可信搜索的材料,必须将原始结果中的 `源网址` 原样写入 `source_url`;不得只写规范化后的文章标题,再依赖标题反查网址。若接口未返回 `源网址`,该材料不显示原文链接;不得猜测、补造或用搜索接口地址代替。
294
+ 12. 整理 `materials` 时,凡来自深知可信搜索的材料,必须将材料条目的 `url`(或规范化后的 `源网址`/`sourceUrl`)原样写入 `source_url`;不得只写规范化后的文章标题,再依赖标题反查网址。若 MCP 返回未提供该材料的 URL,该材料不显示原文链接;不得猜测、补造或用搜索接口地址代替。
295
295
  13. 可信溯源报告中的知识专库链接必须来自每个原始搜索结果 JSON 的 `knowledgeBase`、`content.knowledgeBase` 或 `search_meta.knowledgeBase` 字段,并写入结构化 JSON 的 `knowledge_bases[].url`。不得使用占位链接、`alert()`、纯文本说明、搜索接口地址或无法点击的伪链接替代。
296
296
 
297
297
  搜索异常处理:
@@ -1,19 +1,37 @@
1
1
  #!/usr/bin/env python3
2
2
  """深知 dsh —— MCP 工具返回 → 渲染脚本输入 适配器。
3
3
 
4
- dsh 场景下,skill 不再直连深知接口,而是通过 MCP 工具
5
- (mcp__dknowc__credible_chat / _trusted_search / _deep_query)拿数据。
6
- MCP 工具返回的是 MCP 协议结构({content:[{type:"text",text:"..."}]}),
7
- 而 render_trace_html.py 等渲染脚本期望的是深知接口 JSON 结构。
8
-
9
- 本脚本把 MCP 返回规范化成渲染脚本可消费的接口 JSON,保证溯源 HTML
10
- 等交付物与直连版一致。
4
+ dsh 场景下,skill 通过深知可信工作台 MCP 工具(credible_chat /
5
+ trusted_search / deep_query,或注册后经 mcp_direct.py 直调)拿数据。
6
+ MCP 返回是协议结构 {content:[{type:"text",text:"<业务JSON>"}]},其内层
7
+ 业务 JSON 的字段形态与原直连接口不同,而 render_trace_html.py 等渲染
8
+ 脚本按原接口结构消费字段。
9
+
10
+ 本脚本按【MCP 实测返回】做字段映射(2026-08-19 实测三个工具确认):
11
+
12
+ credible_chat 内层(chat 模式,渲染脚本基本兼容,直通+防御):
13
+ answer 答案正文(渲染脚本 extract_answer 支持顶层 answer)
14
+ referenceMaterials[] 参考材料(title/url/sourceUrl/unit/content[].text 等,
15
+ 与 source_from_article 字段兼容,直接透传)
16
+ policyFiles[] / recommendationItems[] / trace_report_url 附加信息,透传保留
17
+
18
+ trusted_search 内层(search 模式,需要映射):
19
+ materials[{title,source,date,paragraph,url}] → data.检索文章[]
20
+ (渲染脚本 extract_articles_from_search 只认中文键 data.检索文章)
21
+ knowledge_base_url → knowledgeBase / knowledgeBaseUrl(渲染脚本只认驼峰)
22
+
23
+ deep_query 内层(deep 模式,需要映射):
24
+ materials[] / search_groups[].materials[] → data.list[]
25
+ (渲染脚本 extract_articles_from_deep 认 data.list)
26
+ progress[](字符串过程记录)原样保留,供 Agent 综合答案时参考
27
+ 答案不由接口给出,由 Agent 基于材料形成后经 --answer-file 传入
11
28
 
12
29
  用法:
13
30
  python3 scripts/adapt_mcp_result.py <mcp返回.json> --output <规范化.json> [--mode chat|search|deep]
14
31
 
15
- - 输入:模型保存的 MCP 工具返回 JSON(content 数组形式,或已含接口 JSON)
16
- - 输出:可直接传给 render_trace_html.py 的接口 JSON 结构
32
+ - 输入:MCP 工具返回 JSON(mcp_direct.py --output 的产物,或模型保存的
33
+ dsh mcp-client 工具返回;支持 content[].text / structuredContent / 已解包形态)
34
+ - 输出:render_trace_html.py 可直接消费的接口 JSON
17
35
  - --mode:chat=可信咨询 / search=可信搜索 / deep=深度搜索;缺省自动识别
18
36
  """
19
37
 
@@ -25,12 +43,12 @@ from typing import Any, Dict, List, Optional
25
43
 
26
44
 
27
45
  def _deep_find(o: Any, keys, depth=0, max_depth=8):
28
- """在任意嵌套结构里查找第一个命中任一 key 的值。"""
46
+ """在任意嵌套结构里查找第一个命中任一 key 的非空值。"""
29
47
  if depth > max_depth:
30
48
  return None
31
49
  if isinstance(o, dict):
32
50
  for k, v in o.items():
33
- if k in keys:
51
+ if k in keys and v not in (None, "", [], {}):
34
52
  return v
35
53
  r = _deep_find(v, keys, depth + 1, max_depth)
36
54
  if r is not None:
@@ -47,13 +65,11 @@ def _extract_mcp_text(o: Any) -> Optional[str]:
47
65
  """从 MCP 协议返回中提取文本内容。
48
66
 
49
67
  支持形态:
50
- - {content: [{type:"text", text:"..."}]}(MCP 标准,text 常为 JSON 字符串)
68
+ - {content: [{type:"text", text:"..."}]}(MCP 标准,text 为业务 JSON 字符串)
51
69
  - {structuredContent: {...}}
52
- - 直接就是接口 JSON
53
- 返回:解析出的 dict payload;无法解析时返回 None。
70
+ - 已是解包后的业务 JSON dict
54
71
  """
55
72
  if isinstance(o, dict):
56
- # structuredContent 优先
57
73
  sc = o.get("structuredContent")
58
74
  if isinstance(sc, dict):
59
75
  return json.dumps(sc, ensure_ascii=False)
@@ -67,8 +83,12 @@ def _extract_mcp_text(o: Any) -> Optional[str]:
67
83
  parts.append(block)
68
84
  if parts:
69
85
  return "\n".join(parts)
70
- # 已经是接口 JSON?
71
- if any(k in o for k in ("resp", "data", "referenceMaterials", "检索文章", "success")):
86
+ # result.content 嵌套形态(完整 MCP JSON-RPC 响应)
87
+ result = o.get("result")
88
+ if isinstance(result, dict):
89
+ return _extract_mcp_text(result)
90
+ # 已是业务 JSON(answer/materials/referenceMaterials 等特征键)
91
+ if any(k in o for k in ("answer", "referenceMaterials", "materials", "检索文章", "progress", "search_meta")):
72
92
  return json.dumps(o, ensure_ascii=False)
73
93
  return None
74
94
 
@@ -83,118 +103,139 @@ def _try_json(text: str) -> Any:
83
103
  return None
84
104
 
85
105
 
86
- def _unwrap_payload(o: Any) -> Dict[str, Any]:
87
- """递归展开嵌套的接口 JSON,找到最内层含业务字段的对象。
106
+ def _material_to_search_article(m: Dict[str, Any]) -> Dict[str, Any]:
107
+ """trusted_search 的 materials 条目 → 渲染脚本认的检索文章结构。
88
108
 
89
- 接口返回常见 {data: {resp: {...}, referenceMaterials:[...]}},
90
- 也偶见 {content: {data: {...}}} 等包装。这里尽量展开到业务层。
109
+ 渲染脚本 source_from_article 认的字段名(多 key 兜底):
110
+ 标题:文章标题/title/标题;来源:unit/sourceElement/数据源/发布机关/来源;
111
+ 日期:发布日期/date/发布时间;网址:sourceUrl/source_url/源网址/url/原文;
112
+ 摘录:摘要/相关段落/全文/content/text。
113
+ 这里把 MCP 的英文字段同时写入中文键与英文键,保证两条提取路径都能命中。
91
114
  """
92
- cur = o
93
- seen = set()
94
- while isinstance(cur, dict) and id(cur) not in seen:
95
- seen.add(id(cur))
96
- # 展开 {content:{...}} / {data:{...}} 包装,但保留 data 本身
97
- if len(cur) == 1:
98
- only = next(iter(cur.values()))
99
- if isinstance(only, dict):
100
- cur = only
101
- continue
102
- if isinstance(cur.get("data"), dict) and (
103
- "resp" in cur["data"] or "检索文章" in cur["data"] or "referenceMaterials" in cur["data"]
104
- ):
105
- # 保留外层 data 键,同时业务字段也升到顶层
106
- merged = dict(cur)
107
- merged.update({k: v for k, v in cur["data"].items() if k not in merged})
108
- merged["data"] = cur["data"]
109
- return merged
110
- break
111
- return cur if isinstance(cur, dict) else {"raw": cur}
115
+ title = str(m.get("title") or m.get("标题") or "")
116
+ source = str(m.get("source") or m.get("来源") or m.get("unit") or "")
117
+ date = str(m.get("date") or m.get("发布日期") or "")
118
+ url = str(m.get("url") or m.get("sourceUrl") or m.get("源网址") or "")
119
+ paragraph = str(m.get("paragraph") or m.get("content") or m.get("摘要") or "")
120
+ return {
121
+ "标题": title,
122
+ "title": title,
123
+ "来源": source,
124
+ "发布日期": date,
125
+ "date": date,
126
+ "源网址": url,
127
+ "sourceUrl": url,
128
+ "url": url,
129
+ "摘要": paragraph,
130
+ "全文": paragraph,
131
+ }
112
132
 
113
133
 
114
134
  def _normalize_chat(payload: Dict[str, Any]) -> Dict[str, Any]:
115
- """规范化可信咨询(credible_chat)返回。"""
135
+ """规范化可信咨询(credible_chat)返回。
136
+
137
+ MCP 内层已是顶层 answer + referenceMaterials 形态,渲染脚本
138
+ extract_answer / extract_sources / source_from_article 直接兼容,
139
+ 此处直通透传,仅做两处防御:
140
+ - answer 缺失时从任意位置兜底找正文,包成渲染脚本认的 resp.content
141
+ - 保留 trace_report_url / policyFiles / recommendationItems 等附加字段
142
+ """
116
143
  out = dict(payload)
117
- data = payload.get("data") if isinstance(payload.get("data"), dict) else {}
118
- # 确保 resp.content 可被提取
119
- if "resp" not in out:
120
- resp = data.get("resp") if isinstance(data, dict) else None
121
- if isinstance(resp, dict):
122
- out["resp"] = resp
123
- else:
124
- # 从任意位置找正文
125
- answer = _deep_find(payload, ("content", "answer", "text", "resp"), depth=0)
126
- if isinstance(answer, str):
127
- out["resp"] = {"content": answer}
128
- # 确保 referenceMaterials
129
- if "referenceMaterials" not in out:
130
- rm = data.get("referenceMaterials") if isinstance(data, dict) else None
131
- if isinstance(rm, list):
132
- out["referenceMaterials"] = rm
133
- # knowledgeBase / question
134
- for key in ("knowledgeBase", "question"):
135
- if key not in out and isinstance(data, dict) and key in data:
136
- out[key] = data[key]
144
+ if not (isinstance(out.get("answer"), str) and out.get("answer").strip()):
145
+ answer = _deep_find(payload, ("answer", "contentText"))
146
+ if isinstance(answer, str) and answer.strip():
147
+ out["answer"] = answer
148
+ # 渲染脚本 extract_answer 优先找 resp.content;补一份兼容形态
149
+ answer = out.get("answer")
150
+ if isinstance(answer, str) and answer.strip() and not isinstance(out.get("resp"), dict):
151
+ out["resp"] = {"content": answer}
137
152
  return out
138
153
 
139
154
 
140
155
  def _normalize_search(payload: Dict[str, Any]) -> Dict[str, Any]:
141
- """规范化可信搜索(trusted_search)返回。"""
156
+ """规范化可信搜索(trusted_search)返回:materials → data.检索文章,
157
+ knowledge_base_url → knowledgeBase(驼峰)。
158
+ """
142
159
  out = dict(payload)
143
- # 检索文章:优先顶层 data.检索文章,其次 content.data.检索文章
144
- articles = _deep_find(payload, ("检索文章",))
145
- if articles is None:
146
- content = payload.get("content") if isinstance(payload.get("content"), dict) else payload
147
- data = content.get("data") if isinstance(content.get("data"), dict) else {}
148
- articles = data.get("检索文章")
149
- if isinstance(articles, list):
150
- if "data" not in out or not isinstance(out["data"], dict):
151
- out["data"] = {}
152
- out["data"]["检索文章"] = articles
153
- # 确保 referenceMaterials
154
- if "referenceMaterials" not in out:
155
- rm = _deep_find(payload, ("referenceMaterials",))
156
- if isinstance(rm, list):
157
- out["referenceMaterials"] = rm
158
- # knowledgeBase
159
- if "knowledgeBase" not in out:
160
- kb = _deep_find(payload, ("knowledgeBase", "knowledgeBaseUrl"))
161
- if isinstance(kb, str):
162
- out["knowledgeBase"] = kb
160
+ materials = payload.get("materials")
161
+ if isinstance(materials, list):
162
+ articles = [_material_to_search_article(m) for m in materials if isinstance(m, dict)]
163
+ data = out.get("data") if isinstance(out.get("data"), dict) else {}
164
+ data["检索文章"] = articles
165
+ out["data"] = data
166
+ out["total_articles"] = out.get("total_articles") or len(articles)
167
+ # 兼容旧直连形态(content.data.检索文章)的防御提取
168
+ if not (isinstance(out.get("data"), dict) and isinstance(out["data"].get("检索文章"), list)):
169
+ legacy = _deep_find(payload, ("检索文章",))
170
+ if isinstance(legacy, list) and legacy:
171
+ data = out.get("data") if isinstance(out.get("data"), dict) else {}
172
+ data["检索文章"] = [x for x in legacy if isinstance(x, dict)]
173
+ out["data"] = data
174
+ # 知识专库链接:MCP 用下划线 knowledge_base_url,渲染脚本只认驼峰
175
+ kb = payload.get("knowledge_base_url") or payload.get("knowledgeBase") or payload.get("knowledgeBaseUrl")
176
+ if isinstance(kb, str) and kb.strip():
177
+ out["knowledgeBase"] = kb
178
+ out["knowledgeBaseUrl"] = kb
163
179
  return out
164
180
 
165
181
 
166
182
  def _normalize_deep(payload: Dict[str, Any]) -> Dict[str, Any]:
167
- """规范化深度搜索(deep_query)返回。"""
183
+ """规范化深度搜索(deep_query)返回:materials / search_groups → data.list,
184
+ progress(字符串过程)保留,knowledge_base_url 映射驼峰。
185
+ 深度搜索答案由 Agent 基于材料与 progress 综合形成,经 --answer-file 传入渲染。
186
+ """
168
187
  out = dict(payload)
169
- events = payload.get("events")
170
- if not isinstance(events, list):
171
- events = _deep_find(payload, ("events",))
172
- if isinstance(events, list):
173
- out["events"] = events
174
- # data.list 兜底
175
- data = payload.get("data") if isinstance(payload.get("data"), dict) else {}
176
- if isinstance(data.get("list"), list):
177
- out["data"] = data
178
- if "referenceMaterials" not in out:
179
- rm = _deep_find(payload, ("referenceMaterials",))
180
- if isinstance(rm, list):
181
- out["referenceMaterials"] = rm
188
+ items: List[Dict[str, Any]] = []
189
+ mats = payload.get("materials")
190
+ if isinstance(mats, list):
191
+ items.extend([m for m in mats if isinstance(m, dict)])
192
+ groups = payload.get("search_groups")
193
+ if isinstance(groups, list):
194
+ for g in groups:
195
+ if isinstance(g, dict) and isinstance(g.get("materials"), list):
196
+ items.extend([m for m in g["materials"] if isinstance(m, dict)])
197
+ elif isinstance(g, dict):
198
+ # search_groups 条目本身可能就是材料(含 title/url 等特征键)
199
+ if any(k in g for k in ("title", "url", "sourceUrl")):
200
+ items.append(g)
201
+ if items:
202
+ # 渲染脚本 extract_articles_from_deep 消费顶层 data.list
203
+ out["data"] = {"list": items}
204
+ # 兼容旧直连 events 形态的防御提取
205
+ if "data" not in out:
206
+ events = payload.get("events")
207
+ if isinstance(events, list):
208
+ out["events"] = events
209
+ kb = payload.get("knowledge_base_url") or payload.get("knowledgeBase") or payload.get("knowledgeBaseUrl")
210
+ if isinstance(kb, str) and kb.strip():
211
+ out["knowledgeBase"] = kb
212
+ out["knowledgeBaseUrl"] = kb
182
213
  return out
183
214
 
184
215
 
185
216
  def detect_mode(payload: Dict[str, Any]) -> str:
186
- """自动识别返回属于哪种接口。"""
187
- if _deep_find(payload, ("检索文章",)) is not None:
188
- return "search"
189
- if isinstance(payload.get("events"), list) or _deep_find(payload, ("events",)) is not None:
217
+ """按 MCP 实测特征自动识别接口类型。
218
+
219
+ deep 的特征键(query_id/progress/search_groups/deep_query_meta)最特异,
220
+ 必须先于 search 判断:deep 返回同样携带 materials 键,若先判 search
221
+ 会被误判(materials 为空列表也是 list)。
222
+ """
223
+ if (
224
+ "query_id" in payload
225
+ or isinstance(payload.get("progress"), list)
226
+ or isinstance(payload.get("search_groups"), list)
227
+ or isinstance(payload.get("deep_query_meta"), dict)
228
+ ):
190
229
  return "deep"
191
- if _deep_find(payload, ("resp",)) is not None:
192
- return "chat"
230
+ if isinstance(payload.get("search_meta"), dict) or (
231
+ isinstance(payload.get("materials"), list) and "answer" not in payload
232
+ ):
233
+ return "search"
193
234
  return "chat"
194
235
 
195
236
 
196
237
  def main() -> int:
197
- parser = argparse.ArgumentParser(description="MCP 返回 → 渲染脚本输入 适配器")
238
+ parser = argparse.ArgumentParser(description="MCP 返回 → 渲染脚本输入 适配器(按 2026-08-19 实测 MCP 结构映射)")
198
239
  parser.add_argument("input_json", help="MCP 工具返回 JSON 文件路径")
199
240
  parser.add_argument("--output", "-o", required=True, help="规范化 JSON 输出路径")
200
241
  parser.add_argument("--mode", choices=["chat", "search", "deep"], default=None, help="接口类型;缺省自动识别")
@@ -211,17 +252,14 @@ def main() -> int:
211
252
  print(f"错误:输入不是合法 JSON:{e}", file=sys.stderr)
212
253
  return 2
213
254
 
214
- # 1) 提取 MCP 文本 → 尝试解析成接口 JSON
255
+ # 1) 提取 MCP 协议层 → 业务 JSON
215
256
  text = _extract_mcp_text(raw)
216
257
  payload = _try_json(text) if text else None
217
258
  if not isinstance(payload, dict):
218
- # 纯文本回答(无 JSON)→ 包成 resp.content
219
- payload = {"resp": {"content": text or json.dumps(raw, ensure_ascii=False)}}
220
-
221
- # 2) 展开包装层
222
- payload = _unwrap_payload(payload)
259
+ # 纯文本回答(无业务 JSON)→ 包成 answer
260
+ payload = {"answer": text or json.dumps(raw, ensure_ascii=False)}
223
261
 
224
- # 3) 按模式规范化
262
+ # 2) 按模式做字段映射
225
263
  mode = args.mode or detect_mode(payload)
226
264
  if mode == "search":
227
265
  out = _normalize_search(payload)
@@ -163,7 +163,7 @@ def get_skill_root():
163
163
 
164
164
 
165
165
  def get_configured_output_dir():
166
- """获取 Word 输出目录:相对路径基于 Skill 安装目录解析,不依赖 cwd。"""
166
+ """获取 Word 输出目录:相对路径基于会话工作区(WS_ROOT)解析,不依赖 skill 安装目录。"""
167
167
  configured_dir = None
168
168
  if FORMAT_CONFIG:
169
169
  output_config = FORMAT_CONFIG.get('output', {})
@@ -172,10 +172,10 @@ def get_configured_output_dir():
172
172
 
173
173
  output_dir = os.path.expanduser(configured_dir or DEFAULT_OUTPUT_DIR)
174
174
  if not os.path.isabs(output_dir):
175
- output_dir = os.path.join(get_skill_root(), output_dir)
175
+ output_dir = os.path.join(WS_ROOT, output_dir)
176
176
  output_dir = os.path.abspath(output_dir)
177
- if not is_path_within(output_dir, os.path.abspath(os.path.join(get_skill_root(), DEFAULT_OUTPUT_DIR))):
178
- raise ValueError(f"输出目录必须位于 {os.path.join(get_skill_root(), DEFAULT_OUTPUT_DIR)} 内")
177
+ if not is_path_within(output_dir, os.path.abspath(os.path.join(WS_ROOT, DEFAULT_OUTPUT_DIR))):
178
+ raise ValueError(f"输出目录必须位于 {os.path.join(WS_ROOT, DEFAULT_OUTPUT_DIR)} 内")
179
179
  return output_dir
180
180
 
181
181
 
@@ -195,7 +195,7 @@ def resolve_input_text_path(input_path):
195
195
  elif raw_path == os.path.basename(raw_path):
196
196
  resolved = os.path.abspath(os.path.join(INPUT_DIR, raw_path))
197
197
  else:
198
- resolved = os.path.abspath(os.path.join(get_skill_root(), raw_path))
198
+ resolved = os.path.abspath(os.path.join(WS_ROOT, raw_path))
199
199
 
200
200
  allowed_dirs = [
201
201
  os.path.abspath(INPUT_DIR),
@@ -220,7 +220,7 @@ def resolve_output_path(output_path):
220
220
  elif output_path == os.path.basename(output_path):
221
221
  resolved = os.path.abspath(os.path.join(output_dir, output_path))
222
222
  else:
223
- resolved = os.path.abspath(os.path.join(get_skill_root(), output_path))
223
+ resolved = os.path.abspath(os.path.join(WS_ROOT, output_path))
224
224
  if not is_path_within(resolved, output_dir):
225
225
  raise ValueError(f"输出文件必须位于 Word 输出目录内: {output_dir}")
226
226
  return resolved
@@ -230,7 +230,7 @@ def display_path(path):
230
230
  """将 Skill 内文件路径转换为面向用户的相对路径。"""
231
231
  resolved = os.path.abspath(os.path.expanduser(str(path)))
232
232
  try:
233
- return os.path.relpath(resolved, get_skill_root())
233
+ return os.path.relpath(resolved, WS_ROOT)
234
234
  except ValueError:
235
235
  return resolved
236
236
 
@@ -122,7 +122,7 @@ python3 <skillDir>/scripts/adapt_mcp_result.py official-docs/search-results/dkno
122
122
  --mode chat
123
123
  ```
124
124
 
125
- 5. 读取规范化后 JSON 中的 `resp.content`、`referenceMaterials` 等字段。
125
+ 5. 读取规范化后 JSON 中的字段(MCP 返回的实际形态):`answer`(接口答案正文,含角标)、`referenceMaterials`(参考材料,含 title/url/sourceUrl/content 摘录)、`policyFiles`(政策文件原文清单)、`recommendationItems`(办事事项,含线上办理入口)、`trace_report_url`(接口侧溯源报告链接,展示时以本地 HTML 为准)。
126
126
 
127
127
  6. 形成面向用户的最终答案:
128
128
 
@@ -1,19 +1,37 @@
1
1
  #!/usr/bin/env python3
2
2
  """深知 dsh —— MCP 工具返回 → 渲染脚本输入 适配器。
3
3
 
4
- dsh 场景下,skill 不再直连深知接口,而是通过 MCP 工具
5
- (mcp__dknowc__credible_chat / _trusted_search / _deep_query)拿数据。
6
- MCP 工具返回的是 MCP 协议结构({content:[{type:"text",text:"..."}]}),
7
- 而 render_trace_html.py 等渲染脚本期望的是深知接口 JSON 结构。
8
-
9
- 本脚本把 MCP 返回规范化成渲染脚本可消费的接口 JSON,保证溯源 HTML
10
- 等交付物与直连版一致。
4
+ dsh 场景下,skill 通过深知可信工作台 MCP 工具(credible_chat /
5
+ trusted_search / deep_query,或注册后经 mcp_direct.py 直调)拿数据。
6
+ MCP 返回是协议结构 {content:[{type:"text",text:"<业务JSON>"}]},其内层
7
+ 业务 JSON 的字段形态与原直连接口不同,而 render_trace_html.py 等渲染
8
+ 脚本按原接口结构消费字段。
9
+
10
+ 本脚本按【MCP 实测返回】做字段映射(2026-08-19 实测三个工具确认):
11
+
12
+ credible_chat 内层(chat 模式,渲染脚本基本兼容,直通+防御):
13
+ answer 答案正文(渲染脚本 extract_answer 支持顶层 answer)
14
+ referenceMaterials[] 参考材料(title/url/sourceUrl/unit/content[].text 等,
15
+ 与 source_from_article 字段兼容,直接透传)
16
+ policyFiles[] / recommendationItems[] / trace_report_url 附加信息,透传保留
17
+
18
+ trusted_search 内层(search 模式,需要映射):
19
+ materials[{title,source,date,paragraph,url}] → data.检索文章[]
20
+ (渲染脚本 extract_articles_from_search 只认中文键 data.检索文章)
21
+ knowledge_base_url → knowledgeBase / knowledgeBaseUrl(渲染脚本只认驼峰)
22
+
23
+ deep_query 内层(deep 模式,需要映射):
24
+ materials[] / search_groups[].materials[] → data.list[]
25
+ (渲染脚本 extract_articles_from_deep 认 data.list)
26
+ progress[](字符串过程记录)原样保留,供 Agent 综合答案时参考
27
+ 答案不由接口给出,由 Agent 基于材料形成后经 --answer-file 传入
11
28
 
12
29
  用法:
13
30
  python3 scripts/adapt_mcp_result.py <mcp返回.json> --output <规范化.json> [--mode chat|search|deep]
14
31
 
15
- - 输入:模型保存的 MCP 工具返回 JSON(content 数组形式,或已含接口 JSON)
16
- - 输出:可直接传给 render_trace_html.py 的接口 JSON 结构
32
+ - 输入:MCP 工具返回 JSON(mcp_direct.py --output 的产物,或模型保存的
33
+ dsh mcp-client 工具返回;支持 content[].text / structuredContent / 已解包形态)
34
+ - 输出:render_trace_html.py 可直接消费的接口 JSON
17
35
  - --mode:chat=可信咨询 / search=可信搜索 / deep=深度搜索;缺省自动识别
18
36
  """
19
37
 
@@ -25,12 +43,12 @@ from typing import Any, Dict, List, Optional
25
43
 
26
44
 
27
45
  def _deep_find(o: Any, keys, depth=0, max_depth=8):
28
- """在任意嵌套结构里查找第一个命中任一 key 的值。"""
46
+ """在任意嵌套结构里查找第一个命中任一 key 的非空值。"""
29
47
  if depth > max_depth:
30
48
  return None
31
49
  if isinstance(o, dict):
32
50
  for k, v in o.items():
33
- if k in keys:
51
+ if k in keys and v not in (None, "", [], {}):
34
52
  return v
35
53
  r = _deep_find(v, keys, depth + 1, max_depth)
36
54
  if r is not None:
@@ -47,13 +65,11 @@ def _extract_mcp_text(o: Any) -> Optional[str]:
47
65
  """从 MCP 协议返回中提取文本内容。
48
66
 
49
67
  支持形态:
50
- - {content: [{type:"text", text:"..."}]}(MCP 标准,text 常为 JSON 字符串)
68
+ - {content: [{type:"text", text:"..."}]}(MCP 标准,text 为业务 JSON 字符串)
51
69
  - {structuredContent: {...}}
52
- - 直接就是接口 JSON
53
- 返回:解析出的 dict payload;无法解析时返回 None。
70
+ - 已是解包后的业务 JSON dict
54
71
  """
55
72
  if isinstance(o, dict):
56
- # structuredContent 优先
57
73
  sc = o.get("structuredContent")
58
74
  if isinstance(sc, dict):
59
75
  return json.dumps(sc, ensure_ascii=False)
@@ -67,8 +83,12 @@ def _extract_mcp_text(o: Any) -> Optional[str]:
67
83
  parts.append(block)
68
84
  if parts:
69
85
  return "\n".join(parts)
70
- # 已经是接口 JSON?
71
- if any(k in o for k in ("resp", "data", "referenceMaterials", "检索文章", "success")):
86
+ # result.content 嵌套形态(完整 MCP JSON-RPC 响应)
87
+ result = o.get("result")
88
+ if isinstance(result, dict):
89
+ return _extract_mcp_text(result)
90
+ # 已是业务 JSON(answer/materials/referenceMaterials 等特征键)
91
+ if any(k in o for k in ("answer", "referenceMaterials", "materials", "检索文章", "progress", "search_meta")):
72
92
  return json.dumps(o, ensure_ascii=False)
73
93
  return None
74
94
 
@@ -83,118 +103,139 @@ def _try_json(text: str) -> Any:
83
103
  return None
84
104
 
85
105
 
86
- def _unwrap_payload(o: Any) -> Dict[str, Any]:
87
- """递归展开嵌套的接口 JSON,找到最内层含业务字段的对象。
106
+ def _material_to_search_article(m: Dict[str, Any]) -> Dict[str, Any]:
107
+ """trusted_search 的 materials 条目 → 渲染脚本认的检索文章结构。
88
108
 
89
- 接口返回常见 {data: {resp: {...}, referenceMaterials:[...]}},
90
- 也偶见 {content: {data: {...}}} 等包装。这里尽量展开到业务层。
109
+ 渲染脚本 source_from_article 认的字段名(多 key 兜底):
110
+ 标题:文章标题/title/标题;来源:unit/sourceElement/数据源/发布机关/来源;
111
+ 日期:发布日期/date/发布时间;网址:sourceUrl/source_url/源网址/url/原文;
112
+ 摘录:摘要/相关段落/全文/content/text。
113
+ 这里把 MCP 的英文字段同时写入中文键与英文键,保证两条提取路径都能命中。
91
114
  """
92
- cur = o
93
- seen = set()
94
- while isinstance(cur, dict) and id(cur) not in seen:
95
- seen.add(id(cur))
96
- # 展开 {content:{...}} / {data:{...}} 包装,但保留 data 本身
97
- if len(cur) == 1:
98
- only = next(iter(cur.values()))
99
- if isinstance(only, dict):
100
- cur = only
101
- continue
102
- if isinstance(cur.get("data"), dict) and (
103
- "resp" in cur["data"] or "检索文章" in cur["data"] or "referenceMaterials" in cur["data"]
104
- ):
105
- # 保留外层 data 键,同时业务字段也升到顶层
106
- merged = dict(cur)
107
- merged.update({k: v for k, v in cur["data"].items() if k not in merged})
108
- merged["data"] = cur["data"]
109
- return merged
110
- break
111
- return cur if isinstance(cur, dict) else {"raw": cur}
115
+ title = str(m.get("title") or m.get("标题") or "")
116
+ source = str(m.get("source") or m.get("来源") or m.get("unit") or "")
117
+ date = str(m.get("date") or m.get("发布日期") or "")
118
+ url = str(m.get("url") or m.get("sourceUrl") or m.get("源网址") or "")
119
+ paragraph = str(m.get("paragraph") or m.get("content") or m.get("摘要") or "")
120
+ return {
121
+ "标题": title,
122
+ "title": title,
123
+ "来源": source,
124
+ "发布日期": date,
125
+ "date": date,
126
+ "源网址": url,
127
+ "sourceUrl": url,
128
+ "url": url,
129
+ "摘要": paragraph,
130
+ "全文": paragraph,
131
+ }
112
132
 
113
133
 
114
134
  def _normalize_chat(payload: Dict[str, Any]) -> Dict[str, Any]:
115
- """规范化可信咨询(credible_chat)返回。"""
135
+ """规范化可信咨询(credible_chat)返回。
136
+
137
+ MCP 内层已是顶层 answer + referenceMaterials 形态,渲染脚本
138
+ extract_answer / extract_sources / source_from_article 直接兼容,
139
+ 此处直通透传,仅做两处防御:
140
+ - answer 缺失时从任意位置兜底找正文,包成渲染脚本认的 resp.content
141
+ - 保留 trace_report_url / policyFiles / recommendationItems 等附加字段
142
+ """
116
143
  out = dict(payload)
117
- data = payload.get("data") if isinstance(payload.get("data"), dict) else {}
118
- # 确保 resp.content 可被提取
119
- if "resp" not in out:
120
- resp = data.get("resp") if isinstance(data, dict) else None
121
- if isinstance(resp, dict):
122
- out["resp"] = resp
123
- else:
124
- # 从任意位置找正文
125
- answer = _deep_find(payload, ("content", "answer", "text", "resp"), depth=0)
126
- if isinstance(answer, str):
127
- out["resp"] = {"content": answer}
128
- # 确保 referenceMaterials
129
- if "referenceMaterials" not in out:
130
- rm = data.get("referenceMaterials") if isinstance(data, dict) else None
131
- if isinstance(rm, list):
132
- out["referenceMaterials"] = rm
133
- # knowledgeBase / question
134
- for key in ("knowledgeBase", "question"):
135
- if key not in out and isinstance(data, dict) and key in data:
136
- out[key] = data[key]
144
+ if not (isinstance(out.get("answer"), str) and out.get("answer").strip()):
145
+ answer = _deep_find(payload, ("answer", "contentText"))
146
+ if isinstance(answer, str) and answer.strip():
147
+ out["answer"] = answer
148
+ # 渲染脚本 extract_answer 优先找 resp.content;补一份兼容形态
149
+ answer = out.get("answer")
150
+ if isinstance(answer, str) and answer.strip() and not isinstance(out.get("resp"), dict):
151
+ out["resp"] = {"content": answer}
137
152
  return out
138
153
 
139
154
 
140
155
  def _normalize_search(payload: Dict[str, Any]) -> Dict[str, Any]:
141
- """规范化可信搜索(trusted_search)返回。"""
156
+ """规范化可信搜索(trusted_search)返回:materials → data.检索文章,
157
+ knowledge_base_url → knowledgeBase(驼峰)。
158
+ """
142
159
  out = dict(payload)
143
- # 检索文章:优先顶层 data.检索文章,其次 content.data.检索文章
144
- articles = _deep_find(payload, ("检索文章",))
145
- if articles is None:
146
- content = payload.get("content") if isinstance(payload.get("content"), dict) else payload
147
- data = content.get("data") if isinstance(content.get("data"), dict) else {}
148
- articles = data.get("检索文章")
149
- if isinstance(articles, list):
150
- if "data" not in out or not isinstance(out["data"], dict):
151
- out["data"] = {}
152
- out["data"]["检索文章"] = articles
153
- # 确保 referenceMaterials
154
- if "referenceMaterials" not in out:
155
- rm = _deep_find(payload, ("referenceMaterials",))
156
- if isinstance(rm, list):
157
- out["referenceMaterials"] = rm
158
- # knowledgeBase
159
- if "knowledgeBase" not in out:
160
- kb = _deep_find(payload, ("knowledgeBase", "knowledgeBaseUrl"))
161
- if isinstance(kb, str):
162
- out["knowledgeBase"] = kb
160
+ materials = payload.get("materials")
161
+ if isinstance(materials, list):
162
+ articles = [_material_to_search_article(m) for m in materials if isinstance(m, dict)]
163
+ data = out.get("data") if isinstance(out.get("data"), dict) else {}
164
+ data["检索文章"] = articles
165
+ out["data"] = data
166
+ out["total_articles"] = out.get("total_articles") or len(articles)
167
+ # 兼容旧直连形态(content.data.检索文章)的防御提取
168
+ if not (isinstance(out.get("data"), dict) and isinstance(out["data"].get("检索文章"), list)):
169
+ legacy = _deep_find(payload, ("检索文章",))
170
+ if isinstance(legacy, list) and legacy:
171
+ data = out.get("data") if isinstance(out.get("data"), dict) else {}
172
+ data["检索文章"] = [x for x in legacy if isinstance(x, dict)]
173
+ out["data"] = data
174
+ # 知识专库链接:MCP 用下划线 knowledge_base_url,渲染脚本只认驼峰
175
+ kb = payload.get("knowledge_base_url") or payload.get("knowledgeBase") or payload.get("knowledgeBaseUrl")
176
+ if isinstance(kb, str) and kb.strip():
177
+ out["knowledgeBase"] = kb
178
+ out["knowledgeBaseUrl"] = kb
163
179
  return out
164
180
 
165
181
 
166
182
  def _normalize_deep(payload: Dict[str, Any]) -> Dict[str, Any]:
167
- """规范化深度搜索(deep_query)返回。"""
183
+ """规范化深度搜索(deep_query)返回:materials / search_groups → data.list,
184
+ progress(字符串过程)保留,knowledge_base_url 映射驼峰。
185
+ 深度搜索答案由 Agent 基于材料与 progress 综合形成,经 --answer-file 传入渲染。
186
+ """
168
187
  out = dict(payload)
169
- events = payload.get("events")
170
- if not isinstance(events, list):
171
- events = _deep_find(payload, ("events",))
172
- if isinstance(events, list):
173
- out["events"] = events
174
- # data.list 兜底
175
- data = payload.get("data") if isinstance(payload.get("data"), dict) else {}
176
- if isinstance(data.get("list"), list):
177
- out["data"] = data
178
- if "referenceMaterials" not in out:
179
- rm = _deep_find(payload, ("referenceMaterials",))
180
- if isinstance(rm, list):
181
- out["referenceMaterials"] = rm
188
+ items: List[Dict[str, Any]] = []
189
+ mats = payload.get("materials")
190
+ if isinstance(mats, list):
191
+ items.extend([m for m in mats if isinstance(m, dict)])
192
+ groups = payload.get("search_groups")
193
+ if isinstance(groups, list):
194
+ for g in groups:
195
+ if isinstance(g, dict) and isinstance(g.get("materials"), list):
196
+ items.extend([m for m in g["materials"] if isinstance(m, dict)])
197
+ elif isinstance(g, dict):
198
+ # search_groups 条目本身可能就是材料(含 title/url 等特征键)
199
+ if any(k in g for k in ("title", "url", "sourceUrl")):
200
+ items.append(g)
201
+ if items:
202
+ # 渲染脚本 extract_articles_from_deep 消费顶层 data.list
203
+ out["data"] = {"list": items}
204
+ # 兼容旧直连 events 形态的防御提取
205
+ if "data" not in out:
206
+ events = payload.get("events")
207
+ if isinstance(events, list):
208
+ out["events"] = events
209
+ kb = payload.get("knowledge_base_url") or payload.get("knowledgeBase") or payload.get("knowledgeBaseUrl")
210
+ if isinstance(kb, str) and kb.strip():
211
+ out["knowledgeBase"] = kb
212
+ out["knowledgeBaseUrl"] = kb
182
213
  return out
183
214
 
184
215
 
185
216
  def detect_mode(payload: Dict[str, Any]) -> str:
186
- """自动识别返回属于哪种接口。"""
187
- if _deep_find(payload, ("检索文章",)) is not None:
188
- return "search"
189
- if isinstance(payload.get("events"), list) or _deep_find(payload, ("events",)) is not None:
217
+ """按 MCP 实测特征自动识别接口类型。
218
+
219
+ deep 的特征键(query_id/progress/search_groups/deep_query_meta)最特异,
220
+ 必须先于 search 判断:deep 返回同样携带 materials 键,若先判 search
221
+ 会被误判(materials 为空列表也是 list)。
222
+ """
223
+ if (
224
+ "query_id" in payload
225
+ or isinstance(payload.get("progress"), list)
226
+ or isinstance(payload.get("search_groups"), list)
227
+ or isinstance(payload.get("deep_query_meta"), dict)
228
+ ):
190
229
  return "deep"
191
- if _deep_find(payload, ("resp",)) is not None:
192
- return "chat"
230
+ if isinstance(payload.get("search_meta"), dict) or (
231
+ isinstance(payload.get("materials"), list) and "answer" not in payload
232
+ ):
233
+ return "search"
193
234
  return "chat"
194
235
 
195
236
 
196
237
  def main() -> int:
197
- parser = argparse.ArgumentParser(description="MCP 返回 → 渲染脚本输入 适配器")
238
+ parser = argparse.ArgumentParser(description="MCP 返回 → 渲染脚本输入 适配器(按 2026-08-19 实测 MCP 结构映射)")
198
239
  parser.add_argument("input_json", help="MCP 工具返回 JSON 文件路径")
199
240
  parser.add_argument("--output", "-o", required=True, help="规范化 JSON 输出路径")
200
241
  parser.add_argument("--mode", choices=["chat", "search", "deep"], default=None, help="接口类型;缺省自动识别")
@@ -211,17 +252,14 @@ def main() -> int:
211
252
  print(f"错误:输入不是合法 JSON:{e}", file=sys.stderr)
212
253
  return 2
213
254
 
214
- # 1) 提取 MCP 文本 → 尝试解析成接口 JSON
255
+ # 1) 提取 MCP 协议层 → 业务 JSON
215
256
  text = _extract_mcp_text(raw)
216
257
  payload = _try_json(text) if text else None
217
258
  if not isinstance(payload, dict):
218
- # 纯文本回答(无 JSON)→ 包成 resp.content
219
- payload = {"resp": {"content": text or json.dumps(raw, ensure_ascii=False)}}
220
-
221
- # 2) 展开包装层
222
- payload = _unwrap_payload(payload)
259
+ # 纯文本回答(无业务 JSON)→ 包成 answer
260
+ payload = {"answer": text or json.dumps(raw, ensure_ascii=False)}
223
261
 
224
- # 3) 按模式规范化
262
+ # 2) 按模式做字段映射
225
263
  mode = args.mode or detect_mode(payload)
226
264
  if mode == "search":
227
265
  out = _normalize_search(payload)
@@ -123,7 +123,7 @@ python3 <skillDir>/scripts/adapt_mcp_result.py official-docs/search-results/dkno
123
123
  }
124
124
  ```
125
125
 
126
- 把 MCP 返回保存为 `official-docs/search-results/dknowc_search_mcp_raw.json`,然后:
126
+ 把 MCP 返回保存为 `official-docs/search-results/dknowc_search_mcp_raw.json`。**MCP 返回的实际字段形态**(与旧直连接口不同):内层为 `query`、`service_area`、`consult_date`、`knowledge_base_url`(知识专库链接,下划线命名)、`total_articles`、`materials[]`(每条含 `title`/`source`/`date`/`paragraph`/`url`)、`search_meta`。不要按旧接口的 `data.检索文章` 或 `referenceMaterials` 字段名直接读取 MCP 原始返回——先经过适配脚本转换:
127
127
 
128
128
  ```bash
129
129
  python3 <skillDir>/scripts/adapt_mcp_result.py official-docs/search-results/dknowc_search_mcp_raw.json \
@@ -136,6 +136,8 @@ python3 <skillDir>/scripts/render_trace_html.py \
136
136
  --question "用户原始问题"
137
137
  ```
138
138
 
139
+ 适配脚本会把 `materials` 转成渲染脚本消费的 `data.检索文章`(中文键,含标题/来源/发布日期/源网址/摘要),并把 `knowledge_base_url` 映射为 `knowledgeBase`(驼峰)。综合答案时直接读规范化后 JSON 的 `data.检索文章` 与 `knowledgeBase`。
140
+
139
141
  `render_trace_html.py` 会同时生成 HTML 和同名 `.clean.md`,输出到 `official-docs/output/`。如需指定干净 Markdown 路径,传 `--clean-md-output official-docs/output/xxx.md`。
140
142
 
141
143
  ## 深度搜索调用(MCP)
@@ -150,7 +152,7 @@ python3 <skillDir>/scripts/render_trace_html.py \
150
152
  }
151
153
  ```
152
154
 
153
- 把 MCP 返回保存为 `official-docs/search-results/dknowc_deep_mcp_raw.json`,然后:
155
+ 把 MCP 返回保存为 `official-docs/search-results/dknowc_deep_mcp_raw.json`。**MCP 返回的实际字段形态**:内层为 `query_id`、`status`(`finished` 等)、`progress[]`(深度搜索过程记录,**字符串数组**,如"[查询]xxx"、"[检索]找到相关…")、`search_groups[]` 与 `materials[]`(深度材料,可能为空——部分任务完成后材料经过程聚合输出)、`timings`。深度搜索**不直接返回答案正文**:最终答案由你基于 `progress` 过程记录与 `materials` 材料综合形成,保存为答案文件后经 `--answer-file` 传入渲染。然后:
154
156
 
155
157
  ```bash
156
158
  python3 <skillDir>/scripts/adapt_mcp_result.py official-docs/search-results/dknowc_deep_mcp_raw.json \
@@ -163,6 +165,8 @@ python3 <skillDir>/scripts/render_trace_html.py \
163
165
  --question "用户原始问题"
164
166
  ```
165
167
 
168
+ 适配脚本会把 `materials` / `search_groups` 中的材料归集为渲染脚本消费的 `data.list`,并保留 `progress` 过程记录。
169
+
166
170
  多地域、多层级任务应拆成多次调用,例如中国、重庆市、重庆两江新区分别搜索。如果用户没有明确要求深度搜索,不要主动调用。先完成可信搜索版答案和三件套交付,再询问用户是否升级深度搜索。
167
171
 
168
172
  ## ReAct 与追问规则
@@ -1,19 +1,37 @@
1
1
  #!/usr/bin/env python3
2
2
  """深知 dsh —— MCP 工具返回 → 渲染脚本输入 适配器。
3
3
 
4
- dsh 场景下,skill 不再直连深知接口,而是通过 MCP 工具
5
- (mcp__dknowc__credible_chat / _trusted_search / _deep_query)拿数据。
6
- MCP 工具返回的是 MCP 协议结构({content:[{type:"text",text:"..."}]}),
7
- 而 render_trace_html.py 等渲染脚本期望的是深知接口 JSON 结构。
8
-
9
- 本脚本把 MCP 返回规范化成渲染脚本可消费的接口 JSON,保证溯源 HTML
10
- 等交付物与直连版一致。
4
+ dsh 场景下,skill 通过深知可信工作台 MCP 工具(credible_chat /
5
+ trusted_search / deep_query,或注册后经 mcp_direct.py 直调)拿数据。
6
+ MCP 返回是协议结构 {content:[{type:"text",text:"<业务JSON>"}]},其内层
7
+ 业务 JSON 的字段形态与原直连接口不同,而 render_trace_html.py 等渲染
8
+ 脚本按原接口结构消费字段。
9
+
10
+ 本脚本按【MCP 实测返回】做字段映射(2026-08-19 实测三个工具确认):
11
+
12
+ credible_chat 内层(chat 模式,渲染脚本基本兼容,直通+防御):
13
+ answer 答案正文(渲染脚本 extract_answer 支持顶层 answer)
14
+ referenceMaterials[] 参考材料(title/url/sourceUrl/unit/content[].text 等,
15
+ 与 source_from_article 字段兼容,直接透传)
16
+ policyFiles[] / recommendationItems[] / trace_report_url 附加信息,透传保留
17
+
18
+ trusted_search 内层(search 模式,需要映射):
19
+ materials[{title,source,date,paragraph,url}] → data.检索文章[]
20
+ (渲染脚本 extract_articles_from_search 只认中文键 data.检索文章)
21
+ knowledge_base_url → knowledgeBase / knowledgeBaseUrl(渲染脚本只认驼峰)
22
+
23
+ deep_query 内层(deep 模式,需要映射):
24
+ materials[] / search_groups[].materials[] → data.list[]
25
+ (渲染脚本 extract_articles_from_deep 认 data.list)
26
+ progress[](字符串过程记录)原样保留,供 Agent 综合答案时参考
27
+ 答案不由接口给出,由 Agent 基于材料形成后经 --answer-file 传入
11
28
 
12
29
  用法:
13
30
  python3 scripts/adapt_mcp_result.py <mcp返回.json> --output <规范化.json> [--mode chat|search|deep]
14
31
 
15
- - 输入:模型保存的 MCP 工具返回 JSON(content 数组形式,或已含接口 JSON)
16
- - 输出:可直接传给 render_trace_html.py 的接口 JSON 结构
32
+ - 输入:MCP 工具返回 JSON(mcp_direct.py --output 的产物,或模型保存的
33
+ dsh mcp-client 工具返回;支持 content[].text / structuredContent / 已解包形态)
34
+ - 输出:render_trace_html.py 可直接消费的接口 JSON
17
35
  - --mode:chat=可信咨询 / search=可信搜索 / deep=深度搜索;缺省自动识别
18
36
  """
19
37
 
@@ -25,12 +43,12 @@ from typing import Any, Dict, List, Optional
25
43
 
26
44
 
27
45
  def _deep_find(o: Any, keys, depth=0, max_depth=8):
28
- """在任意嵌套结构里查找第一个命中任一 key 的值。"""
46
+ """在任意嵌套结构里查找第一个命中任一 key 的非空值。"""
29
47
  if depth > max_depth:
30
48
  return None
31
49
  if isinstance(o, dict):
32
50
  for k, v in o.items():
33
- if k in keys:
51
+ if k in keys and v not in (None, "", [], {}):
34
52
  return v
35
53
  r = _deep_find(v, keys, depth + 1, max_depth)
36
54
  if r is not None:
@@ -47,13 +65,11 @@ def _extract_mcp_text(o: Any) -> Optional[str]:
47
65
  """从 MCP 协议返回中提取文本内容。
48
66
 
49
67
  支持形态:
50
- - {content: [{type:"text", text:"..."}]}(MCP 标准,text 常为 JSON 字符串)
68
+ - {content: [{type:"text", text:"..."}]}(MCP 标准,text 为业务 JSON 字符串)
51
69
  - {structuredContent: {...}}
52
- - 直接就是接口 JSON
53
- 返回:解析出的 dict payload;无法解析时返回 None。
70
+ - 已是解包后的业务 JSON dict
54
71
  """
55
72
  if isinstance(o, dict):
56
- # structuredContent 优先
57
73
  sc = o.get("structuredContent")
58
74
  if isinstance(sc, dict):
59
75
  return json.dumps(sc, ensure_ascii=False)
@@ -67,8 +83,12 @@ def _extract_mcp_text(o: Any) -> Optional[str]:
67
83
  parts.append(block)
68
84
  if parts:
69
85
  return "\n".join(parts)
70
- # 已经是接口 JSON?
71
- if any(k in o for k in ("resp", "data", "referenceMaterials", "检索文章", "success")):
86
+ # result.content 嵌套形态(完整 MCP JSON-RPC 响应)
87
+ result = o.get("result")
88
+ if isinstance(result, dict):
89
+ return _extract_mcp_text(result)
90
+ # 已是业务 JSON(answer/materials/referenceMaterials 等特征键)
91
+ if any(k in o for k in ("answer", "referenceMaterials", "materials", "检索文章", "progress", "search_meta")):
72
92
  return json.dumps(o, ensure_ascii=False)
73
93
  return None
74
94
 
@@ -83,118 +103,139 @@ def _try_json(text: str) -> Any:
83
103
  return None
84
104
 
85
105
 
86
- def _unwrap_payload(o: Any) -> Dict[str, Any]:
87
- """递归展开嵌套的接口 JSON,找到最内层含业务字段的对象。
106
+ def _material_to_search_article(m: Dict[str, Any]) -> Dict[str, Any]:
107
+ """trusted_search 的 materials 条目 → 渲染脚本认的检索文章结构。
88
108
 
89
- 接口返回常见 {data: {resp: {...}, referenceMaterials:[...]}},
90
- 也偶见 {content: {data: {...}}} 等包装。这里尽量展开到业务层。
109
+ 渲染脚本 source_from_article 认的字段名(多 key 兜底):
110
+ 标题:文章标题/title/标题;来源:unit/sourceElement/数据源/发布机关/来源;
111
+ 日期:发布日期/date/发布时间;网址:sourceUrl/source_url/源网址/url/原文;
112
+ 摘录:摘要/相关段落/全文/content/text。
113
+ 这里把 MCP 的英文字段同时写入中文键与英文键,保证两条提取路径都能命中。
91
114
  """
92
- cur = o
93
- seen = set()
94
- while isinstance(cur, dict) and id(cur) not in seen:
95
- seen.add(id(cur))
96
- # 展开 {content:{...}} / {data:{...}} 包装,但保留 data 本身
97
- if len(cur) == 1:
98
- only = next(iter(cur.values()))
99
- if isinstance(only, dict):
100
- cur = only
101
- continue
102
- if isinstance(cur.get("data"), dict) and (
103
- "resp" in cur["data"] or "检索文章" in cur["data"] or "referenceMaterials" in cur["data"]
104
- ):
105
- # 保留外层 data 键,同时业务字段也升到顶层
106
- merged = dict(cur)
107
- merged.update({k: v for k, v in cur["data"].items() if k not in merged})
108
- merged["data"] = cur["data"]
109
- return merged
110
- break
111
- return cur if isinstance(cur, dict) else {"raw": cur}
115
+ title = str(m.get("title") or m.get("标题") or "")
116
+ source = str(m.get("source") or m.get("来源") or m.get("unit") or "")
117
+ date = str(m.get("date") or m.get("发布日期") or "")
118
+ url = str(m.get("url") or m.get("sourceUrl") or m.get("源网址") or "")
119
+ paragraph = str(m.get("paragraph") or m.get("content") or m.get("摘要") or "")
120
+ return {
121
+ "标题": title,
122
+ "title": title,
123
+ "来源": source,
124
+ "发布日期": date,
125
+ "date": date,
126
+ "源网址": url,
127
+ "sourceUrl": url,
128
+ "url": url,
129
+ "摘要": paragraph,
130
+ "全文": paragraph,
131
+ }
112
132
 
113
133
 
114
134
  def _normalize_chat(payload: Dict[str, Any]) -> Dict[str, Any]:
115
- """规范化可信咨询(credible_chat)返回。"""
135
+ """规范化可信咨询(credible_chat)返回。
136
+
137
+ MCP 内层已是顶层 answer + referenceMaterials 形态,渲染脚本
138
+ extract_answer / extract_sources / source_from_article 直接兼容,
139
+ 此处直通透传,仅做两处防御:
140
+ - answer 缺失时从任意位置兜底找正文,包成渲染脚本认的 resp.content
141
+ - 保留 trace_report_url / policyFiles / recommendationItems 等附加字段
142
+ """
116
143
  out = dict(payload)
117
- data = payload.get("data") if isinstance(payload.get("data"), dict) else {}
118
- # 确保 resp.content 可被提取
119
- if "resp" not in out:
120
- resp = data.get("resp") if isinstance(data, dict) else None
121
- if isinstance(resp, dict):
122
- out["resp"] = resp
123
- else:
124
- # 从任意位置找正文
125
- answer = _deep_find(payload, ("content", "answer", "text", "resp"), depth=0)
126
- if isinstance(answer, str):
127
- out["resp"] = {"content": answer}
128
- # 确保 referenceMaterials
129
- if "referenceMaterials" not in out:
130
- rm = data.get("referenceMaterials") if isinstance(data, dict) else None
131
- if isinstance(rm, list):
132
- out["referenceMaterials"] = rm
133
- # knowledgeBase / question
134
- for key in ("knowledgeBase", "question"):
135
- if key not in out and isinstance(data, dict) and key in data:
136
- out[key] = data[key]
144
+ if not (isinstance(out.get("answer"), str) and out.get("answer").strip()):
145
+ answer = _deep_find(payload, ("answer", "contentText"))
146
+ if isinstance(answer, str) and answer.strip():
147
+ out["answer"] = answer
148
+ # 渲染脚本 extract_answer 优先找 resp.content;补一份兼容形态
149
+ answer = out.get("answer")
150
+ if isinstance(answer, str) and answer.strip() and not isinstance(out.get("resp"), dict):
151
+ out["resp"] = {"content": answer}
137
152
  return out
138
153
 
139
154
 
140
155
  def _normalize_search(payload: Dict[str, Any]) -> Dict[str, Any]:
141
- """规范化可信搜索(trusted_search)返回。"""
156
+ """规范化可信搜索(trusted_search)返回:materials → data.检索文章,
157
+ knowledge_base_url → knowledgeBase(驼峰)。
158
+ """
142
159
  out = dict(payload)
143
- # 检索文章:优先顶层 data.检索文章,其次 content.data.检索文章
144
- articles = _deep_find(payload, ("检索文章",))
145
- if articles is None:
146
- content = payload.get("content") if isinstance(payload.get("content"), dict) else payload
147
- data = content.get("data") if isinstance(content.get("data"), dict) else {}
148
- articles = data.get("检索文章")
149
- if isinstance(articles, list):
150
- if "data" not in out or not isinstance(out["data"], dict):
151
- out["data"] = {}
152
- out["data"]["检索文章"] = articles
153
- # 确保 referenceMaterials
154
- if "referenceMaterials" not in out:
155
- rm = _deep_find(payload, ("referenceMaterials",))
156
- if isinstance(rm, list):
157
- out["referenceMaterials"] = rm
158
- # knowledgeBase
159
- if "knowledgeBase" not in out:
160
- kb = _deep_find(payload, ("knowledgeBase", "knowledgeBaseUrl"))
161
- if isinstance(kb, str):
162
- out["knowledgeBase"] = kb
160
+ materials = payload.get("materials")
161
+ if isinstance(materials, list):
162
+ articles = [_material_to_search_article(m) for m in materials if isinstance(m, dict)]
163
+ data = out.get("data") if isinstance(out.get("data"), dict) else {}
164
+ data["检索文章"] = articles
165
+ out["data"] = data
166
+ out["total_articles"] = out.get("total_articles") or len(articles)
167
+ # 兼容旧直连形态(content.data.检索文章)的防御提取
168
+ if not (isinstance(out.get("data"), dict) and isinstance(out["data"].get("检索文章"), list)):
169
+ legacy = _deep_find(payload, ("检索文章",))
170
+ if isinstance(legacy, list) and legacy:
171
+ data = out.get("data") if isinstance(out.get("data"), dict) else {}
172
+ data["检索文章"] = [x for x in legacy if isinstance(x, dict)]
173
+ out["data"] = data
174
+ # 知识专库链接:MCP 用下划线 knowledge_base_url,渲染脚本只认驼峰
175
+ kb = payload.get("knowledge_base_url") or payload.get("knowledgeBase") or payload.get("knowledgeBaseUrl")
176
+ if isinstance(kb, str) and kb.strip():
177
+ out["knowledgeBase"] = kb
178
+ out["knowledgeBaseUrl"] = kb
163
179
  return out
164
180
 
165
181
 
166
182
  def _normalize_deep(payload: Dict[str, Any]) -> Dict[str, Any]:
167
- """规范化深度搜索(deep_query)返回。"""
183
+ """规范化深度搜索(deep_query)返回:materials / search_groups → data.list,
184
+ progress(字符串过程)保留,knowledge_base_url 映射驼峰。
185
+ 深度搜索答案由 Agent 基于材料与 progress 综合形成,经 --answer-file 传入渲染。
186
+ """
168
187
  out = dict(payload)
169
- events = payload.get("events")
170
- if not isinstance(events, list):
171
- events = _deep_find(payload, ("events",))
172
- if isinstance(events, list):
173
- out["events"] = events
174
- # data.list 兜底
175
- data = payload.get("data") if isinstance(payload.get("data"), dict) else {}
176
- if isinstance(data.get("list"), list):
177
- out["data"] = data
178
- if "referenceMaterials" not in out:
179
- rm = _deep_find(payload, ("referenceMaterials",))
180
- if isinstance(rm, list):
181
- out["referenceMaterials"] = rm
188
+ items: List[Dict[str, Any]] = []
189
+ mats = payload.get("materials")
190
+ if isinstance(mats, list):
191
+ items.extend([m for m in mats if isinstance(m, dict)])
192
+ groups = payload.get("search_groups")
193
+ if isinstance(groups, list):
194
+ for g in groups:
195
+ if isinstance(g, dict) and isinstance(g.get("materials"), list):
196
+ items.extend([m for m in g["materials"] if isinstance(m, dict)])
197
+ elif isinstance(g, dict):
198
+ # search_groups 条目本身可能就是材料(含 title/url 等特征键)
199
+ if any(k in g for k in ("title", "url", "sourceUrl")):
200
+ items.append(g)
201
+ if items:
202
+ # 渲染脚本 extract_articles_from_deep 消费顶层 data.list
203
+ out["data"] = {"list": items}
204
+ # 兼容旧直连 events 形态的防御提取
205
+ if "data" not in out:
206
+ events = payload.get("events")
207
+ if isinstance(events, list):
208
+ out["events"] = events
209
+ kb = payload.get("knowledge_base_url") or payload.get("knowledgeBase") or payload.get("knowledgeBaseUrl")
210
+ if isinstance(kb, str) and kb.strip():
211
+ out["knowledgeBase"] = kb
212
+ out["knowledgeBaseUrl"] = kb
182
213
  return out
183
214
 
184
215
 
185
216
  def detect_mode(payload: Dict[str, Any]) -> str:
186
- """自动识别返回属于哪种接口。"""
187
- if _deep_find(payload, ("检索文章",)) is not None:
188
- return "search"
189
- if isinstance(payload.get("events"), list) or _deep_find(payload, ("events",)) is not None:
217
+ """按 MCP 实测特征自动识别接口类型。
218
+
219
+ deep 的特征键(query_id/progress/search_groups/deep_query_meta)最特异,
220
+ 必须先于 search 判断:deep 返回同样携带 materials 键,若先判 search
221
+ 会被误判(materials 为空列表也是 list)。
222
+ """
223
+ if (
224
+ "query_id" in payload
225
+ or isinstance(payload.get("progress"), list)
226
+ or isinstance(payload.get("search_groups"), list)
227
+ or isinstance(payload.get("deep_query_meta"), dict)
228
+ ):
190
229
  return "deep"
191
- if _deep_find(payload, ("resp",)) is not None:
192
- return "chat"
230
+ if isinstance(payload.get("search_meta"), dict) or (
231
+ isinstance(payload.get("materials"), list) and "answer" not in payload
232
+ ):
233
+ return "search"
193
234
  return "chat"
194
235
 
195
236
 
196
237
  def main() -> int:
197
- parser = argparse.ArgumentParser(description="MCP 返回 → 渲染脚本输入 适配器")
238
+ parser = argparse.ArgumentParser(description="MCP 返回 → 渲染脚本输入 适配器(按 2026-08-19 实测 MCP 结构映射)")
198
239
  parser.add_argument("input_json", help="MCP 工具返回 JSON 文件路径")
199
240
  parser.add_argument("--output", "-o", required=True, help="规范化 JSON 输出路径")
200
241
  parser.add_argument("--mode", choices=["chat", "search", "deep"], default=None, help="接口类型;缺省自动识别")
@@ -211,17 +252,14 @@ def main() -> int:
211
252
  print(f"错误:输入不是合法 JSON:{e}", file=sys.stderr)
212
253
  return 2
213
254
 
214
- # 1) 提取 MCP 文本 → 尝试解析成接口 JSON
255
+ # 1) 提取 MCP 协议层 → 业务 JSON
215
256
  text = _extract_mcp_text(raw)
216
257
  payload = _try_json(text) if text else None
217
258
  if not isinstance(payload, dict):
218
- # 纯文本回答(无 JSON)→ 包成 resp.content
219
- payload = {"resp": {"content": text or json.dumps(raw, ensure_ascii=False)}}
220
-
221
- # 2) 展开包装层
222
- payload = _unwrap_payload(payload)
259
+ # 纯文本回答(无业务 JSON)→ 包成 answer
260
+ payload = {"answer": text or json.dumps(raw, ensure_ascii=False)}
223
261
 
224
- # 3) 按模式规范化
262
+ # 2) 按模式做字段映射
225
263
  mode = args.mode or detect_mode(payload)
226
264
  if mode == "search":
227
265
  out = _normalize_search(payload)