dknowc-dsh 1.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 (89) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +131 -0
  3. package/cordis.patch.yml +17 -0
  4. package/package.json +33 -0
  5. package/skills/dknowc-official-doc-writer/README.md +156 -0
  6. package/skills/dknowc-official-doc-writer/SKILL.md +462 -0
  7. package/skills/dknowc-official-doc-writer/config/format.json +101 -0
  8. package/skills/dknowc-official-doc-writer/config/user_profile.json.example +6 -0
  9. package/skills/dknowc-official-doc-writer/official-docs/input/mcp_intro_content.md +61 -0
  10. package/skills/dknowc-official-doc-writer/reference/anti_ai_patterns.md +113 -0
  11. package/skills/dknowc-official-doc-writer/reference/fact_discipline.md +62 -0
  12. package/skills/dknowc-official-doc-writer/reference/material_usage_guidance.md +138 -0
  13. package/skills/dknowc-official-doc-writer/reference/output_guide.md +288 -0
  14. package/skills/dknowc-official-doc-writer/reference/review_checklist.md +156 -0
  15. package/skills/dknowc-official-doc-writer/reference/search_guide.md +317 -0
  16. package/skills/dknowc-official-doc-writer/reference/search_intro.md +15 -0
  17. package/skills/dknowc-official-doc-writer/reference/search_policy.md +284 -0
  18. package/skills/dknowc-official-doc-writer/reference/standards/00_index.md +151 -0
  19. package/skills/dknowc-official-doc-writer/reference/standards/01_report.md +51 -0
  20. package/skills/dknowc-official-doc-writer/reference/standards/02_qingshi.md +53 -0
  21. package/skills/dknowc-official-doc-writer/reference/standards/03_pifu.md +48 -0
  22. package/skills/dknowc-official-doc-writer/reference/standards/04_tongzhi.md +51 -0
  23. package/skills/dknowc-official-doc-writer/reference/standards/05_yijian.md +55 -0
  24. package/skills/dknowc-official-doc-writer/reference/standards/06_han.md +81 -0
  25. package/skills/dknowc-official-doc-writer/reference/standards/07_minutes.md +46 -0
  26. package/skills/dknowc-official-doc-writer/reference/standards/08_tongbao.md +53 -0
  27. package/skills/dknowc-official-doc-writer/reference/standards/09_tonggao.md +45 -0
  28. package/skills/dknowc-official-doc-writer/reference/standards/10_gonggao.md +44 -0
  29. package/skills/dknowc-official-doc-writer/reference/standards/11_fuhan_approve.md +46 -0
  30. package/skills/dknowc-official-doc-writer/reference/standards/12_fuhan_objection.md +46 -0
  31. package/skills/dknowc-official-doc-writer/reference/standards/13_reminder.md +46 -0
  32. package/skills/dknowc-official-doc-writer/reference/standards/14_generic.md +41 -0
  33. package/skills/dknowc-official-doc-writer/reference/standards/15_business_docs.md +47 -0
  34. package/skills/dknowc-official-doc-writer/reference/standards/16_decision.md +47 -0
  35. package/skills/dknowc-official-doc-writer/reference/standards/17_resolution.md +45 -0
  36. package/skills/dknowc-official-doc-writer/reference/standards/18_order.md +44 -0
  37. package/skills/dknowc-official-doc-writer/reference/standards/19_gazette.md +45 -0
  38. package/skills/dknowc-official-doc-writer/reference/standards/20_motion.md +45 -0
  39. package/skills/dknowc-official-doc-writer/reference/standards/21_explanation.md +40 -0
  40. package/skills/dknowc-official-doc-writer/reference/standards/22_application.md +47 -0
  41. package/skills/dknowc-official-doc-writer/reference/standards/23_publicity.md +46 -0
  42. package/skills/dknowc-official-doc-writer/reference/standards/24_procurement.md +40 -0
  43. package/skills/dknowc-official-doc-writer/reference/standards/25_plan.md +42 -0
  44. package/skills/dknowc-official-doc-writer/reference/standards/26_summary.md +42 -0
  45. package/skills/dknowc-official-doc-writer/reference/standards/27_speech.md +43 -0
  46. package/skills/dknowc-official-doc-writer/reference/standards/28_rules.md +40 -0
  47. package/skills/dknowc-official-doc-writer/reference/standards/29_research.md +42 -0
  48. package/skills/dknowc-official-doc-writer/reference/standards/30_feasibility.md +42 -0
  49. package/skills/dknowc-official-doc-writer/reference/standards/31_review_material.md +40 -0
  50. package/skills/dknowc-official-doc-writer/reference/standards/32_ai_compute.md +41 -0
  51. package/skills/dknowc-official-doc-writer/reference/standards/99_expressions.md +569 -0
  52. package/skills/dknowc-official-doc-writer/reference/task_router.md +119 -0
  53. package/skills/dknowc-official-doc-writer/scripts/adapt_mcp_result.py +241 -0
  54. package/skills/dknowc-official-doc-writer/scripts/check_release.py +78 -0
  55. package/skills/dknowc-official-doc-writer/scripts/dkag_search.py +575 -0
  56. package/skills/dknowc-official-doc-writer/scripts/format_document.py +1756 -0
  57. package/skills/dknowc-official-doc-writer/scripts/initialize.py +178 -0
  58. package/skills/dknowc-official-doc-writer/scripts/mcp_direct.py +158 -0
  59. package/skills/dknowc-official-doc-writer/scripts/merge_search_results.py +223 -0
  60. package/skills/dknowc-official-doc-writer/scripts/outline_reference.py +202 -0
  61. package/skills/dknowc-official-doc-writer/scripts/prose_lint.py +242 -0
  62. package/skills/dknowc-official-doc-writer/scripts/register.mjs +218 -0
  63. package/skills/dknowc-official-doc-writer/scripts/render_trace_html.py +966 -0
  64. package/skills/dknowc-official-doc-writer/scripts/review_document.py +127 -0
  65. package/skills/dknowc-official-doc-writer/scripts/source_note_html.py +180 -0
  66. package/skills/dknowc-official-doc-writer/scripts/template_generator.py +975 -0
  67. package/skills/dknowc-trusted-consulting/README.md +63 -0
  68. package/skills/dknowc-trusted-consulting/SKILL.md +172 -0
  69. package/skills/dknowc-trusted-consulting/scripts/adapt_mcp_result.py +241 -0
  70. package/skills/dknowc-trusted-consulting/scripts/check_release.py +66 -0
  71. package/skills/dknowc-trusted-consulting/scripts/gov_chat.py +475 -0
  72. package/skills/dknowc-trusted-consulting/scripts/initialize.py +89 -0
  73. package/skills/dknowc-trusted-consulting/scripts/mcp_direct.py +158 -0
  74. package/skills/dknowc-trusted-consulting/scripts/register_key.mjs +181 -0
  75. package/skills/dknowc-trusted-consulting/scripts/render_trace_html.py +990 -0
  76. package/skills/dknowc-trusted-search/README.md +63 -0
  77. package/skills/dknowc-trusted-search/SKILL.md +232 -0
  78. package/skills/dknowc-trusted-search/official-docs/output/.gitkeep +0 -0
  79. package/skills/dknowc-trusted-search/official-docs/search-results/.gitkeep +0 -0
  80. package/skills/dknowc-trusted-search/scripts/adapt_mcp_result.py +241 -0
  81. package/skills/dknowc-trusted-search/scripts/check_release.py +79 -0
  82. package/skills/dknowc-trusted-search/scripts/deep_query.py +266 -0
  83. package/skills/dknowc-trusted-search/scripts/initialize.py +89 -0
  84. package/skills/dknowc-trusted-search/scripts/mcp_direct.py +158 -0
  85. package/skills/dknowc-trusted-search/scripts/register_key.mjs +181 -0
  86. package/skills/dknowc-trusted-search/scripts/render_policy_visualization.py +889 -0
  87. package/skills/dknowc-trusted-search/scripts/render_trace_html.py +1011 -0
  88. package/skills/dknowc-trusted-search/scripts/trusted_search.py +325 -0
  89. package/src/index.js +103 -0
