argo-search 2.14.1 → 2.16.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/AGENTS.md +8 -6
- package/README.es.md +57 -813
- package/README.ja.md +56 -814
- package/README.ko.md +56 -812
- package/README.md +160 -754
- package/README.zh.md +152 -872
- package/SKILL.md +22 -23
- package/assets/readme/counts.json +1 -1
- package/assets/readme/hero.svg +23 -23
- package/backends/concept_vectors.bin +0 -0
- package/backends/domain_profiles.json +149 -6
- package/backends/engine_concept_vectors.json +1525 -1525
- package/backends/engine_registry.yaml +139 -30
- package/backends/quota_profiles.json +83 -3
- package/bin/argo +33 -17
- package/config.yaml +189 -33
- package/docs/ADDING_NEW_ENGINE.md +10 -0
- package/docs/ARGO_INTRO.md +1 -1
- package/docs/CHANGELOG.md +38 -0
- package/docs/ENGINE_CATALOG.md +102 -89
- package/docs/MCP_SETUP.md +10 -1
- package/docs/RELEASE_NOTES_v2.14.1.md +4 -4
- package/docs/RELEASE_NOTES_v2.15.0.md +50 -0
- package/docs/RELEASE_NOTES_v2.16.0.md +58 -0
- package/docs/RELEASING.md +1 -1
- package/engines/specs/ai_labs.yaml +89 -0
- package/engines/specs/archive_org.yaml +1 -1
- package/engines/specs/bilibili_hot.yaml +11 -1
- package/engines/specs/brave.yaml +3 -3
- package/engines/specs/carbon_intensity.yaml +1 -1
- package/engines/specs/cisa_alerts.yaml +40 -0
- package/engines/specs/cn_ai_news.yaml +10 -8
- package/engines/specs/crates.yaml +1 -1
- package/engines/specs/crossref.yaml +4 -2
- package/engines/specs/crt_sh.yaml +1 -1
- package/engines/specs/dblp.yaml +1 -1
- package/engines/specs/devto.yaml +1 -1
- package/engines/specs/digup.yaml +11 -6
- package/engines/specs/docker_hub.yaml +1 -1
- package/engines/specs/douyin_hot.yaml +11 -1
- package/engines/specs/dw_news.yaml +4 -2
- package/engines/specs/eng_blogs.yaml +63 -0
- package/engines/specs/europeana.yaml +3 -4
- package/engines/specs/europepmc.yaml +1 -1
- package/engines/specs/felo.yaml +3 -3
- package/engines/specs/firecrawl.yaml +3 -0
- package/engines/specs/fourget.yaml +5 -2
- package/engines/specs/france24.yaml +6 -4
- package/engines/specs/fxtwitter.yaml +30 -7
- package/engines/specs/gbfs_nyc.yaml +1 -1
- package/engines/specs/gleif.yaml +1 -1
- package/engines/specs/gov_regulations.yaml +1 -1
- package/engines/specs/grepapp_mcp.yaml +62 -0
- package/engines/specs/guardian_rss.yaml +6 -4
- package/engines/specs/hf_datasets.yaml +1 -1
- package/engines/specs/huggingface.yaml +1 -1
- package/engines/specs/itotii.yaml +13 -1
- package/engines/specs/keenable.yaml +7 -1
- package/engines/specs/linux_do.yaml +63 -0
- package/engines/specs/lobsters.yaml +41 -0
- package/engines/specs/local_crossref.yaml +3 -1
- package/engines/specs/local_github.yaml +1 -1
- package/engines/specs/local_npm.yaml +6 -0
- package/engines/specs/local_openstreetmap.yaml +1 -1
- package/engines/specs/local_seek.yaml +6 -0
- package/engines/specs/maven.yaml +1 -1
- package/engines/specs/mdn.yaml +1 -1
- package/engines/specs/musicbrainz.yaml +1 -1
- package/engines/specs/nasa_images.yaml +1 -1
- package/engines/specs/nhtsa_vpic.yaml +6 -3
- package/engines/specs/npm.yaml +1 -1
- package/engines/specs/nuget.yaml +1 -1
- package/engines/specs/nvd.yaml +1 -1
- package/engines/specs/open_meteo.yaml +1 -1
- package/engines/specs/openalex.yaml +4 -2
- package/engines/specs/openreview.yaml +1 -1
- package/engines/specs/polymarket.yaml +1 -1
- package/engines/specs/redskill.yaml +2 -0
- package/engines/specs/searxng.yaml +4 -2
- package/engines/specs/sec_edgar.yaml +9 -4
- package/engines/specs/steam.yaml +1 -1
- package/engines/specs/tinyfish.yaml +2 -0
- package/engines/specs/tinyfish_news.yaml +2 -0
- package/engines/specs/tinyfish_paper.yaml +2 -0
- package/engines/specs/toutiao_hot.yaml +11 -1
- package/engines/specs/train.yaml +3 -0
- package/engines/specs/twitter.yaml +4 -0
- package/engines/specs/unpaywall.yaml +6 -0
- package/engines/specs/vam.yaml +17 -3
- package/engines/specs/weibo_hot.yaml +11 -1
- package/engines/specs/wikidata.yaml +1 -1
- package/engines/specs/wikipedia.yaml +1 -1
- package/engines/specs/wolframalpha.yaml +3 -3
- package/engines/specs/xiaohongshu.yaml +2 -0
- package/engines/specs/zhihu.yaml +3 -18
- package/engines/specs/zhihu_hot_app.yaml +1 -1
- package/engines/specs/zhihu_kb.yaml +18 -0
- package/engines/specs/zhihu_questions.yaml +19 -0
- package/package.json +4 -2
- package/packages/dsh-plugin/README.md +9 -14
- package/packages/dsh-plugin/dsh/client.js +481 -1037
- package/packages/dsh-plugin/dsh/diagnostics.js +71 -20
- package/packages/dsh-plugin/dsh/index.js +6 -0
- package/packages/dsh-plugin/dsh/runner.js +3 -1
- package/packages/dsh-plugin/dsh/workbench-client.js +796 -0
- package/packages/dsh-plugin/dsh/workbench-md.js +386 -0
- package/packages/dsh-plugin/dsh/workbench-suggestions.js +148 -0
- package/packages/dsh-plugin/dsh/workbench.js +966 -0
- package/packages/dsh-plugin/icon.svg +23 -0
- package/packages/dsh-plugin/package.json +10 -3
- package/packages/dsh-plugin/scripts/sync-local.mjs +87 -0
- package/packages/dsh-plugin/scripts/sync-local.sh +13 -1
- package/packages/dsh-plugin/test/diagnostics.test.js +38 -1
- package/packages/dsh-plugin/test/size-gate.test.js +2 -9
- package/packages/dsh-plugin/test/workbench.test.js +92 -0
- package/scripts/adaptive.py +7 -1
- package/scripts/archive_run.py +112 -53
- package/scripts/argo_paths.py +42 -5
- package/scripts/badcase_ledger.py +117 -9
- package/scripts/build_concept_table.py +112 -55
- package/scripts/cache.py +6 -2
- package/scripts/caliber_isolation.py +60 -23
- package/scripts/circuit_breaker.py +72 -11
- package/scripts/cli_io.py +20 -2
- package/scripts/config_cache.py +44 -1
- package/scripts/daemon.py +151 -51
- package/scripts/dormant_ledger.py +23 -9
- package/scripts/engine_dispatch.py +8 -5
- package/scripts/engine_env.py +191 -1
- package/scripts/engine_families.py +50 -7
- package/scripts/engine_states.py +3 -50
- package/scripts/engine_validate.py +13 -45
- package/scripts/engines.py +15 -31
- package/scripts/engines_base.py +66 -61
- package/scripts/engines_builders.py +0 -15
- package/scripts/engines_builders_archive.py +4 -3
- package/scripts/engines_builders_batch10.py +346 -100
- package/scripts/engines_builders_batch11.py +4 -76
- package/scripts/engines_builders_batch13.py +4 -3
- package/scripts/engines_builders_batch14.py +2 -1
- package/scripts/engines_builders_batch15.py +2 -1
- package/scripts/engines_builders_batch9.py +16 -25
- package/scripts/engines_builders_cn.py +7 -201
- package/scripts/engines_builders_data.py +12 -11
- package/scripts/engines_builders_data_macro.py +5 -4
- package/scripts/engines_builders_dsh.py +2 -1
- package/scripts/engines_builders_feeds.py +76 -11
- package/scripts/engines_builders_finance.py +2 -1
- package/scripts/engines_builders_intl.py +18 -117
- package/scripts/engines_builders_media.py +59 -12
- package/scripts/engines_builders_pixiv.py +2 -16
- package/scripts/engines_builders_science.py +8 -7
- package/scripts/engines_builders_search.py +7 -14
- package/scripts/engines_builders_skill.py +2 -1
- package/scripts/engines_builders_tech.py +8 -17
- package/scripts/engines_builders_weather.py +241 -0
- package/scripts/engines_fields.py +91 -0
- package/scripts/engines_http.py +184 -0
- package/scripts/engines_mcp.py +405 -0
- package/scripts/engines_parsers.py +13 -369
- package/scripts/engines_schema_drift.py +260 -0
- package/scripts/evidence.py +13 -0
- package/scripts/evidence_loop.py +19 -4
- package/scripts/extend_route_labels.py +6 -0
- package/scripts/fetch_jina.py +98 -0
- package/scripts/fetch_jsrun.py +15 -11
- package/scripts/fetch_v3.py +79 -120
- package/scripts/fulltext_store.py +42 -1
- package/scripts/fxtwitter_api.py +8 -7
- package/scripts/gen_engine_catalog.py +2 -2
- package/scripts/general_pool.py +15 -4
- package/scripts/health_check.py +1 -1
- package/scripts/image_vision/vision_probe +0 -0
- package/scripts/install.sh +2 -0
- package/scripts/link_source.py +65 -24
- package/scripts/local_seek_adapter.py +57 -17
- package/scripts/matrix_search_eval.py +8 -10
- package/scripts/mcp_handlers.py +53 -31
- package/scripts/mcp_handlers_surface.py +6 -18
- package/scripts/mcp_transport.py +10 -5
- package/scripts/min_version_scan.py +7 -3
- package/scripts/network_aware.py +7 -13
- package/scripts/numeric_verify.py +3 -2
- package/scripts/output_transparency.py +3 -0
- package/scripts/pre-commit +45 -43
- package/scripts/query_understanding.py +30 -6
- package/scripts/quota.py +36 -30
- package/scripts/rank_signals.py +9 -0
- package/scripts/recompute.py +15 -5
- package/scripts/recovery.py +38 -29
- package/scripts/recovery_runner.py +29 -10
- package/scripts/redskill/redskill_engine.py +2 -1
- package/scripts/release.py +14 -26
- package/scripts/release_check.py +5 -25
- package/scripts/replay_eval.py +2 -2
- package/scripts/research_cli.py +40 -0
- package/scripts/research_notes.py +368 -0
- package/scripts/route.py +40 -70
- package/scripts/route_audit.py +259 -0
- package/scripts/route_combo.py +21 -6
- package/scripts/route_domains.py +150 -23
- package/scripts/route_lang.py +20 -7
- package/scripts/route_log.py +26 -9
- package/scripts/route_policy.py +85 -6
- package/scripts/route_telemetry_export.py +199 -0
- package/scripts/rrf_classic.py +5 -22
- package/scripts/search.py +2 -1
- package/scripts/search_attribution.py +53 -10
- package/scripts/search_entry.py +32 -1
- package/scripts/search_output.py +23 -11
- package/scripts/search_pipeline.py +15 -3
- package/scripts/search_rank.py +21 -11
- package/scripts/semantic_evidence.py +394 -178
- package/scripts/serp_guard.py +13 -1
- package/scripts/settings_page.py +4 -3
- package/scripts/single_flight.py +1 -1
- package/scripts/social_engines/hackernews_engine.py +2 -1
- package/scripts/social_engines/reddit_engine.py +2 -1
- package/scripts/social_engines/xiaohongshu_engine.py +2 -1
- package/scripts/social_engines/zhihu_engine.py +252 -43
- package/scripts/sogou_weixin_browser.py +5 -6
- package/scripts/source_audit.py +44 -9
- package/scripts/source_ledger.py +2 -15
- package/scripts/source_selection.py +45 -20
- package/scripts/straggler_policy.py +1 -2
- package/scripts/sync_backends.py +17 -0
- package/scripts/tfidf_router.py +23 -11
- package/scripts/time_utils.py +54 -1
- package/scripts/train.py +68 -2
- package/scripts/usage_log.py +50 -10
- package/scripts/watch.py +3 -3
- package/scripts/zhihu_quota.py +2 -1
- package/sub-skills/argo-wide-research/SKILL.md +70 -0
- package/sub-skills/ego-search/{SKILL.md → README.md} +15 -47
- package/sub-skills/ego-search/scripts/ego_search.py +13 -4
- package/sub-skills/js-run/{SKILL.md → README.md} +3 -20
- package/sub-skills/local-search/{SKILL.md → README.md} +3 -8
- package/sub-skills/local-search/engine_registry.py +32 -7
- package/sub-skills/local-seek/SKILL.md +20 -22
- package/sub-skills/local-seek/scripts/seek_fts.py +58 -3
- package/scripts/caliber_dedupe.py +0 -66
- package/scripts/engines_builders_batch16.py +0 -13
- package/scripts/health_probe.py +0 -253
- package/scripts/social_engines/twitter_engine.py +0 -514
- package/scripts/sync_installs.py +0 -29
|
@@ -0,0 +1,405 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""engines_mcp.py — MCP 通用连接器适配器(spec type: mcp)。
|
|
3
|
+
|
|
4
|
+
把任意 MCP server(stdio 子进程或 Streamable HTTP)接入为 argo 搜索引擎。
|
|
5
|
+
分层契约:
|
|
6
|
+
|
|
7
|
+
- 协议层通用:initialize 握手 → notifications/initialized → tools/call。
|
|
8
|
+
响应可能是 application/json 或 text/event-stream(实测 mcp.grep.app 返回
|
|
9
|
+
SSE),Mcp-Session-Id 响应头存在则全程回传。
|
|
10
|
+
- 内容层声明式:structuredContent / JSON 文本走标准 output_map(与 http 引擎
|
|
11
|
+
同一套字段映射、url_kind、引擎出处打标);纯文本工具声明 mode: text,用
|
|
12
|
+
text_split 分块正则 + item_*_regex 逐块抽字段。两类都不写每源代码。
|
|
13
|
+
|
|
14
|
+
spec 契约(engines/specs/<engine_id>.yaml)::
|
|
15
|
+
|
|
16
|
+
engine_id: grepapp_mcp
|
|
17
|
+
type: mcp
|
|
18
|
+
transport: http # http(Streamable HTTP)| stdio(子进程)
|
|
19
|
+
url: https://mcp.grep.app # http 传输端点
|
|
20
|
+
# command: [uvx, -y, some-server] # stdio 传输命令——必须是列表,禁 shell
|
|
21
|
+
tool: searchGitHub # 工具单一 allowlist,只可调用这一个
|
|
22
|
+
arguments: # 参数模板:{query}/{n}/{depth} 与 {ENV}
|
|
23
|
+
query: "{query}"
|
|
24
|
+
perPage: "{n}"
|
|
25
|
+
required_env: [ARGO_GREP_APP_API_KEY] # env 白名单真源;未配置的头不发送
|
|
26
|
+
headers: {} # http 可选;{ENV} 走 required_env 白名单
|
|
27
|
+
timeout: 20
|
|
28
|
+
output_map:
|
|
29
|
+
mode: json # 默认 json;纯文本工具显式声明 text
|
|
30
|
+
text_split: '\\n(?=Repository: )'
|
|
31
|
+
item_title_regex: 'Path: (.+)'
|
|
32
|
+
item_url_regex: 'URL: (\\S+)'
|
|
33
|
+
item_summary_regex: '(?s)--- Snippet 1 \\(Line \\d+\\) ---\\n(.*)'
|
|
34
|
+
explicit_only: true # 连接器默认不占自动路由预算
|
|
35
|
+
synthesized: true # 合成/新接入标记,人工确认后摘除
|
|
36
|
+
|
|
37
|
+
安全边界:stdio 用列表参数 + build_child_env 白名单环境(禁 shell);
|
|
38
|
+
不 eval 远端 payload;密钥不落日志;isError 的结果不产出条目(fail-visible)。
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
from __future__ import annotations
|
|
42
|
+
|
|
43
|
+
import json
|
|
44
|
+
import re
|
|
45
|
+
import select
|
|
46
|
+
import subprocess
|
|
47
|
+
import time
|
|
48
|
+
import urllib.error
|
|
49
|
+
import urllib.request
|
|
50
|
+
from typing import Any
|
|
51
|
+
|
|
52
|
+
from engine_env import allowed_placeholders_for, build_child_env
|
|
53
|
+
from engines_base import (
|
|
54
|
+
_apply_url_kind,
|
|
55
|
+
_ensure_engine_source,
|
|
56
|
+
_get_logger,
|
|
57
|
+
_header_meaningful,
|
|
58
|
+
_parse_http_payload,
|
|
59
|
+
_resolve,
|
|
60
|
+
http_open,
|
|
61
|
+
safe_search,
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
_PROTOCOL_VERSION = "2025-06-18"
|
|
65
|
+
_TRANSPORTS = ("http", "stdio")
|
|
66
|
+
_JSON_RE = re.compile(r"^data:\s*(.+?)\s*$")
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
# ── JSON-RPC 响应解析(application/json 或 SSE data: 帧)─────────────────────
|
|
70
|
+
|
|
71
|
+
def _parse_jsonrpc_body(text: str) -> dict[str, Any] | None:
|
|
72
|
+
"""整段 JSON 优先,SSE 逐 data: 行兜底,返回首个完整 JSON-RPC 对象。"""
|
|
73
|
+
try:
|
|
74
|
+
obj = json.loads(text)
|
|
75
|
+
if isinstance(obj, dict):
|
|
76
|
+
return obj
|
|
77
|
+
except (json.JSONDecodeError, ValueError):
|
|
78
|
+
pass
|
|
79
|
+
for line in text.splitlines():
|
|
80
|
+
line = line.strip()
|
|
81
|
+
if not line.startswith("data:"):
|
|
82
|
+
continue
|
|
83
|
+
payload = line[5:].strip()
|
|
84
|
+
if not payload:
|
|
85
|
+
continue
|
|
86
|
+
try:
|
|
87
|
+
obj = json.loads(payload)
|
|
88
|
+
except (json.JSONDecodeError, ValueError):
|
|
89
|
+
continue
|
|
90
|
+
if isinstance(obj, dict):
|
|
91
|
+
return obj
|
|
92
|
+
return None
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
# ── Streamable HTTP 通道 ─────────────────────────────────────────────────────
|
|
96
|
+
|
|
97
|
+
def _client_info() -> dict[str, str]:
|
|
98
|
+
"""握手用的 clientInfo:版本读单源,不再手抄字面量。
|
|
99
|
+
|
|
100
|
+
此前这里写死 "2.14.1",v2.15.0 升版时没人改——而 release_check 的八处
|
|
101
|
+
机器声明扫描不含本文件,升版盲区就是这么来的。真源与 mcp_transport
|
|
102
|
+
同口径:argo_search.__version__(release_check 已把它列为声明之一)。
|
|
103
|
+
"""
|
|
104
|
+
try:
|
|
105
|
+
import argo_search
|
|
106
|
+
version = str(argo_search.__version__)
|
|
107
|
+
except Exception:
|
|
108
|
+
version = "unknown"
|
|
109
|
+
return {"name": "argo", "version": version}
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
class _HttpChannel:
|
|
113
|
+
"""Streamable HTTP JSON-RPC 通道(握手/回执/工具调用按 MCP 2025-06-18)。
|
|
114
|
+
|
|
115
|
+
HTTP 出口统一走 engines_base.http_open(egress 门禁 + 代理解析 + 失败
|
|
116
|
+
归因,issue #13),与 http 引擎同一出口;不直连 urlopen。
|
|
117
|
+
"""
|
|
118
|
+
|
|
119
|
+
def __init__(self, url: str, headers: dict[str, str], timeout: float,
|
|
120
|
+
eng: str = "") -> None:
|
|
121
|
+
self._url = url
|
|
122
|
+
self._headers = headers
|
|
123
|
+
self._timeout = timeout
|
|
124
|
+
self._eng = eng
|
|
125
|
+
self._session: str | None = None
|
|
126
|
+
self._next_id = 1
|
|
127
|
+
|
|
128
|
+
def _post(self, payload: dict[str, Any]) -> str:
|
|
129
|
+
body = json.dumps(payload).encode("utf-8")
|
|
130
|
+
headers = {
|
|
131
|
+
"Content-Type": "application/json",
|
|
132
|
+
"Accept": "application/json, text/event-stream",
|
|
133
|
+
**self._headers,
|
|
134
|
+
}
|
|
135
|
+
if self._session:
|
|
136
|
+
headers["Mcp-Session-Id"] = self._session
|
|
137
|
+
req = urllib.request.Request(self._url, data=body, headers=headers, method="POST")
|
|
138
|
+
with http_open(req, timeout=self._timeout, engine=self._eng) as resp:
|
|
139
|
+
sid = resp.headers.get("Mcp-Session-Id")
|
|
140
|
+
if sid:
|
|
141
|
+
self._session = sid
|
|
142
|
+
return resp.read().decode("utf-8", "replace")
|
|
143
|
+
|
|
144
|
+
def _request(self, method: str, params: dict[str, Any] | None = None,
|
|
145
|
+
*, notify: bool = False) -> dict[str, Any] | None:
|
|
146
|
+
payload: dict[str, Any] = {"jsonrpc": "2.0", "method": method}
|
|
147
|
+
if notify:
|
|
148
|
+
payload.pop("id", None)
|
|
149
|
+
else:
|
|
150
|
+
payload["id"] = self._next_id
|
|
151
|
+
self._next_id += 1
|
|
152
|
+
if params is not None:
|
|
153
|
+
payload["params"] = params
|
|
154
|
+
raw = self._post(payload)
|
|
155
|
+
return None if notify else _parse_jsonrpc_body(raw)
|
|
156
|
+
|
|
157
|
+
def handshake(self) -> None:
|
|
158
|
+
self._request("initialize", {
|
|
159
|
+
"protocolVersion": _PROTOCOL_VERSION,
|
|
160
|
+
"capabilities": {},
|
|
161
|
+
"clientInfo": _client_info(),
|
|
162
|
+
})
|
|
163
|
+
self._request("notifications/initialized", notify=True)
|
|
164
|
+
|
|
165
|
+
def call_tool(self, tool: str, arguments: dict[str, Any]) -> dict[str, Any] | None:
|
|
166
|
+
obj = self._request("tools/call", {"name": tool, "arguments": arguments})
|
|
167
|
+
if obj is None:
|
|
168
|
+
return None
|
|
169
|
+
if obj.get("error"):
|
|
170
|
+
err = obj["error"]
|
|
171
|
+
raise RuntimeError(f"MCP tools/call error: {err.get('code')} {err.get('message', '')[:200]}")
|
|
172
|
+
return obj.get("result")
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
# ── stdio 通道 ───────────────────────────────────────────────────────────────
|
|
176
|
+
|
|
177
|
+
class _StdioChannel:
|
|
178
|
+
"""stdio 子进程 JSON-RPC 通道:换行分隔帧 + select 截止期读。"""
|
|
179
|
+
|
|
180
|
+
def __init__(self, command: list[str], env: dict[str, str], timeout: float) -> None:
|
|
181
|
+
self._timeout = timeout
|
|
182
|
+
self._proc = subprocess.Popen(
|
|
183
|
+
command,
|
|
184
|
+
stdin=subprocess.PIPE,
|
|
185
|
+
stdout=subprocess.PIPE,
|
|
186
|
+
stderr=subprocess.DEVNULL,
|
|
187
|
+
env=env,
|
|
188
|
+
shell=False,
|
|
189
|
+
text=True,
|
|
190
|
+
encoding="utf-8",
|
|
191
|
+
bufsize=1,
|
|
192
|
+
)
|
|
193
|
+
self._next_id = 1
|
|
194
|
+
|
|
195
|
+
def _exchange(self, payload: dict[str, Any], *, notify: bool) -> dict[str, Any] | None:
|
|
196
|
+
assert self._proc.stdin is not None and self._proc.stdout is not None
|
|
197
|
+
self._proc.stdin.write(json.dumps(payload) + "\n")
|
|
198
|
+
self._proc.stdin.flush()
|
|
199
|
+
if notify:
|
|
200
|
+
return None
|
|
201
|
+
# 预算按墙钟而不是「未就绪的次数」:旧实现只在 select 超时未就绪时
|
|
202
|
+
# deadline -= 1.0,只要对端持续吐帧(日志通知、其它 id 的响应、空行、
|
|
203
|
+
# 解析失败的行)就永远不减,MCP 通知流可以把一次 tools/call 挂死到
|
|
204
|
+
# 线程被杀。截止期在这里唯一,任何读到的行都不得延长它。
|
|
205
|
+
deadline = time.monotonic() + max(0.0, float(self._timeout))
|
|
206
|
+
stream = self._proc.stdout
|
|
207
|
+
while True:
|
|
208
|
+
remaining = deadline - time.monotonic()
|
|
209
|
+
if remaining <= 0:
|
|
210
|
+
break
|
|
211
|
+
ready, _, _ = select.select([stream], [], [], min(remaining, 1.0))
|
|
212
|
+
if not ready:
|
|
213
|
+
continue
|
|
214
|
+
line = stream.readline()
|
|
215
|
+
if not line:
|
|
216
|
+
break
|
|
217
|
+
line = line.strip()
|
|
218
|
+
if not line:
|
|
219
|
+
continue
|
|
220
|
+
try:
|
|
221
|
+
obj = json.loads(line)
|
|
222
|
+
except (json.JSONDecodeError, ValueError):
|
|
223
|
+
continue
|
|
224
|
+
if isinstance(obj, dict) and obj.get("id") == payload.get("id"):
|
|
225
|
+
return obj
|
|
226
|
+
raise TimeoutError(f"MCP stdio 响应超时(工具 {payload.get('method')})")
|
|
227
|
+
|
|
228
|
+
def handshake(self) -> None:
|
|
229
|
+
self._exchange({
|
|
230
|
+
"jsonrpc": "2.0", "id": self._next_id, "method": "initialize",
|
|
231
|
+
"params": {
|
|
232
|
+
"protocolVersion": _PROTOCOL_VERSION,
|
|
233
|
+
"capabilities": {},
|
|
234
|
+
"clientInfo": _client_info(),
|
|
235
|
+
},
|
|
236
|
+
}, notify=False)
|
|
237
|
+
self._next_id += 1
|
|
238
|
+
self._exchange({"jsonrpc": "2.0", "method": "notifications/initialized"}, notify=True)
|
|
239
|
+
|
|
240
|
+
def call_tool(self, tool: str, arguments: dict[str, Any]) -> dict[str, Any] | None:
|
|
241
|
+
self._next_id += 1
|
|
242
|
+
obj = self._exchange({
|
|
243
|
+
"jsonrpc": "2.0", "id": self._next_id, "method": "tools/call",
|
|
244
|
+
"params": {"name": tool, "arguments": arguments},
|
|
245
|
+
}, notify=False)
|
|
246
|
+
if obj is None:
|
|
247
|
+
return None
|
|
248
|
+
if obj.get("error"):
|
|
249
|
+
err = obj["error"]
|
|
250
|
+
raise RuntimeError(f"MCP tools/call error: {err.get('code')} {err.get('message', '')[:200]}")
|
|
251
|
+
return obj.get("result")
|
|
252
|
+
|
|
253
|
+
def close(self) -> None:
|
|
254
|
+
try:
|
|
255
|
+
self._proc.kill()
|
|
256
|
+
except OSError:
|
|
257
|
+
pass
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
# ── 内容层:MCP 结果 → argo 标准条目 ─────────────────────────────────────────
|
|
261
|
+
|
|
262
|
+
def _text_blocks(result: dict[str, Any]) -> str:
|
|
263
|
+
parts = []
|
|
264
|
+
for block in result.get("content") or []:
|
|
265
|
+
if isinstance(block, dict) and block.get("type") == "text":
|
|
266
|
+
t = block.get("text")
|
|
267
|
+
if isinstance(t, str) and t.strip():
|
|
268
|
+
parts.append(t)
|
|
269
|
+
return "\n\n".join(parts)
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def _regex_first(pattern: str, text: str) -> str:
|
|
273
|
+
if not pattern:
|
|
274
|
+
return ""
|
|
275
|
+
m = re.search(pattern, text)
|
|
276
|
+
return (m.group(1) if m and m.groups() else m.group(0)) if m else ""
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def _text_items(text: str, om: dict[str, Any], eng: str, n: int, spec: dict) -> list[dict[str, Any]]:
|
|
280
|
+
"""mode: text——按 text_split 分块,逐块正则抽 title/url/snippet。"""
|
|
281
|
+
split_re = om.get("text_split") or ""
|
|
282
|
+
try:
|
|
283
|
+
chunks = re.split(split_re, text) if split_re else [text]
|
|
284
|
+
except re.error as e:
|
|
285
|
+
raise ValueError(f"output_map.text_split 非法正则: {e}") from e
|
|
286
|
+
rows: list[dict[str, Any]] = []
|
|
287
|
+
for chunk in chunks:
|
|
288
|
+
chunk = chunk.strip()
|
|
289
|
+
if not chunk:
|
|
290
|
+
continue
|
|
291
|
+
row = {
|
|
292
|
+
"title": _regex_first(om.get("item_title_regex", ""), chunk),
|
|
293
|
+
"url": _regex_first(om.get("item_url_regex", ""), chunk),
|
|
294
|
+
"snippet": _regex_first(om.get("item_summary_regex", ""), chunk),
|
|
295
|
+
}
|
|
296
|
+
if not (row["title"] or row["url"] or row["snippet"]):
|
|
297
|
+
continue
|
|
298
|
+
if row["snippet"]:
|
|
299
|
+
row["snippet"] = row["snippet"][:300]
|
|
300
|
+
if row["title"]:
|
|
301
|
+
row["title"] = row["title"][:200]
|
|
302
|
+
rows.append(row)
|
|
303
|
+
if len(rows) >= n:
|
|
304
|
+
break
|
|
305
|
+
return _apply_url_kind(_ensure_engine_source(rows, eng), spec)
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def _result_to_items(result: dict[str, Any] | None, spec: dict, eng: str, n: int) -> list[dict[str, Any]]:
|
|
309
|
+
om = spec.get("output_map") or {}
|
|
310
|
+
mode = str(om.get("mode", "json")).lower()
|
|
311
|
+
if not isinstance(result, dict):
|
|
312
|
+
return []
|
|
313
|
+
if result.get("isError"):
|
|
314
|
+
_get_logger().warning(f"引擎 {eng} MCP 工具 isError: {_text_blocks(result)[:200]}")
|
|
315
|
+
return []
|
|
316
|
+
if mode == "text":
|
|
317
|
+
return _text_items(_text_blocks(result), om, eng, n, spec)
|
|
318
|
+
data = result.get("structuredContent")
|
|
319
|
+
if data is None:
|
|
320
|
+
blob = _text_blocks(result).strip()
|
|
321
|
+
if not blob:
|
|
322
|
+
return []
|
|
323
|
+
try:
|
|
324
|
+
data = json.loads(blob)
|
|
325
|
+
except (json.JSONDecodeError, ValueError):
|
|
326
|
+
raise ValueError(
|
|
327
|
+
f"引擎 {eng} 工具返回非 JSON 文本;纯文本工具须在 output_map 声明 mode: text")
|
|
328
|
+
return _parse_http_payload(json.dumps(data, ensure_ascii=False), "json", eng, n, om, spec)
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
# ── builder ──────────────────────────────────────────────────────────────────
|
|
332
|
+
|
|
333
|
+
def _build_mcp_engine(spec: dict[str, Any]) -> Any:
|
|
334
|
+
"""type: mcp 统一构造(stdio / Streamable HTTP 双传输)。"""
|
|
335
|
+
eng = spec.get("_name", "")
|
|
336
|
+
transport = str(spec.get("transport", "")).lower()
|
|
337
|
+
if transport not in _TRANSPORTS:
|
|
338
|
+
raise ValueError(f"引擎 {eng} type: mcp 需要 transport: http|stdio,得 {transport!r}")
|
|
339
|
+
tool = str(spec.get("tool", "")).strip()
|
|
340
|
+
if not tool:
|
|
341
|
+
raise ValueError(f"引擎 {eng} type: mcp 必须声明 tool(单一 allowlist)")
|
|
342
|
+
timeout = float(spec.get("timeout", 20))
|
|
343
|
+
arguments_template = dict(spec.get("arguments") or {})
|
|
344
|
+
allowed = allowed_placeholders_for(eng, spec)
|
|
345
|
+
|
|
346
|
+
command: list[str] = []
|
|
347
|
+
if transport == "stdio":
|
|
348
|
+
raw_command = spec.get("command")
|
|
349
|
+
# 必须是列表:字符串会被逐字符拆开(且 shell 形态在禁用之列)
|
|
350
|
+
if not isinstance(raw_command, list) or not raw_command or \
|
|
351
|
+
not all(isinstance(c, str) and c.strip() for c in raw_command):
|
|
352
|
+
raise ValueError(
|
|
353
|
+
f"引擎 {eng} stdio 传输必须声明非空 command 字符串列表(禁 shell)")
|
|
354
|
+
command = [str(c) for c in raw_command]
|
|
355
|
+
elif not str(spec.get("url", "")).strip().startswith(("http://", "https://")):
|
|
356
|
+
raise ValueError(f"引擎 {eng} http 传输需要合法 url")
|
|
357
|
+
|
|
358
|
+
@safe_search
|
|
359
|
+
def _engine(query: str, n: int = 5, _timeout: float | None = None, depth: str = "fast", **kwargs) -> list[dict[str, Any]]:
|
|
360
|
+
to = _timeout or timeout
|
|
361
|
+
# env/header 在每次请求时解析(对齐 http builder):daemon 下密钥热轮换
|
|
362
|
+
# 与 envfile 热读不失效;未配置的 {ENV} 头由 _header_meaningful 过滤。
|
|
363
|
+
env = build_child_env(eng, spec) if transport == "stdio" else {}
|
|
364
|
+
headers = {}
|
|
365
|
+
if transport == "http":
|
|
366
|
+
headers = {
|
|
367
|
+
k: v for k, v in (
|
|
368
|
+
(k, _resolve(str(v), query, n, allowed_env=allowed, **kwargs))
|
|
369
|
+
for k, v in (spec.get("headers") or {}).items()
|
|
370
|
+
) if _header_meaningful(v)
|
|
371
|
+
}
|
|
372
|
+
args: dict[str, Any] = {}
|
|
373
|
+
for k, v in arguments_template.items():
|
|
374
|
+
resolved = _resolve(str(v), query, n, allowed_env=allowed, depth=depth, **kwargs)
|
|
375
|
+
if isinstance(resolved, list):
|
|
376
|
+
resolved = " ".join(resolved)
|
|
377
|
+
if resolved.lower() == "true":
|
|
378
|
+
args[k] = True
|
|
379
|
+
elif resolved.lower() == "false":
|
|
380
|
+
args[k] = False
|
|
381
|
+
else:
|
|
382
|
+
try:
|
|
383
|
+
args[k] = int(resolved)
|
|
384
|
+
except ValueError:
|
|
385
|
+
try:
|
|
386
|
+
args[k] = float(resolved)
|
|
387
|
+
except ValueError:
|
|
388
|
+
args[k] = resolved
|
|
389
|
+
channel: Any
|
|
390
|
+
if transport == "stdio":
|
|
391
|
+
channel = _StdioChannel(command, env, to)
|
|
392
|
+
else:
|
|
393
|
+
channel = _HttpChannel(str(spec.get("url")), headers, to, eng=eng)
|
|
394
|
+
try:
|
|
395
|
+
channel.handshake()
|
|
396
|
+
result = channel.call_tool(tool, args)
|
|
397
|
+
except (urllib.error.URLError, TimeoutError, RuntimeError, OSError) as e:
|
|
398
|
+
_get_logger().warning(f"引擎 {eng} MCP 调用失败: {type(e).__name__}: {e}")
|
|
399
|
+
return []
|
|
400
|
+
finally:
|
|
401
|
+
if isinstance(channel, _StdioChannel):
|
|
402
|
+
channel.close()
|
|
403
|
+
return _result_to_items(result, spec, eng, n)
|
|
404
|
+
|
|
405
|
+
return _engine
|