dknowc-dsh 1.4.0 → 2.0.0

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.
Files changed (82) hide show
  1. package/README.md +18 -19
  2. package/package.json +3 -3
  3. package/skills/dknowc-official-doc-writer/README.md +18 -16
  4. package/skills/dknowc-official-doc-writer/SKILL.md +112 -143
  5. package/skills/dknowc-official-doc-writer/attribution.json +5 -0
  6. package/skills/dknowc-official-doc-writer/reference/material_usage_guidance.md +5 -0
  7. package/skills/dknowc-official-doc-writer/reference/onboarding_scripts.md +18 -8
  8. package/skills/dknowc-official-doc-writer/reference/output_guide.md +2 -2
  9. package/skills/dknowc-official-doc-writer/reference/research_notes.md +34 -0
  10. package/skills/dknowc-official-doc-writer/reference/review_checklist.md +2 -9
  11. package/skills/dknowc-official-doc-writer/reference/sample_trace_report.html +38 -18
  12. package/skills/dknowc-official-doc-writer/reference/search_guide.md +100 -33
  13. package/skills/dknowc-official-doc-writer/reference/search_intro.md +6 -6
  14. package/skills/dknowc-official-doc-writer/reference/search_policy.md +77 -55
  15. package/skills/dknowc-official-doc-writer/reference/task_router.md +6 -6
  16. package/skills/dknowc-official-doc-writer/scripts/api_key.py +41 -14
  17. package/skills/dknowc-official-doc-writer/scripts/attribution.py +60 -0
  18. package/skills/dknowc-official-doc-writer/scripts/build_trace_json.py +288 -0
  19. package/skills/dknowc-official-doc-writer/scripts/check_materials.py +265 -0
  20. package/skills/dknowc-official-doc-writer/scripts/deep_convert.py +235 -0
  21. package/skills/dknowc-official-doc-writer/scripts/deep_query.py +333 -0
  22. package/skills/dknowc-official-doc-writer/scripts/dkag_search.py +13 -4
  23. package/skills/dknowc-official-doc-writer/scripts/extract_reference.py +245 -0
  24. package/skills/dknowc-official-doc-writer/scripts/format_document.py +106 -18
  25. package/skills/dknowc-official-doc-writer/scripts/initialize.py +13 -7
  26. package/skills/dknowc-official-doc-writer/scripts/mcp_convert.py +272 -0
  27. package/skills/dknowc-official-doc-writer/scripts/mcp_direct.py +257 -143
  28. package/skills/dknowc-official-doc-writer/scripts/merge_search_results.py +72 -8
  29. package/skills/dknowc-official-doc-writer/scripts/outline_reference.py +14 -4
  30. package/skills/dknowc-official-doc-writer/scripts/prose_lint.py +6 -1
  31. package/skills/dknowc-official-doc-writer/scripts/register.mjs +122 -50
  32. package/skills/dknowc-official-doc-writer/scripts/render_trace_html.py +238 -94
  33. package/skills/dknowc-official-doc-writer/scripts/source_note_html.py +11 -2
  34. package/skills/dknowc-official-doc-writer/scripts/template_generator.py +13 -0
  35. package/skills/dknowc-ppt-assistant/README.md +14 -10
  36. package/skills/dknowc-ppt-assistant/SKILL.md +33 -15
  37. package/skills/dknowc-ppt-assistant/attribution.json +5 -0
  38. package/skills/dknowc-ppt-assistant/references/material_usage.md +9 -5
  39. package/skills/dknowc-ppt-assistant/references/onboarding_scripts.md +14 -2
  40. package/skills/dknowc-ppt-assistant/references/sample_trace_report.html +123 -115
  41. package/skills/dknowc-ppt-assistant/references/search_intro.md +1 -1
  42. package/skills/dknowc-ppt-assistant/references/svg-authoring.md +1 -1
  43. package/skills/dknowc-ppt-assistant/scripts/api_key.py +41 -14
  44. package/skills/dknowc-ppt-assistant/scripts/attribution.py +60 -0
  45. package/skills/dknowc-ppt-assistant/scripts/initialize.py +5 -3
  46. package/skills/dknowc-ppt-assistant/scripts/mcp_convert.py +188 -0
  47. package/skills/dknowc-ppt-assistant/scripts/register_key.mjs +184 -94
  48. package/skills/dknowc-ppt-assistant/scripts/render_trace_html.py +141 -121
  49. package/skills/dknowc-ppt-assistant/scripts/trusted_search.py +33 -3
  50. package/skills/dknowc-ppt-assistant/workflows/generate-pptx.md +15 -17
  51. package/skills/dknowc-trusted-search/README.md +27 -23
  52. package/skills/dknowc-trusted-search/SKILL.md +213 -141
  53. package/skills/dknowc-trusted-search/attribution.json +5 -0
  54. package/skills/dknowc-trusted-search/reference/onboarding_scripts.md +17 -7
  55. package/skills/dknowc-trusted-search/reference/sample_trace_report.html +129 -521
  56. package/skills/dknowc-trusted-search/scripts/api_key.py +41 -14
  57. package/skills/dknowc-trusted-search/scripts/attribution.py +61 -0
  58. package/skills/dknowc-trusted-search/scripts/chart_embed.py +350 -0
  59. package/skills/dknowc-trusted-search/scripts/deep_query.py +26 -5
  60. package/skills/dknowc-trusted-search/scripts/initialize.py +19 -27
  61. package/skills/dknowc-trusted-search/scripts/mcp_convert.py +189 -0
  62. package/skills/dknowc-trusted-search/scripts/merge_search_results.py +272 -0
  63. package/skills/dknowc-trusted-search/scripts/register_key.mjs +151 -45
  64. package/skills/dknowc-trusted-search/scripts/render_trace_html.py +340 -129
  65. package/skills/dknowc-trusted-search/scripts/trusted_search.py +28 -28
  66. package/src/index.js +2 -7
  67. package/skills/dknowc-ppt-assistant/scripts/adapt_mcp_result.py +0 -279
  68. package/skills/dknowc-trusted-consulting/README.md +0 -63
  69. package/skills/dknowc-trusted-consulting/SKILL.md +0 -241
  70. package/skills/dknowc-trusted-consulting/reference/consult_intro.md +0 -47
  71. package/skills/dknowc-trusted-consulting/reference/onboarding_scripts.md +0 -132
  72. package/skills/dknowc-trusted-consulting/reference/sample_consult_answer.md +0 -31
  73. package/skills/dknowc-trusted-consulting/reference/sample_trace_report.html +0 -867
  74. package/skills/dknowc-trusted-consulting/scripts/adapt_mcp_result.py +0 -283
  75. package/skills/dknowc-trusted-consulting/scripts/api_key.py +0 -41
  76. package/skills/dknowc-trusted-consulting/scripts/gov_chat.py +0 -508
  77. package/skills/dknowc-trusted-consulting/scripts/initialize.py +0 -123
  78. package/skills/dknowc-trusted-consulting/scripts/mcp_direct.py +0 -166
  79. package/skills/dknowc-trusted-consulting/scripts/register_key.mjs +0 -281
  80. package/skills/dknowc-trusted-consulting/scripts/render_trace_html.py +0 -2534
  81. package/skills/dknowc-trusted-search/scripts/adapt_mcp_result.py +0 -261
  82. package/skills/dknowc-trusted-search/scripts/render_policy_visualization.py +0 -894