@@ -0,0 +1,266 @@
1
+ #!/usr/bin/env python3
2
+ """深知可信搜索深度搜索调用脚本。
3
+
4
+ 调用 deep-query/v2 SSE 接口,适合复杂政策研究、方案设计和多轮查证。
5
+ 默认不传 queryId,由接口自动生成。
6
+ """
7
+
8
+ import argparse
9
+ import json
10
+ import os
11
+ import socket
12
+ import sys
13
+ import time
14
+ import urllib.error
15
+ import urllib.request
16
+ from pathlib import Path
17
+ from typing import Any, Dict, Iterable, List, Optional, Tuple
18
+
19
+
20
+ DEFAULT_ENDPOINT = "https://open.dknowc.cn/api/services/deep-query/v2"
21
+ SKILL_ROOT = Path(__file__).resolve().parent.parent
22
+ # 工作区根:dsh 场景通过环境变量 DKNWOC_WS_ROOT 指向会话工作区,未设置时回退到 skill 目录(SkillHub 兼容)
23
+ import os as _os
24
+ WS_ROOT = Path(_os.environ.get("DKNWOC_WS_ROOT") or _os.getcwd()).resolve()
25
+
26
+ SEARCH_RESULTS_DIR = WS_ROOT / "official-docs" / "search-results"
27
+
28
+
29
+ def resolve_output_json(output_path: str) -> Path:
30
+ """把深度搜索结果 JSON 落到 official-docs/search-results/,阻断路径遍历。"""
31
+ raw_path = Path(output_path).expanduser()
32
+ if raw_path.is_absolute():
33
+ resolved = raw_path.resolve()
34
+ elif raw_path.parent == Path("."):
35
+ resolved = (SEARCH_RESULTS_DIR / raw_path.name).resolve()
36
+ else:
37
+ resolved = (WS_ROOT / raw_path).resolve()
38
+
39
+ if resolved.suffix.lower() != ".json":
40
+ resolved = resolved.with_suffix(".json")
41
+ try:
42
+ resolved.relative_to(SEARCH_RESULTS_DIR.resolve())
43
+ except ValueError:
44
+ raise ValueError(f"输出文件必须位于 official-docs/search-results/ 内: {output_path}")
45
+ return resolved
46
+
47
+
48
+ def _pick(*values: Optional[str]) -> str:
49
+ for value in values:
50
+ if value:
51
+ return value.strip()
52
+ return ""
53
+
54
+
55
+ def _validate_area(value: str) -> str:
56
+ value = value.strip()
57
+ multi_area_markers = [",", ",", "、", ";", ";", "/", "|", " 和 ", " 与 ", "及"]
58
+ if any(marker in value for marker in multi_area_markers):
59
+ print(
60
+ "错误:areas 每次只传一个地域,例如 北京市、重庆市、重庆两江新区;复杂任务需要多地域时请拆成多次调用。",
61
+ file=sys.stderr,
62
+ )
63
+ sys.exit(2)
64
+ return value
65
+
66
+
67
+ def _build_payload(args: argparse.Namespace) -> Dict[str, Any]:
68
+ payload: Dict[str, Any] = {"question": args.question}
69
+
70
+ areas = args.area
71
+ if areas:
72
+ payload["areas"] = [_validate_area(areas)]
73
+
74
+ query_id = args.query_id
75
+ if query_id:
76
+ payload["queryId"] = query_id
77
+
78
+ return payload
79
+
80
+
81
+ def _post_sse(url: str, api_key: str, payload: Dict[str, Any], timeout: int) -> Tuple[List[Tuple[str, Dict[str, Any]]], Dict[str, float]]:
82
+ data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
83
+ req = urllib.request.Request(url, data=data, method="POST")
84
+ req.add_header("api-key", api_key)
85
+ req.add_header("Content-Type", "application/json")
86
+
87
+ events: List[Tuple[str, Dict[str, Any]]] = []
88
+ timings = {"start": time.perf_counter(), "first_event": 0.0, "total": 0.0}
89
+ current_event = "message"
90
+
91
+ try:
92
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
93
+ while True:
94
+ raw_line = resp.readline()
95
+ if not raw_line:
96
+ break
97
+ line = raw_line.decode("utf-8", errors="replace").replace("\x00", "").strip()
98
+ if not line:
99
+ continue
100
+ if line.startswith("event:"):
101
+ current_event = line.split(":", 1)[1].strip() or "message"
102
+ continue
103
+ if not line.startswith("data:"):
104
+ continue
105
+ chunk = line[5:].strip()
106
+ if chunk == "[DONE]":
107
+ break
108
+ try:
109
+ obj = json.loads(chunk)
110
+ except json.JSONDecodeError:
111
+ obj = {"raw": chunk}
112
+ if not timings["first_event"]:
113
+ timings["first_event"] = time.perf_counter() - timings["start"]
114
+ events.append((current_event, obj))
115
+ if current_event == "done":
116
+ break
117
+ except urllib.error.HTTPError as e:
118
+ detail = e.read().decode("utf-8", errors="ignore")
119
+ print(f"错误:HTTP {e.code} {detail or e.reason}", file=sys.stderr)
120
+ sys.exit(1)
121
+ except urllib.error.URLError as e:
122
+ print(f"错误:网络请求失败 - {e.reason}", file=sys.stderr)
123
+ sys.exit(1)
124
+ except socket.timeout:
125
+ print("错误:深度搜索接口请求超时。该接口耗时较长,可适当增大 --timeout。", file=sys.stderr)
126
+ sys.exit(1)
127
+ finally:
128
+ timings["total"] = time.perf_counter() - timings["start"]
129
+
130
+ return events, timings
131
+
132
+
133
+ def _query_id(events: Iterable[Tuple[str, Dict[str, Any]]]) -> str:
134
+ last = ""
135
+ for _, obj in events:
136
+ value = obj.get("queryId")
137
+ if isinstance(value, str) and value.strip():
138
+ last = value.strip()
139
+ return last
140
+
141
+
142
+ def _result_data(events: Iterable[Tuple[str, Dict[str, Any]]]) -> Dict[str, Any]:
143
+ for event, obj in events:
144
+ if event == "result":
145
+ data = obj.get("data")
146
+ if isinstance(data, dict):
147
+ return data
148
+ return {}
149
+
150
+
151
+ def _short(text: Any, limit: int = 180) -> str:
152
+ value = " ".join(str(text or "").split())
153
+ if len(value) <= limit:
154
+ return value
155
+ return value[:limit].rstrip() + "..."
156
+
157
+
158
+ def _print_summary(events: List[Tuple[str, Dict[str, Any]]], timings: Dict[str, float], show_materials: int) -> None:
159
+ print("深度搜索结果")
160
+ print(f"首个事件耗时:{timings['first_event']:.2f} 秒")
161
+ print(f"总耗时:{timings['total']:.2f} 秒")
162
+
163
+ progress = [obj.get("message") for event, obj in events if event == "progress" and obj.get("message")]
164
+ if progress:
165
+ print("\n搜索过程")
166
+ for item in progress:
167
+ print(f"- {_short(item, 500)}")
168
+
169
+ data = _result_data(events)
170
+ result_list = data.get("list")
171
+ if isinstance(result_list, list):
172
+ print(f"\n召回材料:{len(result_list)} 条")
173
+
174
+ groups = data.get("searchGroupInfos")
175
+ if isinstance(groups, list) and groups:
176
+ print("\n搜索分组")
177
+ for group in groups:
178
+ if not isinstance(group, dict):
179
+ continue
180
+ area = group.get("area") or ""
181
+ text = group.get("text") or ""
182
+ count = len(group.get("voMd5List") or [])
183
+ print(f"- {area} {text}({count} 条)".strip())
184
+
185
+ if isinstance(result_list, list) and result_list and show_materials > 0:
186
+ print(f"\n重点材料(前 {min(show_materials, len(result_list))} 条)")
187
+ for idx, item in enumerate(result_list[:show_materials], start=1):
188
+ if not isinstance(item, dict):
189
+ continue
190
+ vo = item.get("vo") if isinstance(item.get("vo"), dict) else {}
191
+ title = vo.get("showTitle") or vo.get("title") or item.get("title") or "未命名材料"
192
+ type_name = vo.get("typeName") or vo.get("type") or ""
193
+ area = vo.get("areaName") or ""
194
+ date = vo.get("dateTime") or vo.get("createDate") or ""
195
+ url = vo.get("sourceUrl") or vo.get("url") or ""
196
+ print(f"{idx}. {title}")
197
+ if type_name or area or date:
198
+ print(f" 类型/地域/日期:{' | '.join(v for v in [type_name, area, date] if v)}")
199
+ if url:
200
+ print(f" 原文:{url}")
201
+
202
+ event_names = [event for event, _ in events]
203
+ if "done" in event_names:
204
+ print("\n状态:检索完成")
205
+
206
+
207
+ def main() -> None:
208
+ parser = argparse.ArgumentParser(description="深知可信搜索 deep-query/v2 深度搜索调用脚本")
209
+ parser.add_argument("question", help="用户复杂问题")
210
+ parser.add_argument("--endpoint", help="覆盖深度搜索接口地址")
211
+ parser.add_argument("--area", help="单个地域,例如 北京市、重庆市、重庆两江新区")
212
+ parser.add_argument("--query-id", help="显式传入 queryId;默认不传,由接口自动生成")
213
+ parser.add_argument("--show-payload", action="store_true", help="打印请求参数")
214
+ parser.add_argument("--dry-run", action="store_true", help="只打印请求参数,不发起请求")
215
+ parser.add_argument("--raw", action="store_true", help="打印原始事件 JSON")
216
+ parser.add_argument("--json-only", action="store_true", help="仅输出结构化 JSON")
217
+ parser.add_argument("--output", "-o", help="深度搜索结果 JSON 文件名,写入 official-docs/search-results/(配合 --json-only 使用)")
218
+ parser.add_argument("--show-materials", type=int, default=5, help="摘要中展示前 N 条材料")
219
+ parser.add_argument("--timeout", type=int, default=180, help="请求超时秒数")
220
+ args = parser.parse_args()
221
+
222
+ endpoint = _pick(
223
+ args.endpoint,
224
+ os.environ.get("DKNOWC_KNOW_DEEP_QUERY_ENDPOINT"),
225
+ os.environ.get("DKNOWC_DEEP_QUERY_ENDPOINT"),
226
+ DEFAULT_ENDPOINT,
227
+ )
228
+ api_key = _pick(
229
+ os.environ.get("DKNOWC_API_KEY"),
230
+ )
231
+ if not api_key:
232
+ print("错误:缺少 api_key,请配置环境变量 DKNOWC_API_KEY。", file=sys.stderr)
233
+ sys.exit(2)
234
+
235
+ payload = _build_payload(args)
236
+ if args.show_payload:
237
+ print("=== 请求参数 ===")
238
+ print(json.dumps(payload, ensure_ascii=False, indent=2))
239
+ print()
240
+ if args.dry_run:
241
+ return
242
+
243
+ events, timings = _post_sse(endpoint, api_key, payload, args.timeout)
244
+
245
+ if args.json_only:
246
+ raw_json = json.dumps({"success": True, "timings": timings, "events": events}, ensure_ascii=False, indent=2)
247
+ if args.output:
248
+ output_path = resolve_output_json(args.output)
249
+ output_path.parent.mkdir(parents=True, exist_ok=True)
250
+ output_path.write_text(raw_json, encoding="utf-8")
251
+ print(f"已保存深度搜索结果 JSON:{_rel_to_ws(output_path)}")
252
+ else:
253
+ print(raw_json)
254
+ return
255
+
256
+ if args.raw:
257
+ for event, obj in events:
258
+ print(f"event:{event}")
259
+ print(json.dumps(obj, ensure_ascii=False))
260
+ return
261
+
262
+ _print_summary(events, timings, args.show_materials)
263
+
264
+
265
+ if __name__ == "__main__":
266
+ main()
@@ -0,0 +1,89 @@
1
+ #!/usr/bin/env python3
2
+ """深知可信搜索 SkillHub / WorkBuddy public 版初始化检查。
3
+
4
+ Public 版统一只从环境变量 DKNOWC_API_KEY 读取 API Key,不读取、不写入本地 config.ini 中的 Key。
5
+ """
6
+
7
+ import json
8
+ import os
9
+
10
+
11
+ API_KEY_ENV = "DKNOWC_API_KEY"
12
+ PLACEHOLDER_KEYS = {"", "your_api_key_here", "你的深知可信搜索 API Key", "你的深知搜索 API Key"}
13
+
14
+
15
+ def _looks_like_key(value: str) -> bool:
16
+ value = (value or "").strip()
17
+ return value not in PLACEHOLDER_KEYS and value.startswith("sk-")
18
+
19
+
20
+ def _in_dsh() -> bool:
21
+ """dsh 环境标志:dsh 的 bash 工具会注入 DSH_SHELL=1。
22
+
23
+ dsh 场景下,脚本子进程无法隐式继承 DKNOWC_API_KEY(dsh 安全机制会清理
24
+ 名字含 KEY 的环境变量),但 dsh 插件会通过 shell-env 显式通道把该 Key
25
+ 注入为 DSH_DKNOWC_API_KEY。因此检查 DSH_DKNOWC_API_KEY 即可真实判断
26
+ "dsh 主进程环境变量是否已配置 DKNOWC_API_KEY"。
27
+ """
28
+ return os.environ.get("DSH_SHELL") == "1"
29
+
30
+
31
+ def check_api_key_config():
32
+ if _in_dsh():
33
+ # dsh 场景:读取插件注入的 DSH_DKNOWC_API_KEY(来源为 dsh 主进程的 DKNOWC_API_KEY)
34
+ api_key = os.environ.get("DSH_DKNOWC_API_KEY", "").strip()
35
+ if _looks_like_key(api_key):
36
+ return {
37
+ "api_key_configured": True,
38
+ "api_key_env": "DKNOWC_API_KEY (DSH_DKNOWC_API_KEY)",
39
+ "api_key_source": "environment",
40
+ "api_key_hint": None,
41
+ "search_ready": True,
42
+ "search_note": "dsh 场景:接口经深知可信工作台 MCP 转接(trusted_search / deep_query),API Key 由 dsh 主进程环境变量 DKNOWC_API_KEY 提供(经 shell-env 显式注入为 DSH_DKNOWC_API_KEY)。",
43
+ }
44
+ return {
45
+ "api_key_configured": False,
46
+ "api_key_env": API_KEY_ENV,
47
+ "api_key_source": None,
48
+ "api_key_hint": f"未检测到可用的 {API_KEY_ENV}(dsh 主进程环境变量未配置或为空)。需要先将有效的 API Key 配置到启动 dsh 的环境变量 {API_KEY_ENV}(如 ~/.zshrc),再重启 dsh 或新建会话。",
49
+ "search_ready": False,
50
+ "search_note": f"当前缺少 {API_KEY_ENV},暂时无法查询政策法规、办事流程、标准依据和可信溯源内容。",
51
+ }
52
+
53
+ api_key = os.environ.get(API_KEY_ENV, "").strip()
54
+ if _looks_like_key(api_key):
55
+ return {
56
+ "api_key_configured": True,
57
+ "api_key_env": API_KEY_ENV,
58
+ "api_key_source": "environment",
59
+ "api_key_hint": None,
60
+ "search_ready": True,
61
+ "search_note": None,
62
+ }
63
+
64
+ return {
65
+ "api_key_configured": False,
66
+ "api_key_env": API_KEY_ENV,
67
+ "api_key_source": None,
68
+ "api_key_hint": f"本 Skill 需要通过 {API_KEY_ENV} 连接深知可信智能服务以获取可信内容。当前未检测到可用 Key,请先注册或登录深知智能 MaaS 账号并获取 API Key。",
69
+ "search_ready": False,
70
+ "search_note": f"当前缺少 {API_KEY_ENV},暂时不能查询政策法规、办事流程、标准依据和可信溯源内容。",
71
+ }
72
+
73
+
74
+ def main():
75
+ status = check_api_key_config()
76
+ blocking_issues = []
77
+ if not status["api_key_configured"]:
78
+ blocking_issues.append("api_key_missing")
79
+
80
+ print(json.dumps({
81
+ **status,
82
+ "blocking_issues": blocking_issues,
83
+ "ready": not blocking_issues,
84
+ "maas_platform_url": "https://platform.dknowc.cn/",
85
+ }, ensure_ascii=False, indent=2))
86
+
87
+
88
+ if __name__ == "__main__":
89
+ main()
@@ -0,0 +1,158 @@
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>"}]}
23
+ """
24
+
25
+ import argparse
26
+ import json
27
+ import os
28
+ import sys
29
+ import urllib.error
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")
48
+ 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:
77
+ 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
82
+ except json.JSONDecodeError:
83
+ pass
84
+
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)
105
+ 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")
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 建议更大")
119
+ args = parser.parse_args()
120
+
121
+ api_key = os.environ.get(API_KEY_ENV, "").strip()
122
+ if not api_key:
123
+ print(f"错误:缺少环境变量 {API_KEY_ENV}(请用 DKNOWC_API_KEY=<key> 前缀赋值方式传入)。", file=sys.stderr)
124
+ return 2
125
+
126
+ try:
127
+ arguments = json.loads(args.args_json)
128
+ if not isinstance(arguments, dict):
129
+ raise ValueError("参数必须是 JSON 对象")
130
+ except (json.JSONDecodeError, ValueError) as e:
131
+ print(f"错误:参数不是合法 JSON 对象:{e}", file=sys.stderr)
132
+ return 2
133
+
134
+ endpoint = args.endpoint or DEFAULT_ENDPOINT
135
+ try:
136
+ result = _call_tool(api_key, args.tool, arguments, endpoint, args.timeout)
137
+ except RuntimeError as e:
138
+ print(f"错误:{e}", file=sys.stderr)
139
+ return 1
140
+
141
+ raw_json = json.dumps(result, ensure_ascii=False, indent=2)
142
+ if args.output:
143
+ out_path = os.path.abspath(args.output)
144
+ os.makedirs(os.path.dirname(out_path) or ".", exist_ok=True)
145
+ with open(out_path, "w", encoding="utf-8") as f:
146
+ f.write(raw_json)
147
+ print(f"已保存 MCP 返回:{out_path}")
148
+ else:
149
+ print(raw_json)
150
+
151
+ # 若工具返回 isError 或内嵌业务错误码,非零退出以提示
152
+ if result.get("isError"):
153
+ return 1
154
+ return 0
155
+
156
+
157
+ if __name__ == "__main__":
158
+ sys.exit(main())