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.
- package/LICENSE +21 -0
- package/README.md +131 -0
- package/cordis.patch.yml +17 -0
- package/package.json +33 -0
- package/skills/dknowc-official-doc-writer/README.md +156 -0
- package/skills/dknowc-official-doc-writer/SKILL.md +462 -0
- package/skills/dknowc-official-doc-writer/config/format.json +101 -0
- package/skills/dknowc-official-doc-writer/config/user_profile.json.example +6 -0
- package/skills/dknowc-official-doc-writer/official-docs/input/mcp_intro_content.md +61 -0
- package/skills/dknowc-official-doc-writer/reference/anti_ai_patterns.md +113 -0
- package/skills/dknowc-official-doc-writer/reference/fact_discipline.md +62 -0
- package/skills/dknowc-official-doc-writer/reference/material_usage_guidance.md +138 -0
- package/skills/dknowc-official-doc-writer/reference/output_guide.md +288 -0
- package/skills/dknowc-official-doc-writer/reference/review_checklist.md +156 -0
- package/skills/dknowc-official-doc-writer/reference/search_guide.md +317 -0
- package/skills/dknowc-official-doc-writer/reference/search_intro.md +15 -0
- package/skills/dknowc-official-doc-writer/reference/search_policy.md +284 -0
- package/skills/dknowc-official-doc-writer/reference/standards/00_index.md +151 -0
- package/skills/dknowc-official-doc-writer/reference/standards/01_report.md +51 -0
- package/skills/dknowc-official-doc-writer/reference/standards/02_qingshi.md +53 -0
- package/skills/dknowc-official-doc-writer/reference/standards/03_pifu.md +48 -0
- package/skills/dknowc-official-doc-writer/reference/standards/04_tongzhi.md +51 -0
- package/skills/dknowc-official-doc-writer/reference/standards/05_yijian.md +55 -0
- package/skills/dknowc-official-doc-writer/reference/standards/06_han.md +81 -0
- package/skills/dknowc-official-doc-writer/reference/standards/07_minutes.md +46 -0
- package/skills/dknowc-official-doc-writer/reference/standards/08_tongbao.md +53 -0
- package/skills/dknowc-official-doc-writer/reference/standards/09_tonggao.md +45 -0
- package/skills/dknowc-official-doc-writer/reference/standards/10_gonggao.md +44 -0
- package/skills/dknowc-official-doc-writer/reference/standards/11_fuhan_approve.md +46 -0
- package/skills/dknowc-official-doc-writer/reference/standards/12_fuhan_objection.md +46 -0
- package/skills/dknowc-official-doc-writer/reference/standards/13_reminder.md +46 -0
- package/skills/dknowc-official-doc-writer/reference/standards/14_generic.md +41 -0
- package/skills/dknowc-official-doc-writer/reference/standards/15_business_docs.md +47 -0
- package/skills/dknowc-official-doc-writer/reference/standards/16_decision.md +47 -0
- package/skills/dknowc-official-doc-writer/reference/standards/17_resolution.md +45 -0
- package/skills/dknowc-official-doc-writer/reference/standards/18_order.md +44 -0
- package/skills/dknowc-official-doc-writer/reference/standards/19_gazette.md +45 -0
- package/skills/dknowc-official-doc-writer/reference/standards/20_motion.md +45 -0
- package/skills/dknowc-official-doc-writer/reference/standards/21_explanation.md +40 -0
- package/skills/dknowc-official-doc-writer/reference/standards/22_application.md +47 -0
- package/skills/dknowc-official-doc-writer/reference/standards/23_publicity.md +46 -0
- package/skills/dknowc-official-doc-writer/reference/standards/24_procurement.md +40 -0
- package/skills/dknowc-official-doc-writer/reference/standards/25_plan.md +42 -0
- package/skills/dknowc-official-doc-writer/reference/standards/26_summary.md +42 -0
- package/skills/dknowc-official-doc-writer/reference/standards/27_speech.md +43 -0
- package/skills/dknowc-official-doc-writer/reference/standards/28_rules.md +40 -0
- package/skills/dknowc-official-doc-writer/reference/standards/29_research.md +42 -0
- package/skills/dknowc-official-doc-writer/reference/standards/30_feasibility.md +42 -0
- package/skills/dknowc-official-doc-writer/reference/standards/31_review_material.md +40 -0
- package/skills/dknowc-official-doc-writer/reference/standards/32_ai_compute.md +41 -0
- package/skills/dknowc-official-doc-writer/reference/standards/99_expressions.md +569 -0
- package/skills/dknowc-official-doc-writer/reference/task_router.md +119 -0
- package/skills/dknowc-official-doc-writer/scripts/adapt_mcp_result.py +241 -0
- package/skills/dknowc-official-doc-writer/scripts/check_release.py +78 -0
- package/skills/dknowc-official-doc-writer/scripts/dkag_search.py +575 -0
- package/skills/dknowc-official-doc-writer/scripts/format_document.py +1756 -0
- package/skills/dknowc-official-doc-writer/scripts/initialize.py +178 -0
- package/skills/dknowc-official-doc-writer/scripts/mcp_direct.py +158 -0
- package/skills/dknowc-official-doc-writer/scripts/merge_search_results.py +223 -0
- package/skills/dknowc-official-doc-writer/scripts/outline_reference.py +202 -0
- package/skills/dknowc-official-doc-writer/scripts/prose_lint.py +242 -0
- package/skills/dknowc-official-doc-writer/scripts/register.mjs +218 -0
- package/skills/dknowc-official-doc-writer/scripts/render_trace_html.py +966 -0
- package/skills/dknowc-official-doc-writer/scripts/review_document.py +127 -0
- package/skills/dknowc-official-doc-writer/scripts/source_note_html.py +180 -0
- package/skills/dknowc-official-doc-writer/scripts/template_generator.py +975 -0
- package/skills/dknowc-trusted-consulting/README.md +63 -0
- package/skills/dknowc-trusted-consulting/SKILL.md +172 -0
- package/skills/dknowc-trusted-consulting/scripts/adapt_mcp_result.py +241 -0
- package/skills/dknowc-trusted-consulting/scripts/check_release.py +66 -0
- package/skills/dknowc-trusted-consulting/scripts/gov_chat.py +475 -0
- package/skills/dknowc-trusted-consulting/scripts/initialize.py +89 -0
- package/skills/dknowc-trusted-consulting/scripts/mcp_direct.py +158 -0
- package/skills/dknowc-trusted-consulting/scripts/register_key.mjs +181 -0
- package/skills/dknowc-trusted-consulting/scripts/render_trace_html.py +990 -0
- package/skills/dknowc-trusted-search/README.md +63 -0
- package/skills/dknowc-trusted-search/SKILL.md +232 -0
- package/skills/dknowc-trusted-search/official-docs/output/.gitkeep +0 -0
- package/skills/dknowc-trusted-search/official-docs/search-results/.gitkeep +0 -0
- package/skills/dknowc-trusted-search/scripts/adapt_mcp_result.py +241 -0
- package/skills/dknowc-trusted-search/scripts/check_release.py +79 -0
- package/skills/dknowc-trusted-search/scripts/deep_query.py +266 -0
- package/skills/dknowc-trusted-search/scripts/initialize.py +89 -0
- package/skills/dknowc-trusted-search/scripts/mcp_direct.py +158 -0
- package/skills/dknowc-trusted-search/scripts/register_key.mjs +181 -0
- package/skills/dknowc-trusted-search/scripts/render_policy_visualization.py +889 -0
- package/skills/dknowc-trusted-search/scripts/render_trace_html.py +1011 -0
- package/skills/dknowc-trusted-search/scripts/trusted_search.py +325 -0
- package/src/index.js +103 -0
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""检查运行环境,并按用户授权保存可选的本地写作偏好。"""
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import platform
|
|
8
|
+
import shutil
|
|
9
|
+
import sys
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
SKILL_ROOT = Path(__file__).resolve().parent.parent
|
|
14
|
+
API_KEY_ENV = "DKNOWC_API_KEY"
|
|
15
|
+
PROFILE_PATH = SKILL_ROOT / "config" / "user_profile.json"
|
|
16
|
+
ENV_STATE_PATH = SKILL_ROOT / "config" / "environment_state.json"
|
|
17
|
+
SCRIPTS_DIR = SKILL_ROOT / "scripts"
|
|
18
|
+
sys.path.insert(0, str(SCRIPTS_DIR))
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def load_environment_state():
|
|
22
|
+
if not ENV_STATE_PATH.exists():
|
|
23
|
+
return {}
|
|
24
|
+
try:
|
|
25
|
+
with ENV_STATE_PATH.open("r", encoding="utf-8") as state_file:
|
|
26
|
+
state = json.load(state_file)
|
|
27
|
+
return state if isinstance(state, dict) else {}
|
|
28
|
+
except (OSError, json.JSONDecodeError):
|
|
29
|
+
return {}
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def save_environment_state(state):
|
|
33
|
+
ENV_STATE_PATH.parent.mkdir(parents=True, exist_ok=True)
|
|
34
|
+
with ENV_STATE_PATH.open("w", encoding="utf-8") as state_file:
|
|
35
|
+
json.dump(state, state_file, ensure_ascii=False, indent=2)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def check_environment():
|
|
39
|
+
state = load_environment_state()
|
|
40
|
+
python3_available = shutil.which("python3") is not None
|
|
41
|
+
python_docx_available = _module_available("docx")
|
|
42
|
+
requests_available = _module_available("requests")
|
|
43
|
+
config_status = check_api_key_config()
|
|
44
|
+
blocking_issues = []
|
|
45
|
+
if not python3_available:
|
|
46
|
+
blocking_issues.append("python3_missing")
|
|
47
|
+
if not python_docx_available:
|
|
48
|
+
blocking_issues.append("python_docx_missing")
|
|
49
|
+
if not requests_available:
|
|
50
|
+
blocking_issues.append("requests_missing")
|
|
51
|
+
dependency_issues = [
|
|
52
|
+
issue for issue in blocking_issues
|
|
53
|
+
if issue in {"python3_missing", "python_docx_missing", "requests_missing"}
|
|
54
|
+
]
|
|
55
|
+
# API Key 只在任务需要深知搜索时才是前置条件,不作为基础写作的阻断项。
|
|
56
|
+
# 不涉及搜索的简单通知、改写润色、只生成 Word 等任务可直接使用。
|
|
57
|
+
search_blocking_issues = []
|
|
58
|
+
if not config_status["api_key_configured"]:
|
|
59
|
+
search_blocking_issues.append("api_key_missing")
|
|
60
|
+
return {
|
|
61
|
+
"python": platform.python_version(),
|
|
62
|
+
"python3_available": python3_available,
|
|
63
|
+
"python_docx": python_docx_available,
|
|
64
|
+
"requests": requests_available,
|
|
65
|
+
"api_key_configured": config_status["api_key_configured"],
|
|
66
|
+
"api_key_env": API_KEY_ENV,
|
|
67
|
+
"api_key_source": config_status["api_key_source"],
|
|
68
|
+
"api_key_hint": config_status["api_key_hint"],
|
|
69
|
+
"config_issue": None if config_status["api_key_configured"] else "api_key_missing",
|
|
70
|
+
"search_ready": config_status["api_key_configured"] and requests_available,
|
|
71
|
+
"search_blocking_issues": search_blocking_issues,
|
|
72
|
+
"search_note": None if config_status["api_key_configured"] else f"环境变量 {API_KEY_ENV} 中未配置有效 API Key;仅当任务需要深知搜索(查政策依据、数据支撑、案例参考)时才需要配置,不涉及搜索的写作任务可直接使用。",
|
|
73
|
+
"font_note": "Word 文档会写入公文常用字体名称;打开端如缺少对应字体,Word/WPS 可能自动替换,需以本机打开后的显示为准。",
|
|
74
|
+
"blocking_issues": blocking_issues,
|
|
75
|
+
"ready": not blocking_issues,
|
|
76
|
+
"search_ready_note": None if config_status["api_key_configured"] else "仅需要搜索的任务需先完成 MaaS 注册获取 API Key 并写入环境变量;无需搜索的任务可先直接写作。",
|
|
77
|
+
"dependency_install_prompt_needed": bool(dependency_issues) and not state.get("dependency_install_declined"),
|
|
78
|
+
"install_hint": "经用户同意后,可执行 python3 -m pip install python-docx requests" if dependency_issues else None,
|
|
79
|
+
"maas_platform_url": "https://platform.dknowc.cn/",
|
|
80
|
+
"environment_state": {
|
|
81
|
+
"dependency_install_declined": bool(state.get("dependency_install_declined")),
|
|
82
|
+
},
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _module_available(module_name):
|
|
87
|
+
try:
|
|
88
|
+
__import__(module_name)
|
|
89
|
+
return True
|
|
90
|
+
except ImportError:
|
|
91
|
+
return False
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _in_dsh() -> bool:
|
|
95
|
+
"""dsh 环境标志:dsh 的 bash 工具会注入 DSH_SHELL=1。
|
|
96
|
+
|
|
97
|
+
dsh 场景下,脚本子进程无法隐式继承 DKNOWC_API_KEY(dsh 安全机制会清理
|
|
98
|
+
名字含 KEY 的环境变量),但 dsh 插件会通过 shell-env 显式通道把该 Key
|
|
99
|
+
注入为 DSH_DKNOWC_API_KEY。因此检查 DSH_DKNOWC_API_KEY 即可真实判断
|
|
100
|
+
"dsh 主进程环境变量是否已配置 DKNOWC_API_KEY"。搜索子能力走 MCP 转接,
|
|
101
|
+
无 Key 时仅暂停搜索,不阻断纯写作。
|
|
102
|
+
"""
|
|
103
|
+
return os.environ.get("DSH_SHELL") == "1"
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def check_api_key_config():
|
|
107
|
+
if _in_dsh():
|
|
108
|
+
# dsh 场景:读取插件注入的 DSH_DKNOWC_API_KEY(来源为 dsh 主进程的 DKNOWC_API_KEY)
|
|
109
|
+
api_key = os.environ.get("DSH_DKNOWC_API_KEY", "").strip()
|
|
110
|
+
if _valid_api_key(api_key):
|
|
111
|
+
return {
|
|
112
|
+
"api_key_configured": True,
|
|
113
|
+
"api_key_source": "environment",
|
|
114
|
+
"api_key_hint": None,
|
|
115
|
+
}
|
|
116
|
+
return {
|
|
117
|
+
"api_key_configured": False,
|
|
118
|
+
"api_key_source": None,
|
|
119
|
+
"api_key_hint": f"未检测到可用的 {API_KEY_ENV}(dsh 主进程环境变量未配置或为空)。需要先将有效的 API Key 配置到启动 dsh 的环境变量 {API_KEY_ENV}(如 ~/.zshrc),再重启 dsh 或新建会话。仅搜索任务受影响,不涉及搜索的写作任务可继续。",
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
api_key = os.environ.get(API_KEY_ENV, "").strip()
|
|
123
|
+
if not _valid_api_key(api_key):
|
|
124
|
+
return {
|
|
125
|
+
"api_key_configured": False,
|
|
126
|
+
"api_key_source": None,
|
|
127
|
+
"api_key_hint": f"缺少环境变量 {API_KEY_ENV},请先通过 MaaS 初始化获取 API Key,并由 Agent 或平台密钥配置写入该环境变量。",
|
|
128
|
+
}
|
|
129
|
+
return {
|
|
130
|
+
"api_key_configured": True,
|
|
131
|
+
"api_key_source": "environment",
|
|
132
|
+
"api_key_hint": None,
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _valid_api_key(value):
|
|
137
|
+
return bool(value) and value not in {"your_api_key_here", "你的深知搜索 API Key"}
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def main():
|
|
141
|
+
parser = argparse.ArgumentParser(description="深知写作助手初始化与环境检查")
|
|
142
|
+
parser.add_argument("--organization", help="常用发文机关;不填写则使用 XX单位")
|
|
143
|
+
parser.add_argument("--doc-prefix", help="常用发文字号前缀;不填写则使用 XX")
|
|
144
|
+
parser.add_argument("--region", help="常用搜索地域;不填写则按任务询问")
|
|
145
|
+
parser.add_argument("--print-unit", help="常用印发单位")
|
|
146
|
+
parser.add_argument("--save", action="store_true", help="经用户授权后,将所填设置仅保存到本机")
|
|
147
|
+
parser.add_argument("--decline-dependency-install", action="store_true", help="记录用户已拒绝依赖安装提示,后续不再反复询问")
|
|
148
|
+
parser.add_argument("--reset-environment-prompts", action="store_true", help="清除依赖安装提示的拒绝记录")
|
|
149
|
+
args = parser.parse_args()
|
|
150
|
+
|
|
151
|
+
state = load_environment_state()
|
|
152
|
+
if args.reset_environment_prompts:
|
|
153
|
+
state.pop("dependency_install_declined", None)
|
|
154
|
+
if args.decline_dependency_install:
|
|
155
|
+
state["dependency_install_declined"] = True
|
|
156
|
+
if args.reset_environment_prompts or args.decline_dependency_install:
|
|
157
|
+
save_environment_state(state)
|
|
158
|
+
|
|
159
|
+
if args.save:
|
|
160
|
+
profile = {
|
|
161
|
+
"organization": args.organization or "",
|
|
162
|
+
"doc_prefix": args.doc_prefix or "",
|
|
163
|
+
"region": args.region or "",
|
|
164
|
+
"print_unit": args.print_unit or "",
|
|
165
|
+
}
|
|
166
|
+
PROFILE_PATH.parent.mkdir(parents=True, exist_ok=True)
|
|
167
|
+
with PROFILE_PATH.open("w", encoding="utf-8") as profile_file:
|
|
168
|
+
json.dump(profile, profile_file, ensure_ascii=False, indent=2)
|
|
169
|
+
|
|
170
|
+
result = check_environment()
|
|
171
|
+
result["profile_saved"] = args.save
|
|
172
|
+
result["profile_path"] = "config/user_profile.json" if args.save else None
|
|
173
|
+
result["environment_state_path"] = "config/environment_state.json"
|
|
174
|
+
print(json.dumps(result, ensure_ascii=False, indent=2))
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
if __name__ == "__main__":
|
|
178
|
+
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())
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""
|
|
3
|
+
合并多次搜索结果
|
|
4
|
+
功能:去重、重新编号、生成统计信息
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import argparse
|
|
8
|
+
import json
|
|
9
|
+
import sys
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import List, Dict
|
|
12
|
+
|
|
13
|
+
SKILL_ROOT = Path(__file__).resolve().parent.parent
|
|
14
|
+
# 工作区根:dsh 场景通过环境变量 DKNWOC_WS_ROOT 指向会话工作区,未设置时回退到 skill 目录(SkillHub 兼容)
|
|
15
|
+
import os as _os
|
|
16
|
+
WS_ROOT = Path(_os.environ.get("DKNWOC_WS_ROOT") or _os.getcwd()).resolve()
|
|
17
|
+
|
|
18
|
+
OFFICIAL_DOCS_DIR = WS_ROOT / "official-docs"
|
|
19
|
+
SEARCH_RESULTS_DIR = OFFICIAL_DOCS_DIR / "search-results"
|
|
20
|
+
ALLOWED_INPUT_DIRS = (
|
|
21
|
+
OFFICIAL_DOCS_DIR / "input",
|
|
22
|
+
OFFICIAL_DOCS_DIR / "output",
|
|
23
|
+
SEARCH_RESULTS_DIR,
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def is_relative_to(path: Path, parent: Path) -> bool:
|
|
28
|
+
"""兼容旧 Python 版本的 Path.is_relative_to。"""
|
|
29
|
+
try:
|
|
30
|
+
path.relative_to(parent)
|
|
31
|
+
return True
|
|
32
|
+
except ValueError:
|
|
33
|
+
return False
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def resolve_input_json(file_path: str) -> Path:
|
|
37
|
+
"""只允许读取 skill 工作目录内的 JSON 搜索结果。"""
|
|
38
|
+
raw_path = Path(file_path).expanduser()
|
|
39
|
+
if raw_path.is_absolute():
|
|
40
|
+
resolved = raw_path.resolve()
|
|
41
|
+
elif raw_path.parent == Path("."):
|
|
42
|
+
resolved = (SEARCH_RESULTS_DIR / raw_path.name).resolve()
|
|
43
|
+
else:
|
|
44
|
+
resolved = (WS_ROOT / raw_path).resolve()
|
|
45
|
+
|
|
46
|
+
if resolved.suffix.lower() != ".json":
|
|
47
|
+
raise ValueError(f"只允许读取 JSON 文件: {file_path}")
|
|
48
|
+
if not any(is_relative_to(resolved, allowed.resolve()) for allowed in ALLOWED_INPUT_DIRS):
|
|
49
|
+
raise ValueError(f"输入文件必须位于 skill 工作目录内: {file_path}")
|
|
50
|
+
return resolved
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def resolve_output_json(output_path: str) -> Path:
|
|
54
|
+
"""只允许将合并结果写入搜索结果目录。"""
|
|
55
|
+
raw_path = Path(output_path).expanduser()
|
|
56
|
+
if raw_path.is_absolute():
|
|
57
|
+
resolved = raw_path.resolve()
|
|
58
|
+
elif raw_path.parent == Path("."):
|
|
59
|
+
resolved = (SEARCH_RESULTS_DIR / raw_path.name).resolve()
|
|
60
|
+
else:
|
|
61
|
+
resolved = (WS_ROOT / raw_path).resolve()
|
|
62
|
+
|
|
63
|
+
if resolved.suffix.lower() != ".json":
|
|
64
|
+
resolved = resolved.with_suffix(".json")
|
|
65
|
+
if not is_relative_to(resolved, SEARCH_RESULTS_DIR.resolve()):
|
|
66
|
+
raise ValueError(f"输出文件必须位于搜索结果目录内: {SEARCH_RESULTS_DIR}")
|
|
67
|
+
return resolved
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def merge_results(result_files: List[str]) -> Dict:
|
|
71
|
+
"""
|
|
72
|
+
合并多个搜索结果文件
|
|
73
|
+
|
|
74
|
+
Args:
|
|
75
|
+
result_files: 搜索结果文件路径列表
|
|
76
|
+
|
|
77
|
+
Returns:
|
|
78
|
+
合并后的结果字典
|
|
79
|
+
"""
|
|
80
|
+
all_articles = []
|
|
81
|
+
seen_titles = set()
|
|
82
|
+
duplicates_count = 0
|
|
83
|
+
regions_searched = []
|
|
84
|
+
searches = []
|
|
85
|
+
knowledge_bases = []
|
|
86
|
+
|
|
87
|
+
for file_path in result_files:
|
|
88
|
+
try:
|
|
89
|
+
safe_file_path = resolve_input_json(file_path)
|
|
90
|
+
with safe_file_path.open('r', encoding='utf-8') as f:
|
|
91
|
+
data = json.load(f)
|
|
92
|
+
except Exception as e:
|
|
93
|
+
print(f"警告: 无法读取文件 {file_path}: {e}", file=sys.stderr)
|
|
94
|
+
continue
|
|
95
|
+
|
|
96
|
+
# 检查是否是清洗后的格式
|
|
97
|
+
if data.get("cleaned") and "articles" in data:
|
|
98
|
+
articles = data["articles"]
|
|
99
|
+
elif "content" in data and "data" in data.get("content", {}):
|
|
100
|
+
articles = data["content"]["data"].get("检索文章", [])
|
|
101
|
+
else:
|
|
102
|
+
print(f"警告: 文件 {file_path} 格式不识别", file=sys.stderr)
|
|
103
|
+
continue
|
|
104
|
+
|
|
105
|
+
search_meta = data.get("search_meta", {})
|
|
106
|
+
region = search_meta.get("area") or infer_region_from_filename(str(safe_file_path))
|
|
107
|
+
regions_searched.append(region)
|
|
108
|
+
searches.append({
|
|
109
|
+
"file": str(safe_file_path),
|
|
110
|
+
"query": search_meta.get("query", ""),
|
|
111
|
+
"purpose": search_meta.get("purpose", ""),
|
|
112
|
+
"area": region,
|
|
113
|
+
"time": search_meta.get("time", ""),
|
|
114
|
+
"policy": search_meta.get("policy", False),
|
|
115
|
+
"full": search_meta.get("full", False),
|
|
116
|
+
"segmentCount": search_meta.get("segmentCount"),
|
|
117
|
+
"knowledgeBase": data.get("knowledgeBase", ""),
|
|
118
|
+
})
|
|
119
|
+
if data.get("knowledgeBase"):
|
|
120
|
+
knowledge_bases.append({
|
|
121
|
+
"file": str(safe_file_path),
|
|
122
|
+
"query": search_meta.get("query", ""),
|
|
123
|
+
"purpose": search_meta.get("purpose", ""),
|
|
124
|
+
"area": region,
|
|
125
|
+
"knowledgeBase": data.get("knowledgeBase", ""),
|
|
126
|
+
})
|
|
127
|
+
|
|
128
|
+
# 去重合并
|
|
129
|
+
for article in articles:
|
|
130
|
+
title = article.get("文章标题", "")
|
|
131
|
+
if title in seen_titles:
|
|
132
|
+
duplicates_count += 1
|
|
133
|
+
continue
|
|
134
|
+
|
|
135
|
+
seen_titles.add(title)
|
|
136
|
+
article.setdefault("搜索地域", region)
|
|
137
|
+
if search_meta.get("query"):
|
|
138
|
+
article.setdefault("搜索词", search_meta.get("query"))
|
|
139
|
+
if search_meta.get("purpose"):
|
|
140
|
+
article.setdefault("搜索目的", search_meta.get("purpose"))
|
|
141
|
+
if article.get("源网址") and not article.get("原文链接"):
|
|
142
|
+
article["原文链接"] = article["源网址"]
|
|
143
|
+
if article.get("sourceUrl") and not article.get("原文链接"):
|
|
144
|
+
article["原文链接"] = article["sourceUrl"]
|
|
145
|
+
if article.get("policyUrl") and not article.get("知识专库原文"):
|
|
146
|
+
article["知识专库原文"] = article["policyUrl"]
|
|
147
|
+
all_articles.append(article)
|
|
148
|
+
|
|
149
|
+
# 重新编号段落
|
|
150
|
+
global_id = 1
|
|
151
|
+
total_paragraphs = 0
|
|
152
|
+
for article in all_articles:
|
|
153
|
+
paragraphs = article.get("段落", [])
|
|
154
|
+
for p in paragraphs:
|
|
155
|
+
p["id"] = global_id
|
|
156
|
+
global_id += 1
|
|
157
|
+
total_paragraphs += 1
|
|
158
|
+
|
|
159
|
+
# 返回合并结果
|
|
160
|
+
return {
|
|
161
|
+
"cleaned": True,
|
|
162
|
+
"articles": all_articles,
|
|
163
|
+
"search_summary": {
|
|
164
|
+
"total_searches": len(result_files),
|
|
165
|
+
"regions": list(set(regions_searched)),
|
|
166
|
+
"total_articles": len(all_articles),
|
|
167
|
+
"total_paragraphs": total_paragraphs,
|
|
168
|
+
"duplicates_removed": duplicates_count,
|
|
169
|
+
"searches": searches,
|
|
170
|
+
"knowledge_bases": knowledge_bases
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def infer_region_from_filename(file_path: str) -> str:
|
|
176
|
+
"""兼容旧结果文件:从文件名推断地域。新结果优先使用 search_meta.area。"""
|
|
177
|
+
lower_path = file_path.lower()
|
|
178
|
+
if "gd" in lower_path or "guangdong" in lower_path:
|
|
179
|
+
return "广东省"
|
|
180
|
+
if "bj" in lower_path or "beijing" in lower_path:
|
|
181
|
+
return "北京市"
|
|
182
|
+
if "sh" in lower_path or "shanghai" in lower_path:
|
|
183
|
+
return "上海市"
|
|
184
|
+
return "未知地区"
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def main():
|
|
188
|
+
parser = argparse.ArgumentParser(
|
|
189
|
+
description="合并多次搜索结果(去重+重新编号)",
|
|
190
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
191
|
+
epilog="""
|
|
192
|
+
示例:
|
|
193
|
+
%(prog)s result_gd.json result_bj.json result_sh.json
|
|
194
|
+
%(prog)s result_gd.json result_bj.json --output merged.json
|
|
195
|
+
"""
|
|
196
|
+
)
|
|
197
|
+
parser.add_argument("files", nargs="+", help="搜索结果文件路径")
|
|
198
|
+
parser.add_argument("--output", "-o", help="输出文件路径(可选,默认输出到标准输出)")
|
|
199
|
+
|
|
200
|
+
args = parser.parse_args()
|
|
201
|
+
|
|
202
|
+
# 合并结果
|
|
203
|
+
merged = merge_results(args.files)
|
|
204
|
+
|
|
205
|
+
# 输出
|
|
206
|
+
output_json = json.dumps(merged, ensure_ascii=False, indent=2)
|
|
207
|
+
|
|
208
|
+
if args.output:
|
|
209
|
+
output_path = resolve_output_json(args.output)
|
|
210
|
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
|
211
|
+
with output_path.open('w', encoding='utf-8') as f:
|
|
212
|
+
f.write(output_json)
|
|
213
|
+
print(f"✅ 已合并 {merged['search_summary']['total_searches']} 次搜索结果")
|
|
214
|
+
print(f" - 文章数: {merged['search_summary']['total_articles']}")
|
|
215
|
+
print(f" - 段落数: {merged['search_summary']['total_paragraphs']}")
|
|
216
|
+
print(f" - 去重: {merged['search_summary']['duplicates_removed']} 篇")
|
|
217
|
+
print(f" - 输出: {output_path}")
|
|
218
|
+
else:
|
|
219
|
+
print(output_json)
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
if __name__ == "__main__":
|
|
223
|
+
main()
|