@@ -1,166 +1,280 @@
1
1
  #!/usr/bin/env python3
2
- """深知 dsh —— MCP 临时直连客户端。
3
-
4
- dsh 场景下,MCP Bearer 认证在会话启动时从环境变量冻结,注册后拿到的新
5
- API Key 无法热注入到已运行的 mcp-client。本脚本作为"临时 Key 通道":
6
- 用 `DKNOWC_API_KEY=<临时Key> python3 mcp_direct.py ...` 前缀赋值方式,
7
- 把临时 Key 直接传给脚本(绕过 dsh 的环境清理),通过 HTTP 直调深知可信
8
- 工作台 MCP server 的 tools/call,输出与 dsh mcp-client 一致的 MCP 返回
9
- 结构,后续照常走 adapt_mcp_result.py → render_trace_html.py 链路。
10
-
11
- 用法:
12
- DKNOWC_API_KEY=<key> python3 mcp_direct.py <tool> '<json-args>' [--output <out.json>] [--timeout 120]
13
-
14
- 示例:
15
- DKNOWC_API_KEY=sk-xxx python3 mcp_direct.py credible_chat \
16
- '{"query": "深圳公积金租房提取需要哪些材料?", "area": "深圳"}' \
17
- --output official-docs/search-results/dknowc_mcp_raw.json
18
-
19
- 注意:
20
- - API Key 只通过环境变量 DKNOWC_API_KEY 传入(bash 前缀赋值),不得作为命令行参数
21
- - 不打印完整 Key,不持久化 Key
22
- - 输出为 MCP 协议结构 {"content":[{"type":"text","text":"<接口JSON>"}]}
2
+ """在 WorkBuddy 环境里,用脚本直连「本地 MCP 代理」调用深知可信工作台工具,
3
+ 把返回**原样落盘**到 search-results,全程不经模型上下文。
4
+
5
+ 背景(3.7.5):WorkBuddy 不把深知 MCP 的真实 OAuth 凭据放进 skill 环境,而是起一个
6
+ 本地代理(127.0.0.1,路径带会话级 hash),内部持有真实凭据转发到云端 mcp.dknowc.cn。
7
+ 环境变量 `CODEBUDDY_MCP_CONFIG` 内联 JSON 里含各 MCP server 的 url + headers
8
+ (Bearer 会话令牌)。脚本从该变量动态拿到 dknowc-mcp 的地址与头,直连代理发 JSON-RPC,
9
+ 返回的完整 JSON 由脚本写入文件——模型不抄写大 JSON,也就没有转写丢内容的问题
10
+ (此前模型调 MCP 工具会把 60-170KB 返回抄进上下文再落盘,实测丢失 83%)。
11
+
12
+ 只负责"调用 + 落盘原始返回";转换仍走现有 deep_convert.py / mcp_convert.py。
13
+
14
+ 用法(WorkBuddy 环境,必须有 CODEBUDDY_MCP_CONFIG):
15
+ python3 scripts/mcp_direct.py --tool deep_query --query "北京市养老服务政策" \
16
+ --areas 北京市 --area 北京市 --purpose "政策依据型" -o deep_policy.json
17
+ python3 scripts/mcp_direct.py --tool trusted_search --query "北京市养老服务政策" \
18
+ --areas 北京市 --area 北京市 --purpose "政策依据型" -o mcp_policy.json
19
+
20
+ 安全:脚本只读取并使用 url/headers,绝不打印 token / 会话令牌 / 代理路径 hash。
23
21
  """
24
22
 
23
+ from __future__ import annotations
24
+
25
25
  import argparse
26
26
  import json
27
27
  import os
28
28
  import sys
29
29
  import urllib.error
30
30
  import urllib.request
31
- from typing import Any, Dict, Optional
32
-
33
- DEFAULT_ENDPOINT = "https://mcp.dknowc.cn/s6/mcp/"
34
- PROTOCOL_VERSION = "2025-03-26"
35
- API_KEY_ENV = "DKNOWC_API_KEY"
36
-
37
-
38
- def _post(endpoint: str, api_key: str, payload: Dict[str, Any], session_id: Optional[str], timeout: int) -> tuple[int, str, Optional[str]]:
39
- """POST 一次 JSON-RPC,返回 (http_code, body, 新 session_id)。"""
40
- headers = {
41
- "Content-Type": "application/json",
42
- "Accept": "application/json, text/event-stream",
43
- "Authorization": f"Bearer {api_key}",
44
- }
45
- if session_id:
46
- headers["Mcp-Session-Id"] = session_id
47
- req = urllib.request.Request(endpoint, data=json.dumps(payload, ensure_ascii=False).encode("utf-8"), headers=headers, method="POST")
31
+ from pathlib import Path
32
+
33
+ SKILL_ROOT = Path(__file__).resolve().parent.parent
34
+ # 工作区根:dsh 场景通过环境变量 DKNWOC_WS_ROOT 指向会话工作区,未设置时回退到 skill 目录(SkillHub 兼容)
35
+ import os as _os
36
+ _ws = _os.environ.get("DKNWOC_WS_ROOT")
37
+ if not _ws:
38
+ # dsh 会话隔离:每会话独立产物目录 <工作区>/dknowc-output/<DSH_SESSION_ID前8位>/,
39
+ # 多会话共用同一工作区时互不混杂;非 dsh 环境回退为工作区本身。
40
+ _sid = _os.environ.get("DSH_SESSION_ID", "")
41
+ _ws = str(Path(_os.getcwd()) / "dknowc-output" / (_sid[:8] if _sid else "_default"))
42
+ WS_ROOT = Path(_ws).resolve()
43
+ SEARCH_RESULTS_DIR = WS_ROOT / "official-docs" / "search-results"
44
+
45
+ MCP_CONFIG_ENV = "CODEBUDDY_MCP_CONFIG"
46
+
47
+
48
+ def _walk(obj, path: str = ""):
49
+ """深度优先遍历任意嵌套结构,产出 (路径, 值),用于从 CODEBUDDY_MCP_CONFIG 里找 server。"""
50
+ if isinstance(obj, dict):
51
+ for k, v in obj.items():
52
+ yield from _walk(v, f"{path}.{k}" if path else str(k))
53
+ elif isinstance(obj, list):
54
+ for i, v in enumerate(obj):
55
+ yield from _walk(v, f"{path}[{i}]")
56
+ else:
57
+ yield path, obj
58
+
59
+
60
+ def find_dknowc_endpoint(config_raw: str):
61
+ """从 CODEBUDDY_MCP_CONFIG 里解析出深知 MCP 的 {url, headers}。
62
+
63
+ 结构未知(WorkBuddy 内部格式),自适应遍历:找含 dknowc/深知 标识的 server 项,
64
+ 取其 url/endpoint 与 headers。找不到时报错并打印键路径(不含值)辅助调试。
65
+ """
66
+ if not config_raw:
67
+ raise SystemExit(f"错误:环境变量 {MCP_CONFIG_ENV} 为空。本脚本只在 WorkBuddy 环境(宿主注入了该变量)可用。")
48
68
  try:
49
- with urllib.request.urlopen(req, timeout=timeout) as resp:
50
- body = resp.read().decode("utf-8", errors="replace")
51
- new_session = resp.headers.get("Mcp-Session-Id")
52
- return resp.status, body, new_session
53
- except urllib.error.HTTPError as e:
54
- body = e.read().decode("utf-8", errors="replace")
55
- return e.code, body, e.headers.get("Mcp-Session-Id")
56
- except urllib.error.URLError as e:
57
- raise RuntimeError(f"MCP 连接失败: {e.reason}")
58
-
59
-
60
- def _call_tool(api_key: str, tool: str, arguments: Dict[str, Any], endpoint: str, timeout: int) -> Dict[str, Any]:
61
- """initialize → tools/call,返回 MCP 标准结果。"""
62
- # 1. initialize 建立会话
63
- status, body, session_id = _post(endpoint, api_key, {
64
- "jsonrpc": "2.0",
65
- "id": 1,
66
- "method": "initialize",
67
- "params": {
68
- "protocolVersion": PROTOCOL_VERSION,
69
- "capabilities": {},
70
- "clientInfo": {"name": "dknowc-dsh-mcp-direct", "version": "1.0.0"},
71
- },
72
- }, None, timeout)
73
- if status not in (200, 202):
74
- raise RuntimeError(f"MCP initialize 失败 (HTTP {status}): {body[:300]}")
75
- # session_id 若未在响应头返回,尝试从 JSON 里读;无则沿用
76
- if not session_id:
69
+ data = json.loads(config_raw)
70
+ except json.JSONDecodeError as exc:
71
+ raise SystemExit(f"错误:{MCP_CONFIG_ENV} 不是合法 JSON({exc})。") from None
72
+
73
+ key_paths = []
74
+ for path, value in _walk(data):
75
+ key_paths.append(path)
76
+ if not isinstance(value, str):
77
+ continue
78
+ low = value.lower()
79
+ # 找 url 值且标识含 dknowc / 深知
80
+ if ("dknowc" in low or "深知" in low) and ("http" in low or "/mcp" in low):
81
+ # 向上找该 server 的 headers:遍历父路径太复杂,改为收集所有 server 候选后匹配
82
+ pass
83
+
84
+ # 简化策略:收集所有"可能是一组 server 配置"的节点(含 url + headers 的 dict)
85
+ candidates = []
86
+
87
+ def collect(node, hint: str = ""):
88
+ if isinstance(node, dict):
89
+ keys = {str(k).lower() for k in node.keys()}
90
+ url = node.get("url") or node.get("endpoint") or node.get("baseUrl") or node.get("serverUrl")
91
+ headers = node.get("headers") or node.get("header") or node.get("auth")
92
+ # server 名在 mcpServers 的**键**上(如 "dknowc-mcp"),不在节点内部;
93
+ # 节点内无 name 字段时用父级键名兜底,否则会退化成候选列表第一项而选错服务。
94
+ name = str(node.get("name") or node.get("serverName") or node.get("id") or hint or "").lower()
95
+ blob = f"{name} {url}".lower() if url else name
96
+ if url and headers and ("dknowc" in blob or "深知" in blob or "/mcp" in blob):
97
+ candidates.append({"url": str(url), "headers": headers, "name": name})
98
+ for k, v in node.items():
99
+ collect(v, str(k))
100
+ elif isinstance(node, list):
101
+ for v in node:
102
+ collect(v, hint)
103
+
104
+ collect(data)
105
+ if not candidates:
106
+ raise SystemExit(
107
+ "错误:未在 CODEBUDDY_MCP_CONFIG 中找到深知 MCP 的 url+headers。"
108
+ f"该变量键路径结构(不含值):{sorted(set(key_paths))[:30]}")
109
+
110
+ # 优先选明确含 dknowc 的
111
+ pick = next((c for c in candidates if "dknowc" in c["name"]), candidates[0])
112
+ headers = pick["headers"] if isinstance(pick["headers"], dict) else {}
113
+ # headers 可能是 {"Authorization": "Bearer ..."} 或带嵌套
114
+ norm = {}
115
+ if isinstance(headers, dict):
116
+ for k, v in headers.items():
117
+ norm[str(k)] = str(v)
118
+ elif isinstance(headers, list):
119
+ for h in headers:
120
+ if isinstance(h, dict):
121
+ for k, v in h.items():
122
+ norm[str(k)] = str(v)
123
+ return pick["url"], norm
124
+
125
+
126
+ def decode_jsonrpc(text: str) -> dict:
127
+ """解析 MCP 响应体,兼容纯 JSON 与 SSE(text/event-stream)两种形态。
128
+
129
+ 本地 MCP 代理即使收到的 Accept 同时包含 application/json,也可能仍以 SSE 返回
130
+ (`event: message\\ndata: {...}\\n\\n`);若直接 json.loads 会在 initialize 阶段
131
+ 报 "Expecting value: line 1 column 1 (char 0)"。此处先试纯 JSON,失败再逐行解析
132
+ SSE 的 `data:` 载荷,取最后一个可解析对象。
133
+ """
134
+ stripped = text.lstrip()
135
+ if stripped.startswith("{") or stripped.startswith("["):
136
+ return json.loads(text)
137
+ parsed = None
138
+ for line in text.splitlines():
139
+ line = line.strip()
140
+ if not line.startswith("data:"):
141
+ continue
142
+ payload = line[5:].strip()
143
+ if not payload or payload == "[DONE]":
144
+ continue
77
145
  try:
78
- init = json.loads(body)
79
- sid = init.get("result", {}).get("_meta", {}).get("sessionId")
80
- if isinstance(sid, str) and sid:
81
- session_id = sid
146
+ parsed = json.loads(payload)
82
147
  except json.JSONDecodeError:
83
- pass
148
+ continue
149
+ if parsed is None:
150
+ raise json.JSONDecodeError("响应体中未找到可解析 JSON(既非纯 JSON 也非 SSE data 载荷)", text, 0)
151
+ return parsed
152
+
153
+
154
+ _SESSION: dict = {}
84
155
 
85
- # 2. tools/call
86
- status, body, _ = _post(endpoint, api_key, {
87
- "jsonrpc": "2.0",
88
- "id": 2,
89
- "method": "tools/call",
90
- "params": {"name": tool, "arguments": arguments},
91
- }, session_id, timeout)
92
- if status not in (200, 202):
93
- raise RuntimeError(f"MCP tools/call 失败 (HTTP {status}): {body[:300]}")
94
-
95
- # 解析返回;streamable-http 可能是 SSE 或 JSON
96
- text = body.strip()
97
- # 若为 SSE 多行,取 data: 行拼接
98
- if text.startswith("event:") or "\ndata:" in text:
99
- chunks = []
100
- for line in text.splitlines():
101
- line = line.strip()
102
- if line.startswith("data:"):
103
- chunks.append(line[5:].strip())
104
- text = "\n".join(chunks)
156
+
157
+ def mcp_call(url: str, headers: dict, method: str, params: dict, timeout: int = 300) -> dict:
158
+ """发一次 MCP JSON-RPC,返回完整响应。streamableHttp,POST JSON。
159
+
160
+ 本地代理为有状态会话:initialize 响应头返回 mcp-session-id,后续 tools/call
161
+ 必须回带该头,否则代理返回 HTTP 400 Bad Request。
162
+ """
163
+ body = json.dumps({"jsonrpc": "2.0", "id": 1, "method": method, "params": params},
164
+ ensure_ascii=False).encode("utf-8")
165
+ req = urllib.request.Request(url, data=body, method="POST")
166
+ req.add_header("Content-Type", "application/json")
167
+ req.add_header("Accept", "application/json, text/event-stream")
168
+ if _SESSION.get("id"):
169
+ req.add_header("Mcp-Session-Id", _SESSION["id"])
170
+ for k, v in headers.items():
171
+ req.add_header(k, v)
105
172
  try:
106
- return json.loads(text)
107
- except json.JSONDecodeError:
108
- # 不是标准 JSON,包成 MCP content
109
- return {"content": [{"type": "text", "text": text}], "isError": False}
110
-
111
-
112
- def main() -> int:
113
- parser = argparse.ArgumentParser(description="MCP 临时直连客户端(注册后临时 Key 通道)")
114
- parser.add_argument("tool", help="MCP 工具名:credible_chat / trusted_search / deep_query / doc_outline")
115
- parser.add_argument("args_json", help="工具参数 JSON 字符串")
116
- parser.add_argument("--output", "-o", help="输出 JSON 文件路径(保存 MCP 原始返回)")
117
- parser.add_argument("--endpoint", default=None, help="MCP 端点,默认 https://mcp.dknowc.cn/s6/mcp/")
118
- parser.add_argument("--timeout", type=int, default=120, help="请求超时秒数,deep_query 建议更大")
173
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
174
+ sid = resp.headers.get("mcp-session-id")
175
+ if sid:
176
+ _SESSION["id"] = sid
177
+ text = resp.read().decode("utf-8", errors="replace")
178
+ except urllib.error.HTTPError as exc:
179
+ detail = exc.read().decode("utf-8", errors="replace")[:400]
180
+ raise SystemExit(f"错误:MCP {method} 返回 HTTP {exc.code}。响应体:{detail}") from None
181
+ data = decode_jsonrpc(text)
182
+ if "error" in data:
183
+ raise SystemExit(f"错误:MCP {method} 返回 error: {data['error']}")
184
+ return data
185
+
186
+
187
+ def main() -> None:
188
+ if hasattr(sys.stdout, "reconfigure"):
189
+ sys.stdout.reconfigure(encoding="utf-8")
190
+ parser = argparse.ArgumentParser(
191
+ description="WorkBuddy 环境直连本地 MCP 代理调用深知工具并把返回原样落盘(不经模型上下文)")
192
+ parser.add_argument("--tool", required=True, choices=["deep_query", "trusted_search"],
193
+ help="要调用的深知 MCP 工具")
194
+ parser.add_argument("--query", required=True, help="搜索 query(按 Query 生成原则)")
195
+ parser.add_argument("--areas", default="", help="地域;deep_query 传数组、trusted_search 传 service_area")
196
+ parser.add_argument("--area", default="", help="写入 search_meta 的检索地域(deep_convert/mcp_convert 用)")
197
+ parser.add_argument("--purpose", default="", help="搜索目的(内部参数,不向用户展示)")
198
+ parser.add_argument("--timeout", type=int, default=300, help="请求超时秒数(深度搜索较慢)")
199
+ parser.add_argument("--output", "-o", required=True, help="输出文件名,写入 official-docs/search-results/(原始返回)")
119
200
  args = parser.parse_args()
120
201
 
121
- api_key = os.environ.get(API_KEY_ENV, "").strip()
122
- if not api_key:
123
- # dsh 兜底:注册成功后 Key 已自动写入 ~/.zshrc(register.mjs 持久化),
124
- # 本进程环境变量可能未注入——从 ~/.zshrc 解析(api_key.py 同源逻辑)。
125
- try:
126
- from api_key import resolve_api_key
127
- api_key, _src = resolve_api_key()
128
- except ImportError:
129
- pass
130
- if not api_key:
131
- print(f"错误:缺少环境变量 {API_KEY_ENV}(请用 DKNOWC_API_KEY=<key> 前缀赋值方式传入)。", file=sys.stderr)
132
- return 2
202
+ url, headers = find_dknowc_endpoint(os.environ.get(MCP_CONFIG_ENV, ""))
133
203
 
204
+ # ① initialize(拿 serverInfo;无状态 server 也兼容)
134
205
  try:
135
- arguments = json.loads(args.args_json)
136
- if not isinstance(arguments, dict):
137
- raise ValueError("参数必须是 JSON 对象")
138
- except (json.JSONDecodeError, ValueError) as e:
139
- print(f"错误:参数不是合法 JSON 对象:{e}", file=sys.stderr)
140
- return 2
141
-
142
- endpoint = args.endpoint or DEFAULT_ENDPOINT
206
+ init = mcp_call(url, headers, "initialize", {
207
+ "protocolVersion": "2025-03-26",
208
+ "capabilities": {},
209
+ "clientInfo": {"name": "dknowc-skill-direct", "version": "3.7.5"},
210
+ }, timeout=30)
211
+ server = init.get("result", {}).get("serverInfo", {})
212
+ print(f"✓ MCP 连接:{server.get('name', '?')} v{server.get('version', '?')}(本地代理)")
213
+ except SystemExit:
214
+ raise
215
+ except Exception as exc:
216
+ raise SystemExit(f"错误:MCP initialize 失败({exc})。请确认 WorkBuddy 正在运行且深知 MCP 已连接。") from None
217
+
218
+ # ② tools/call
219
+ if args.tool == "deep_query":
220
+ tool_args = {"query": args.query}
221
+ if args.areas:
222
+ tool_args["areas"] = [a.strip() for a in args.areas.split(",") if a.strip()]
223
+ else: # trusted_search
224
+ tool_args = {
225
+ "query": args.query,
226
+ "include_details": True,
227
+ "max_articles": 50,
228
+ "material_length": 200000,
229
+ "policy": True,
230
+ "segment_count": 2,
231
+ "simplified": False,
232
+ "know_base": True,
233
+ "return_full_content": False,
234
+ }
235
+ if args.areas:
236
+ tool_args["service_area"] = args.areas.split(",")[0].strip()
237
+
238
+ result = mcp_call(url, headers, "tools/call", {"name": args.tool, "arguments": tool_args},
239
+ timeout=args.timeout)
240
+ content = result.get("result", {}).get("content", [])
241
+ texts = [c.get("text", "") for c in content if isinstance(c, dict) and c.get("type") == "text"]
242
+ if not texts:
243
+ raise SystemExit(f"错误:{args.tool} 未返回文本内容。原始响应: {json.dumps(result, ensure_ascii=False)[:300]}")
244
+ raw = texts[0]
245
+
246
+ # ③ 校验并落盘(程序化:内容直接进文件,不经模型)
143
247
  try:
144
- result = _call_tool(api_key, args.tool, arguments, endpoint, args.timeout)
145
- except RuntimeError as e:
146
- print(f"错误:{e}", file=sys.stderr)
147
- return 1
148
-
149
- raw_json = json.dumps(result, ensure_ascii=False, indent=2)
150
- if args.output:
151
- out_path = os.path.abspath(args.output)
152
- os.makedirs(os.path.dirname(out_path) or ".", exist_ok=True)
153
- with open(out_path, "w", encoding="utf-8") as f:
154
- f.write(raw_json)
155
- print(f"已保存 MCP 返回:{out_path}")
156
- else:
157
- print(raw_json)
248
+ parsed = json.loads(raw)
249
+ except json.JSONDecodeError as exc:
250
+ raise SystemExit(
251
+ f"错误:MCP {args.tool} 返回的 text 不是合法 JSON({exc})。这是接口返回问题,请保留原始响应排查。") from None
158
252
 
159
- # 若工具返回 isError 或内嵌业务错误码,非零退出以提示
160
- if result.get("isError"):
161
- return 1
162
- return 0
253
+ out = Path(args.output).expanduser()
254
+ if not out.is_absolute():
255
+ out = (SEARCH_RESULTS_DIR / out.name).resolve()
256
+ try:
257
+ out.relative_to(SEARCH_RESULTS_DIR.resolve())
258
+ except ValueError:
259
+ raise SystemExit(f"错误:输出文件必须位于 {SEARCH_RESULTS_DIR}") from None
260
+ out.parent.mkdir(parents=True, exist_ok=True)
261
+ out.write_text(raw, encoding="utf-8")
262
+
263
+ # ④ 摘要(不打印 token / 路径 hash)
264
+ summary = ""
265
+ if args.tool == "deep_query":
266
+ data = parsed.get("data") or {}
267
+ searches = data.get("searches") or []
268
+ total = sum(len(s.get("result") or []) for s in searches)
269
+ common = len(data.get("common_articles") or [])
270
+ summary = f"{total + common} 篇(子查询 {len(searches)} 组 + common {common})"
271
+ else:
272
+ mats = parsed.get("materials") or []
273
+ summary = f"{len(mats)} 篇 materials"
274
+ print(f"✓ {args.tool} 调用成功:{summary} → {out.relative_to(SKILL_ROOT)}")
275
+ print(f" 下一步:python3 scripts/{'deep_convert' if args.tool == 'deep_query' else 'mcp_convert'}.py {out.name} "
276
+ f"--area {args.area or '地域'} --purpose \"{args.purpose or '搜索目的'}\"")
163
277
 
164
278
 
165
279
  if __name__ == "__main__":
166
- sys.exit(main())
280
+ raise SystemExit(main())
@@ -6,6 +6,7 @@
6
6
 
7
7
  import argparse
8
8
  import json
9
+ import re
9
10
  import sys
10
11
  from pathlib import Path
11
12
  from typing import List, Dict
@@ -84,10 +85,13 @@ def merge_results(result_files: List[str]) -> Dict:
84
85
  """
85
86
  all_articles = []
86
87
  seen_titles = set()
88
+ by_key = {}
87
89
  duplicates_count = 0
88
90
  regions_searched = []
89
91
  searches = []
90
92
  knowledge_bases = []
93
+ all_policy_files = []
94
+ seen_policies = set()
91
95
 
92
96
  for file_path in result_files:
93
97
  try:
@@ -110,10 +114,14 @@ def merge_results(result_files: List[str]) -> Dict:
110
114
  search_meta = data.get("search_meta", {})
111
115
  region = search_meta.get("area") or infer_region_from_filename(str(safe_file_path))
112
116
  regions_searched.append(region)
117
+ # 搜索目的兜底(3.7.6 修复):该路 --purpose 为空时用该路 query 兜底——
118
+ # 若留空,文章"搜索目的"缺失,溯源报告分组键(search_key)会退化成
119
+ # "中国"/"浙江省"等地域碎片,材料面板筛选胶囊失去意义(杭州实测 75/295 篇退化)。
120
+ purpose_val = search_meta.get("purpose") or search_meta.get("query") or ""
113
121
  searches.append({
114
122
  "file": str(safe_file_path),
115
123
  "query": search_meta.get("query", ""),
116
- "purpose": search_meta.get("purpose", ""),
124
+ "purpose": purpose_val,
117
125
  "area": region,
118
126
  "time": search_meta.get("time", ""),
119
127
  "policy": search_meta.get("policy", False),
@@ -125,24 +133,79 @@ def merge_results(result_files: List[str]) -> Dict:
125
133
  knowledge_bases.append({
126
134
  "file": str(safe_file_path),
127
135
  "query": search_meta.get("query", ""),
128
- "purpose": search_meta.get("purpose", ""),
136
+ "purpose": purpose_val,
129
137
  "area": region,
130
138
  "knowledgeBase": data.get("knowledgeBase", ""),
131
139
  })
132
140
 
133
- # 去重合并
141
+ # 规范性文件清单(policyFiles,含发文字号):可信搜索补搜产物携带,
142
+ # 是溯源核验报告匹配"文号"的唯一来源,合并时必须带下去(此前被整体丢弃,
143
+ # 导致合并产物 policyFiles 恒为空、政策文件无法显示发文字号)。
144
+ for pf in (data.get("policyFiles") or []):
145
+ if not isinstance(pf, dict):
146
+ continue
147
+ key = (pf.get("writtenText") or "", pf.get("title") or "")
148
+ if key in seen_policies:
149
+ continue
150
+ seen_policies.add(key)
151
+ all_policy_files.append(pf)
152
+
153
+ # 去重合并(3.7.5 修复:合并式去重,禁止按标题整体丢弃后篇)
154
+ # 同一材料多次搜索返回时,标题相同但召回段落可能不同(各次搜索命中不同相关段落)——
155
+ # 按标题丢弃会丢掉其他搜索带来的段落;标题微小差异(空格/全半角/赘词)又可能漏去重。
156
+ # 正确做法:按"规范化标题 + 源网址"双键判同一材料,同一材料合并段落、字段取并集。
134
157
  for article in articles:
135
158
  title = article.get("文章标题", "")
136
- if title in seen_titles:
159
+ url = article.get("源网址") or article.get("sourceUrl") or article.get("原文链接") or ""
160
+ # 规范化标题:去空白、全角转半角、去公文开头(关于印发/关于)与结尾赘词后缀,
161
+ # 使"…管理办法" / "…管理办法的通知" / "关于印发…管理办法的通知" 判为同一材料(去重键,不改原文)
162
+ title_key = re.sub(r"\s+", "", title or "").replace(" ", "")
163
+ title_key = re.sub(r"^(关于印发|关于)", "", title_key)
164
+ title_key = re.sub(r"(的通知|的公告|的意见|的方案|的办法|的规定|的细则|的批复|的规划|的纲要)$", "", title_key)
165
+ url_key = re.sub(r"\s+", "", url or "").rstrip("/")
166
+ key = title_key if title_key else url_key
167
+ if not key:
168
+ all_articles.append(article)
169
+ continue
170
+
171
+ if key in seen_titles:
172
+ # 同一材料:合并段落(保留两篇的段落合集,段落级去重),字段取并集(保留非空者)
137
173
  duplicates_count += 1
174
+ existing = by_key[key]
175
+ # 合并段落:按内容去重合并,保留各自 id(后续统一重编号)
176
+ seen_para = set()
177
+ merged_paras = list(existing.get("段落") or [])
178
+ for p in merged_paras:
179
+ pc = p.get("内容") or p.get("content") or ""
180
+ if pc:
181
+ seen_para.add(re.sub(r"\s+", "", str(pc)))
182
+ for p in (article.get("段落") or []):
183
+ pc = p.get("内容") or p.get("content") or ""
184
+ if pc and re.sub(r"\s+", "", str(pc)) not in seen_para:
185
+ merged_paras.append(p)
186
+ existing["段落"] = merged_paras
187
+ # 字段取并集:已有字段非空则保留,空字段用后篇补
188
+ for f, v in article.items():
189
+ if f == "段落":
190
+ continue
191
+ if not existing.get(f) and v:
192
+ existing[f] = v
193
+ # 追加本次搜索的来源标记(搜索地域/搜索词/搜索目的)
194
+ if region and region not in (existing.get("搜索地域") or ""):
195
+ existing["搜索地域"] = (existing.get("搜索地域") or "") + (("、" + region) if existing.get("搜索地域") else region)
196
+ if search_meta.get("query") and not existing.get("搜索词"):
197
+ existing["搜索词"] = search_meta.get("query")
198
+ if purpose_val and not existing.get("搜索目的"):
199
+ existing["搜索目的"] = purpose_val
138
200
  continue
139
-
140
- seen_titles.add(title)
201
+
202
+ seen_titles.add(key)
203
+ by_key[key] = article
141
204
  article.setdefault("搜索地域", region)
142
205
  if search_meta.get("query"):
143
206
  article.setdefault("搜索词", search_meta.get("query"))
144
- if search_meta.get("purpose"):
145
- article.setdefault("搜索目的", search_meta.get("purpose"))
207
+ if purpose_val:
208
+ article.setdefault("搜索目的", purpose_val)
146
209
  if article.get("源网址") and not article.get("原文链接"):
147
210
  article["原文链接"] = article["源网址"]
148
211
  if article.get("sourceUrl") and not article.get("原文链接"):
@@ -165,6 +228,7 @@ def merge_results(result_files: List[str]) -> Dict:
165
228
  return {
166
229
  "cleaned": True,
167
230
  "articles": all_articles,
231
+ "policyFiles": all_policy_files,
168
232
  "search_summary": {
169
233
  "total_searches": len(result_files),
170
234
  "regions": list(set(regions_searched)),
@@ -89,12 +89,22 @@ def validate_query(query: str) -> str:
89
89
 
90
90
  def call_outline_api(query: str, api_key: str, timeout: int) -> tuple[int, dict | str, float]:
91
91
  start = time.time()
92
+ _headers = {
93
+ "api-key": api_key,
94
+ "Content-Type": "application/json",
95
+ }
96
+ # 来源声明(X-Dknowc-Attribution,仅统计用、不参与鉴权):
97
+ # 读包根 attribution.json + SKILL.md 的 version;读取失败不加头、不阻断请求。
98
+ try:
99
+ from attribution import build_attribution_header, ATTRIBUTION_HEADER
100
+ _attr = build_attribution_header()
101
+ if _attr:
102
+ _headers[ATTRIBUTION_HEADER] = _attr
103
+ except Exception:
104
+ pass
92
105
  response = requests.post(
93
106
  OUTLINE_API_URL,
94
- headers={
95
- "api-key": api_key,
96
- "Content-Type": "application/json",
97
- },
107
+ headers=_headers,
98
108
  json={"query": query},
99
109
  timeout=timeout,
100
110
  )
@@ -83,7 +83,12 @@ PATTERNS = [
83
83
  # --- 格式噪点 ---
84
84
  ("medium", "format", r"[一-鿿][,;:!?][一-鿿]", "中文正文中改用全角标点。"),
85
85
  ("low", "format", r"\d{1,3}(?:,\d{3})+(?:\.\d+)?", "确认正式中文材料中是否应取消千位分隔符。"),
86
- ("low", "format", r"\*\*[^*\n]{1,80}\*\*|^\s*#{1,6}\s+|^\s*---\s*$", "正式公文正文不要用 Markdown 加粗/标题/横线。"),
86
+ # 注:Markdown 标题(`#` / `##` / `###`)**不在本规则范围内**——output_guide.md 明确允许
87
+ # 用它们表达公文的标题层级(# 公文标题 / ## 一、 / ### (一)),转 Word 时映射为对应
88
+ # 字体字号。2026-09-29 修复:原正则含 `^\s*#{1,6}\s+`,对 Markdown 源稿必然误报
89
+ # "不要用 Markdown 标题",与 output_guide 直接冲突。
90
+ ("low", "format", r"\*\*[^*\n]{1,80}\*\*", "正文不要用 Markdown 加粗(`**文字**`),改用标题层级或自然行文。"),
91
+ ("low", "format", r"^\s*---\s*$", "正文不要用 Markdown 分割线(`---`)。"),
87
92
  ("low", "format", r"[\U0001F300-\U0001FAFF]", "正式公文正文避免使用 Emoji。"),
88
93
  ]
89
94