dsh-union-search 0.11.2 → 0.11.3-rc.2
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 -21
- package/cordis.patch.yml +45 -45
- package/lib/index.js +51 -9
- package/lib/mcp_adapter.js +193 -193
- package/package.json +2 -2
package/LICENSE
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
MIT License
|
|
2
|
-
|
|
3
|
-
Copyright (c) 2026 dsh-free-search contributors
|
|
4
|
-
|
|
5
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
-
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
-
in the Software without restriction, including without limitation the rights
|
|
8
|
-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
-
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
-
furnished to do so, subject to the following conditions:
|
|
11
|
-
|
|
12
|
-
The above copyright notice and this permission notice shall be included in all
|
|
13
|
-
copies or substantial portions of the Software.
|
|
14
|
-
|
|
15
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
-
SOFTWARE.
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 dsh-free-search contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/cordis.patch.yml
CHANGED
|
@@ -1,45 +1,45 @@
|
|
|
1
|
-
# dsh-union-search (原 dsh-free-search) — union web search: free keyless engines + professional paid search APIs
|
|
2
|
-
# Registers the plugin into ctx.web + a settings bridge served at
|
|
3
|
-
# /api/dsh-union-search-settings.
|
|
4
|
-
# The engine is chosen from the sidebar Plugins page -> Union Search row config
|
|
5
|
-
# (plugins.row.config, DSH 0.1.7-rc.1+), from the /union-search-engine command,
|
|
6
|
-
# or directly via this entry's config, e.g.:
|
|
7
|
-
# provider: bing # engine id: ddg / bing / baidu / kimi / aliyun / doubao / openai / gemini / claude / auto / multi / ...
|
|
8
|
-
# (openai/gemini/claude are model-based and bill per search; they run only when selected explicitly)
|
|
9
|
-
# region: cn-zh # DuckDuckGo region
|
|
10
|
-
# bingMarket: zh-CN # Bing market
|
|
11
|
-
# A legacy ~/.dsh/settings.yaml "free-search:" section is migrated into this
|
|
12
|
-
# entry's config once at startup (see README). The composition entry id stays
|
|
13
|
-
# `web-search-free` after the 0.10.0 rename: changing it would silently orphan
|
|
14
|
-
# every already-saved profile entry config. Only the package/display identifiers
|
|
15
|
-
# moved to dsh-union-search.
|
|
16
|
-
# Failed/empty engines automatically fall back to the next free engine.
|
|
17
|
-
#
|
|
18
|
-
# NOTE (2026-10, issue #51): this bundle does NOT touch `web.searchProvider`.
|
|
19
|
-
# The plugin takes the search provider over at runtime instead — when the field
|
|
20
|
-
# is unset or still the shipped default (`deepseek-official`) it points it at its
|
|
21
|
-
# own provider id (`ddg`); when another provider was chosen explicitly it leaves
|
|
22
|
-
# it alone and only warns.
|
|
23
|
-
#
|
|
24
|
-
# A static `- id: web config: searchProvider: ddg` used to live here. It was
|
|
25
|
-
# removed because it created a dangling reference: a patch replaces the whole
|
|
26
|
-
# row config, so rows that came from a *disabled* or skipped plugin left
|
|
27
|
-
# `searchProvider: ddg` behind while nothing registered `ddg` — every web search
|
|
28
|
-
# then failed with `configured web provider "ddg" is not registered`. Leaving the
|
|
29
|
-
# base default (`deepseek-official`) in place means a disabled plugin degrades to
|
|
30
|
-
# the official provider instead of breaking search outright.
|
|
31
|
-
# NOTE (0.10.15 bare-name unification, supersedes the 0.9.27 scoped note): the row
|
|
32
|
-
# `name` must be BOTH the specifier the profile resolves AND the package's own
|
|
33
|
-
# manifest name (dsh-client-modules matches row specifier against the nearest
|
|
34
|
-
# package.json `name` via locatePkgJson -> nearestPackage, then uses that manifest
|
|
35
|
-
# name as the boot-graph entry id). The canonical identity is now the UNSCOPED
|
|
36
|
-
# `dsh-union-search`; historic scoped installs (@drscrewdriver/dsh-union-search)
|
|
37
|
-
# keep working but are unmaintained -- migrating = remove + add by bare name
|
|
38
|
-
# (persisted settings keyed by the entry id reset on that swap; accepted 2026-10-24).
|
|
39
|
-
- insert:
|
|
40
|
-
- id: web-search-free
|
|
41
|
-
name: "dsh-union-search"
|
|
42
|
-
config:
|
|
43
|
-
provider: bing
|
|
44
|
-
disabledEngines: []
|
|
45
|
-
bingMarket: zh-CN
|
|
1
|
+
# dsh-union-search (原 dsh-free-search) — union web search: free keyless engines + professional paid search APIs
|
|
2
|
+
# Registers the plugin into ctx.web + a settings bridge served at
|
|
3
|
+
# /api/dsh-union-search-settings.
|
|
4
|
+
# The engine is chosen from the sidebar Plugins page -> Union Search row config
|
|
5
|
+
# (plugins.row.config, DSH 0.1.7-rc.1+), from the /union-search-engine command,
|
|
6
|
+
# or directly via this entry's config, e.g.:
|
|
7
|
+
# provider: bing # engine id: ddg / bing / baidu / kimi / aliyun / doubao / openai / gemini / claude / auto / multi / ...
|
|
8
|
+
# (openai/gemini/claude are model-based and bill per search; they run only when selected explicitly)
|
|
9
|
+
# region: cn-zh # DuckDuckGo region
|
|
10
|
+
# bingMarket: zh-CN # Bing market
|
|
11
|
+
# A legacy ~/.dsh/settings.yaml "free-search:" section is migrated into this
|
|
12
|
+
# entry's config once at startup (see README). The composition entry id stays
|
|
13
|
+
# `web-search-free` after the 0.10.0 rename: changing it would silently orphan
|
|
14
|
+
# every already-saved profile entry config. Only the package/display identifiers
|
|
15
|
+
# moved to dsh-union-search.
|
|
16
|
+
# Failed/empty engines automatically fall back to the next free engine.
|
|
17
|
+
#
|
|
18
|
+
# NOTE (2026-10, issue #51): this bundle does NOT touch `web.searchProvider`.
|
|
19
|
+
# The plugin takes the search provider over at runtime instead — when the field
|
|
20
|
+
# is unset or still the shipped default (`deepseek-official`) it points it at its
|
|
21
|
+
# own provider id (`ddg`); when another provider was chosen explicitly it leaves
|
|
22
|
+
# it alone and only warns.
|
|
23
|
+
#
|
|
24
|
+
# A static `- id: web config: searchProvider: ddg` used to live here. It was
|
|
25
|
+
# removed because it created a dangling reference: a patch replaces the whole
|
|
26
|
+
# row config, so rows that came from a *disabled* or skipped plugin left
|
|
27
|
+
# `searchProvider: ddg` behind while nothing registered `ddg` — every web search
|
|
28
|
+
# then failed with `configured web provider "ddg" is not registered`. Leaving the
|
|
29
|
+
# base default (`deepseek-official`) in place means a disabled plugin degrades to
|
|
30
|
+
# the official provider instead of breaking search outright.
|
|
31
|
+
# NOTE (0.10.15 bare-name unification, supersedes the 0.9.27 scoped note): the row
|
|
32
|
+
# `name` must be BOTH the specifier the profile resolves AND the package's own
|
|
33
|
+
# manifest name (dsh-client-modules matches row specifier against the nearest
|
|
34
|
+
# package.json `name` via locatePkgJson -> nearestPackage, then uses that manifest
|
|
35
|
+
# name as the boot-graph entry id). The canonical identity is now the UNSCOPED
|
|
36
|
+
# `dsh-union-search`; historic scoped installs (@drscrewdriver/dsh-union-search)
|
|
37
|
+
# keep working but are unmaintained -- migrating = remove + add by bare name
|
|
38
|
+
# (persisted settings keyed by the entry id reset on that swap; accepted 2026-10-24).
|
|
39
|
+
- insert:
|
|
40
|
+
- id: web-search-free
|
|
41
|
+
name: "dsh-union-search"
|
|
42
|
+
config:
|
|
43
|
+
provider: bing
|
|
44
|
+
disabledEngines: []
|
|
45
|
+
bingMarket: zh-CN
|
package/lib/index.js
CHANGED
|
@@ -536,7 +536,7 @@ async function searchDdgHtml(query, maxResults, options, signal) {
|
|
|
536
536
|
...(dateMatch ? { publishedAt: dateMatch[1] } : {}),
|
|
537
537
|
});
|
|
538
538
|
}
|
|
539
|
-
return { sources: uniqueSources(sources, maxResults ?? 10), truncated: false };
|
|
539
|
+
return guardRelevance(query, { sources: uniqueSources(sources, maxResults ?? 10), truncated: false });
|
|
540
540
|
}
|
|
541
541
|
|
|
542
542
|
async function searchDdgLite(query, maxResults, options, signal) {
|
|
@@ -566,17 +566,18 @@ async function searchDdgLite(query, maxResults, options, signal) {
|
|
|
566
566
|
...(snippet ? { snippet: stripTags(snippet) } : {}),
|
|
567
567
|
});
|
|
568
568
|
}
|
|
569
|
-
return { sources: uniqueSources(sources, maxResults ?? 10), truncated: false };
|
|
569
|
+
return guardRelevance(query, { sources: uniqueSources(sources, maxResults ?? 10), truncated: false });
|
|
570
570
|
}
|
|
571
571
|
|
|
572
572
|
// Bing 在「查询无结果」时会返回一张完全无关的缓存 SERP(<li class="b_algo"> 照常存在,
|
|
573
573
|
// 但内容是别的查询/热门页的内容),直接返回等于把垃圾结果喂给模型(issue #38:YouTube、
|
|
574
574
|
// 法语微软文档、瑞士基金等都复现过)。这里用「查询 token 与结果文本是否重叠」识别这种页面。
|
|
575
|
-
// token 规则:CJK
|
|
575
|
+
// token 规则:CJK 取二元组(单字不入判据),拉丁/数字取长度 >=2 的词。
|
|
576
576
|
function queryOverlapTokens(query) {
|
|
577
577
|
const tokens = new Set();
|
|
578
578
|
for (const run of String(query).match(/[\u4e00-\u9fff]+/g) ?? []) {
|
|
579
|
-
|
|
579
|
+
// 单字(年/月/日/系/统)几乎出现在任何页面里,只保留二元组(上游 #112 教训)。
|
|
580
|
+
if (run.length === 2) tokens.add(run);
|
|
580
581
|
for (let i = 0; i + 1 < run.length; i++) tokens.add(run.slice(i, i + 2));
|
|
581
582
|
}
|
|
582
583
|
for (const word of String(query).toLowerCase().split(/[^a-z0-9]+/)) {
|
|
@@ -585,13 +586,45 @@ function queryOverlapTokens(query) {
|
|
|
585
586
|
return [...tokens];
|
|
586
587
|
}
|
|
587
588
|
|
|
589
|
+
// 相关性守卫(上游 5001357 + d019d04 终版判据,#112/#132 教训):一批结果与查询词面重叠
|
|
590
|
+
// 太少时判为空结果,交给统一回退链换下一个引擎。三条件同时成立才算相关:
|
|
591
|
+
// ① 命中源数 ≥ 1/3(至少 1)——防单条杂鱼拖整批;② token 重叠度(≥2 个或 ≥50%);
|
|
592
|
+
// ③ 存在标题强命中(中文二元组或 ≥4 位 ASCII 词;短 ASCII 多是型号后缀不算)——
|
|
593
|
+
// 缓存页/导航页正文里满屏都是热词但标题不答问,就是这种。
|
|
588
594
|
function looksRelevant(query, sources) {
|
|
589
595
|
const tokens = queryOverlapTokens(query);
|
|
590
|
-
if (tokens.length === 0) return true; //
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
596
|
+
if (tokens.length === 0) return true; // 纯符号/单字查询无法判定,不拦截
|
|
597
|
+
const strong = tokens.filter((t) => !/^\d+$/.test(t));
|
|
598
|
+
const usable = strong.length > 0 ? strong : tokens;
|
|
599
|
+
const titleStrong = strong.filter((t) => /[\u4e00-\u9fff]/.test(t) || t.length >= 4);
|
|
600
|
+
const titleTokens = titleStrong.length > 0 ? titleStrong : usable;
|
|
601
|
+
const matched = new Set();
|
|
602
|
+
const titleMatched = new Set();
|
|
603
|
+
let relevant = 0;
|
|
604
|
+
for (const source of sources) {
|
|
605
|
+
const title = String(source.title ?? "").toLowerCase();
|
|
606
|
+
const hay = `${title} ${source.snippet ?? ""} ${source.url ?? ""}`.toLowerCase();
|
|
607
|
+
const hits = usable.filter((t) => hay.includes(t.toLowerCase()));
|
|
608
|
+
if (hits.length > 0) {
|
|
609
|
+
relevant += 1;
|
|
610
|
+
for (const hit of hits) matched.add(hit);
|
|
611
|
+
for (const hit of titleTokens) {
|
|
612
|
+
if (title.includes(hit.toLowerCase())) titleMatched.add(hit);
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
const enoughSources = relevant >= Math.max(1, Math.ceil(sources.length / 3));
|
|
617
|
+
const enoughTokens = matched.size >= Math.min(2, usable.length) || matched.size / usable.length >= 0.5;
|
|
618
|
+
return enoughSources && enoughTokens && titleMatched.size > 0;
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
// 引擎出口统一守卫(0.11.3):非空但判无关的批次洗成空结果,交给回退链换下一个引擎;
|
|
622
|
+
// 洗空时附带清掉 content 等聚合提示(避免无关批次的聚合文案残留进工具输出)。
|
|
623
|
+
function guardRelevance(query, result) {
|
|
624
|
+
if (result?.sources?.length > 0 && !looksRelevant(query, result.sources)) {
|
|
625
|
+
return { sources: [], truncated: false };
|
|
626
|
+
}
|
|
627
|
+
return result;
|
|
595
628
|
}
|
|
596
629
|
|
|
597
630
|
async function searchBing(query, maxResults, options, signal) {
|
|
@@ -774,6 +807,12 @@ function mergeSearxngPair(aSources, bSources, maxResults) {
|
|
|
774
807
|
}
|
|
775
808
|
|
|
776
809
|
async function searchSearxng(query, maxResults, options, signal) {
|
|
810
|
+
const res = await searchSearxngRaw(query, maxResults, options, signal);
|
|
811
|
+
// 相关性守卫(0.11.3,与 bing 同判据):公网实例池回无关热页时判空,交回退链。
|
|
812
|
+
return guardRelevance(query, res);
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
async function searchSearxngRaw(query, maxResults, options, signal) {
|
|
777
816
|
const instances = resolveSearxngInstances(options);
|
|
778
817
|
// 三态互斥:当前模式没有端点就是配置问题,直接报可操作错误,绝不偷用其他态的实例
|
|
779
818
|
if (instances.length === 0) {
|
|
@@ -6075,4 +6114,7 @@ export {
|
|
|
6075
6114
|
searchVimeo,
|
|
6076
6115
|
stripBoundaryTags,
|
|
6077
6116
|
wrapUntrustedBlock,
|
|
6117
|
+
looksRelevant,
|
|
6118
|
+
guardRelevance,
|
|
6119
|
+
queryOverlapTokens,
|
|
6078
6120
|
};
|
package/lib/mcp_adapter.js
CHANGED
|
@@ -1,193 +1,193 @@
|
|
|
1
|
-
// MCP JSON-RPC 适配器(方案 v4.3 §2.7):知乎开放平台等 streamable-http MCP 引擎共用。
|
|
2
|
-
// 零新依赖:网络只用 node 标准库(node:https;http:// 端点仅为本地单测保留——
|
|
3
|
-
// 不用 undici/fetch,部分网关按指纹拦 undici,见 research.js #crawl4ai 注记)。
|
|
4
|
-
// 协议要求全部落地:
|
|
5
|
-
// - JSON 与 SSE(text/event-stream 的 data: 行)双响应格式解析;
|
|
6
|
-
// - JSON-RPC error(envelope.error)与工具级 isError(result.isError)区分并各自抛错;
|
|
7
|
-
// - 认证失败(HTTP 401/403)与超时/网络错误给出可被 classifyFailure 归类的消息;
|
|
8
|
-
// - 不假定 HTTP 200 + JSON 解析成功即调用成功:envelope/result/content 逐层校验。
|
|
9
|
-
//
|
|
10
|
-
// 错误消息与 union-search 失败分类(classifyFailure)的约定:
|
|
11
|
-
// 认证 → "authentication failed (HTTP 401/403)" → auth(会话级冷却)
|
|
12
|
-
// 超时/网络 → "timed out"/"aborted"/"ECONN…" → transient(同引擎重试一次)
|
|
13
|
-
// 协议/解析 → "invalid JSON"/"unexpected"/"parse" → invalid-response
|
|
14
|
-
|
|
15
|
-
import https from "node:https";
|
|
16
|
-
import http from "node:http";
|
|
17
|
-
|
|
18
|
-
/**
|
|
19
|
-
* 解析 MCP 响应体:先按纯 JSON 解析,失败再按 SSE 帧提取。
|
|
20
|
-
* SSE 帧:多个 `data:` 行(同一事件内按规范以 \n 拼接);这里同时兼容
|
|
21
|
-
* “每行独立一个完整 JSON-RPC envelope”的服务端实现——两种都取能解析出的 envelope,
|
|
22
|
-
* 优先带 result/error 字段的那条,否则取最后一条可解析的。
|
|
23
|
-
* @param {string} rawText
|
|
24
|
-
* @returns {object|null} JSON-RPC envelope,无法解析返回 null
|
|
25
|
-
*/
|
|
26
|
-
export function parseMcpResponseText(rawText) {
|
|
27
|
-
if (typeof rawText !== "string" || rawText.length === 0) return null;
|
|
28
|
-
const direct = tryJson(rawText);
|
|
29
|
-
if (direct) return direct;
|
|
30
|
-
|
|
31
|
-
// SSE:按空行切事件;事件内拼接 data: 行负载
|
|
32
|
-
const events = rawText.split(/\r?\n\r?\n/);
|
|
33
|
-
const payloads = [];
|
|
34
|
-
for (const event of events) {
|
|
35
|
-
const dataLines = [];
|
|
36
|
-
for (const line of event.split(/\r?\n/)) {
|
|
37
|
-
if (line.startsWith("data:")) dataLines.push(line.slice(5).replace(/^ /, ""));
|
|
38
|
-
}
|
|
39
|
-
if (dataLines.length > 0) payloads.push(dataLines.join("\n"));
|
|
40
|
-
}
|
|
41
|
-
// 兼容没有空行分隔、每行一个 data: 的实现
|
|
42
|
-
if (payloads.length === 0) {
|
|
43
|
-
for (const line of rawText.split(/\r?\n/)) {
|
|
44
|
-
if (line.startsWith("data:")) payloads.push(line.slice(5).replace(/^ /, ""));
|
|
45
|
-
}
|
|
46
|
-
}
|
|
47
|
-
let fallback = null;
|
|
48
|
-
for (const payload of payloads) {
|
|
49
|
-
const parsed = tryJson(payload);
|
|
50
|
-
if (!parsed || typeof parsed !== "object") continue;
|
|
51
|
-
if (parsed.result !== undefined || parsed.error !== undefined) return parsed;
|
|
52
|
-
fallback = fallback ?? parsed;
|
|
53
|
-
}
|
|
54
|
-
return fallback;
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
function tryJson(text) {
|
|
58
|
-
try {
|
|
59
|
-
const parsed = JSON.parse(text);
|
|
60
|
-
return parsed && typeof parsed === "object" ? parsed : null;
|
|
61
|
-
} catch {
|
|
62
|
-
return null;
|
|
63
|
-
}
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
/**
|
|
67
|
-
* 发送一次 JSON-RPC 2.0 请求并返回 envelope.result(工具调用的 CallToolResult)。
|
|
68
|
-
* 任何失败路径都以 Error 抛出(消息见文件头分类约定),不返回部分结果。
|
|
69
|
-
*
|
|
70
|
-
* @param {string} endpoint MCP HTTP 端点(如 https://developer.zhihu.com/api/mcp/v1)
|
|
71
|
-
* @param {object} headers 额外请求头(Authorization / 自定义 UA 等;Content-Type/Accept 内置可覆盖)
|
|
72
|
-
* @param {string} method JSON-RPC 方法("tools/call" / "initialize" / …)
|
|
73
|
-
* @param {object|undefined} params JSON-RPC params
|
|
74
|
-
* @param {{timeoutMs?: number, signal?: AbortSignal, id?: number|string, label?: string}} [options]
|
|
75
|
-
* timeoutMs 默认 30000,<=0 表示不限;label 用于错误消息前缀(默认取端点 hostname)
|
|
76
|
-
* @returns {Promise<object>} JSON-RPC result 对象(tools/call 时为 {content, isError?})
|
|
77
|
-
*/
|
|
78
|
-
export async function mcpCall(endpoint, headers = {}, method, params, options = {}) {
|
|
79
|
-
const { timeoutMs = 30000, signal, id = 1 } = options;
|
|
80
|
-
const label = options.label ?? safeHost(endpoint);
|
|
81
|
-
const body = JSON.stringify({
|
|
82
|
-
jsonrpc: "2.0",
|
|
83
|
-
id,
|
|
84
|
-
method,
|
|
85
|
-
...(params !== undefined ? { params } : {}),
|
|
86
|
-
});
|
|
87
|
-
|
|
88
|
-
const rawText = await httpsPost(endpoint, body, {
|
|
89
|
-
"content-type": "application/json",
|
|
90
|
-
accept: "application/json, text/event-stream",
|
|
91
|
-
...headers,
|
|
92
|
-
}, { timeoutMs, signal, label });
|
|
93
|
-
|
|
94
|
-
const envelope = parseMcpResponseText(rawText);
|
|
95
|
-
if (!envelope) {
|
|
96
|
-
throw new Error(`${label} MCP response is not valid JSON or SSE (parse failed): ${rawText.slice(0, 200)}`);
|
|
97
|
-
}
|
|
98
|
-
if (envelope.error) {
|
|
99
|
-
const { code, message } = envelope.error;
|
|
100
|
-
throw new Error(`${label} MCP error ${code ?? "?"}: ${message ?? JSON.stringify(envelope.error)}`);
|
|
101
|
-
}
|
|
102
|
-
const result = envelope.result;
|
|
103
|
-
if (result === null || result === undefined || typeof result !== "object" || Array.isArray(result)) {
|
|
104
|
-
throw new Error(`${label} MCP result missing or malformed: ${JSON.stringify(envelope).slice(0, 200)}`);
|
|
105
|
-
}
|
|
106
|
-
if (method === "tools/call" && result.isError) {
|
|
107
|
-
// 工具级错误:isError=true,正文在 content 里,不能当搜索结果
|
|
108
|
-
const errText = mcpContentText(result);
|
|
109
|
-
throw new Error(`${label} MCP tool error (isError): ${errText.slice(0, 200) || JSON.stringify(result).slice(0, 200)}`);
|
|
110
|
-
}
|
|
111
|
-
return result;
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
/** 从 CallToolResult.content 里取第一条 text 类型的文本(无则返回空串)。 */
|
|
115
|
-
export function mcpContentText(result) {
|
|
116
|
-
if (!result || !Array.isArray(result.content)) return "";
|
|
117
|
-
const item = result.content.find((c) => c && c.type === "text" && typeof c.text === "string");
|
|
118
|
-
return item ? item.text : "";
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
function safeHost(endpoint) {
|
|
122
|
-
try {
|
|
123
|
-
return new URL(endpoint).hostname;
|
|
124
|
-
} catch {
|
|
125
|
-
return "MCP";
|
|
126
|
-
}
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
// 真实引擎端点都是 https;http 仅为本地错误路径单测保留(同一套 node 标准库实现)
|
|
130
|
-
function transportFor(endpoint) {
|
|
131
|
-
try {
|
|
132
|
-
return new URL(endpoint).protocol === "http:" ? http : https;
|
|
133
|
-
} catch {
|
|
134
|
-
return https;
|
|
135
|
-
}
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
function httpsPost(endpoint, body, headers, { timeoutMs, signal, label }) {
|
|
139
|
-
return new Promise((resolve, reject) => {
|
|
140
|
-
let settled = false;
|
|
141
|
-
let timer = null;
|
|
142
|
-
const onAbort = () => {
|
|
143
|
-
req.destroy(new Error(`${label} MCP request aborted`));
|
|
144
|
-
};
|
|
145
|
-
const req = transportFor(endpoint).request(endpoint, {
|
|
146
|
-
method: "POST",
|
|
147
|
-
headers: { ...headers, "content-length": Buffer.byteLength(body) },
|
|
148
|
-
}, (res) => {
|
|
149
|
-
const chunks = [];
|
|
150
|
-
res.on("data", (chunk) => chunks.push(chunk));
|
|
151
|
-
res.on("end", () => {
|
|
152
|
-
const status = res.statusCode ?? 0;
|
|
153
|
-
const text = Buffer.concat(chunks).toString("utf8");
|
|
154
|
-
if (settled) return;
|
|
155
|
-
settled = true;
|
|
156
|
-
cleanup();
|
|
157
|
-
if (status === 401 || status === 403) {
|
|
158
|
-
reject(new Error(`${label} MCP authentication failed (HTTP ${status}) - check the API key`));
|
|
159
|
-
return;
|
|
160
|
-
}
|
|
161
|
-
if (status < 200 || status >= 300) {
|
|
162
|
-
reject(new Error(`${label} MCP HTTP ${status}: ${text.slice(0, 200)}`));
|
|
163
|
-
return;
|
|
164
|
-
}
|
|
165
|
-
resolve(text);
|
|
166
|
-
});
|
|
167
|
-
});
|
|
168
|
-
const cleanup = () => {
|
|
169
|
-
if (timer !== null) clearTimeout(timer);
|
|
170
|
-
signal?.removeEventListener("abort", onAbort);
|
|
171
|
-
};
|
|
172
|
-
req.on("error", (error) => {
|
|
173
|
-
if (settled) return;
|
|
174
|
-
settled = true;
|
|
175
|
-
cleanup();
|
|
176
|
-
// destroy(err) 的 err 带上下文直接透传;网络栈错误补前缀
|
|
177
|
-
reject(error instanceof Error && /MCP/.test(error.message ?? "")
|
|
178
|
-
? error
|
|
179
|
-
: new Error(`${label} MCP request failed: ${error?.message ?? String(error)}`));
|
|
180
|
-
});
|
|
181
|
-
if (timeoutMs > 0) {
|
|
182
|
-
timer = setTimeout(() => {
|
|
183
|
-
req.destroy(new Error(`${label} MCP request timed out after ${timeoutMs}ms (timeout)`));
|
|
184
|
-
}, timeoutMs);
|
|
185
|
-
}
|
|
186
|
-
if (signal?.aborted) {
|
|
187
|
-
req.destroy(new Error(`${label} MCP request aborted`));
|
|
188
|
-
return;
|
|
189
|
-
}
|
|
190
|
-
signal?.addEventListener("abort", onAbort, { once: true });
|
|
191
|
-
req.end(body);
|
|
192
|
-
});
|
|
193
|
-
}
|
|
1
|
+
// MCP JSON-RPC 适配器(方案 v4.3 §2.7):知乎开放平台等 streamable-http MCP 引擎共用。
|
|
2
|
+
// 零新依赖:网络只用 node 标准库(node:https;http:// 端点仅为本地单测保留——
|
|
3
|
+
// 不用 undici/fetch,部分网关按指纹拦 undici,见 research.js #crawl4ai 注记)。
|
|
4
|
+
// 协议要求全部落地:
|
|
5
|
+
// - JSON 与 SSE(text/event-stream 的 data: 行)双响应格式解析;
|
|
6
|
+
// - JSON-RPC error(envelope.error)与工具级 isError(result.isError)区分并各自抛错;
|
|
7
|
+
// - 认证失败(HTTP 401/403)与超时/网络错误给出可被 classifyFailure 归类的消息;
|
|
8
|
+
// - 不假定 HTTP 200 + JSON 解析成功即调用成功:envelope/result/content 逐层校验。
|
|
9
|
+
//
|
|
10
|
+
// 错误消息与 union-search 失败分类(classifyFailure)的约定:
|
|
11
|
+
// 认证 → "authentication failed (HTTP 401/403)" → auth(会话级冷却)
|
|
12
|
+
// 超时/网络 → "timed out"/"aborted"/"ECONN…" → transient(同引擎重试一次)
|
|
13
|
+
// 协议/解析 → "invalid JSON"/"unexpected"/"parse" → invalid-response
|
|
14
|
+
|
|
15
|
+
import https from "node:https";
|
|
16
|
+
import http from "node:http";
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* 解析 MCP 响应体:先按纯 JSON 解析,失败再按 SSE 帧提取。
|
|
20
|
+
* SSE 帧:多个 `data:` 行(同一事件内按规范以 \n 拼接);这里同时兼容
|
|
21
|
+
* “每行独立一个完整 JSON-RPC envelope”的服务端实现——两种都取能解析出的 envelope,
|
|
22
|
+
* 优先带 result/error 字段的那条,否则取最后一条可解析的。
|
|
23
|
+
* @param {string} rawText
|
|
24
|
+
* @returns {object|null} JSON-RPC envelope,无法解析返回 null
|
|
25
|
+
*/
|
|
26
|
+
export function parseMcpResponseText(rawText) {
|
|
27
|
+
if (typeof rawText !== "string" || rawText.length === 0) return null;
|
|
28
|
+
const direct = tryJson(rawText);
|
|
29
|
+
if (direct) return direct;
|
|
30
|
+
|
|
31
|
+
// SSE:按空行切事件;事件内拼接 data: 行负载
|
|
32
|
+
const events = rawText.split(/\r?\n\r?\n/);
|
|
33
|
+
const payloads = [];
|
|
34
|
+
for (const event of events) {
|
|
35
|
+
const dataLines = [];
|
|
36
|
+
for (const line of event.split(/\r?\n/)) {
|
|
37
|
+
if (line.startsWith("data:")) dataLines.push(line.slice(5).replace(/^ /, ""));
|
|
38
|
+
}
|
|
39
|
+
if (dataLines.length > 0) payloads.push(dataLines.join("\n"));
|
|
40
|
+
}
|
|
41
|
+
// 兼容没有空行分隔、每行一个 data: 的实现
|
|
42
|
+
if (payloads.length === 0) {
|
|
43
|
+
for (const line of rawText.split(/\r?\n/)) {
|
|
44
|
+
if (line.startsWith("data:")) payloads.push(line.slice(5).replace(/^ /, ""));
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
let fallback = null;
|
|
48
|
+
for (const payload of payloads) {
|
|
49
|
+
const parsed = tryJson(payload);
|
|
50
|
+
if (!parsed || typeof parsed !== "object") continue;
|
|
51
|
+
if (parsed.result !== undefined || parsed.error !== undefined) return parsed;
|
|
52
|
+
fallback = fallback ?? parsed;
|
|
53
|
+
}
|
|
54
|
+
return fallback;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function tryJson(text) {
|
|
58
|
+
try {
|
|
59
|
+
const parsed = JSON.parse(text);
|
|
60
|
+
return parsed && typeof parsed === "object" ? parsed : null;
|
|
61
|
+
} catch {
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* 发送一次 JSON-RPC 2.0 请求并返回 envelope.result(工具调用的 CallToolResult)。
|
|
68
|
+
* 任何失败路径都以 Error 抛出(消息见文件头分类约定),不返回部分结果。
|
|
69
|
+
*
|
|
70
|
+
* @param {string} endpoint MCP HTTP 端点(如 https://developer.zhihu.com/api/mcp/v1)
|
|
71
|
+
* @param {object} headers 额外请求头(Authorization / 自定义 UA 等;Content-Type/Accept 内置可覆盖)
|
|
72
|
+
* @param {string} method JSON-RPC 方法("tools/call" / "initialize" / …)
|
|
73
|
+
* @param {object|undefined} params JSON-RPC params
|
|
74
|
+
* @param {{timeoutMs?: number, signal?: AbortSignal, id?: number|string, label?: string}} [options]
|
|
75
|
+
* timeoutMs 默认 30000,<=0 表示不限;label 用于错误消息前缀(默认取端点 hostname)
|
|
76
|
+
* @returns {Promise<object>} JSON-RPC result 对象(tools/call 时为 {content, isError?})
|
|
77
|
+
*/
|
|
78
|
+
export async function mcpCall(endpoint, headers = {}, method, params, options = {}) {
|
|
79
|
+
const { timeoutMs = 30000, signal, id = 1 } = options;
|
|
80
|
+
const label = options.label ?? safeHost(endpoint);
|
|
81
|
+
const body = JSON.stringify({
|
|
82
|
+
jsonrpc: "2.0",
|
|
83
|
+
id,
|
|
84
|
+
method,
|
|
85
|
+
...(params !== undefined ? { params } : {}),
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
const rawText = await httpsPost(endpoint, body, {
|
|
89
|
+
"content-type": "application/json",
|
|
90
|
+
accept: "application/json, text/event-stream",
|
|
91
|
+
...headers,
|
|
92
|
+
}, { timeoutMs, signal, label });
|
|
93
|
+
|
|
94
|
+
const envelope = parseMcpResponseText(rawText);
|
|
95
|
+
if (!envelope) {
|
|
96
|
+
throw new Error(`${label} MCP response is not valid JSON or SSE (parse failed): ${rawText.slice(0, 200)}`);
|
|
97
|
+
}
|
|
98
|
+
if (envelope.error) {
|
|
99
|
+
const { code, message } = envelope.error;
|
|
100
|
+
throw new Error(`${label} MCP error ${code ?? "?"}: ${message ?? JSON.stringify(envelope.error)}`);
|
|
101
|
+
}
|
|
102
|
+
const result = envelope.result;
|
|
103
|
+
if (result === null || result === undefined || typeof result !== "object" || Array.isArray(result)) {
|
|
104
|
+
throw new Error(`${label} MCP result missing or malformed: ${JSON.stringify(envelope).slice(0, 200)}`);
|
|
105
|
+
}
|
|
106
|
+
if (method === "tools/call" && result.isError) {
|
|
107
|
+
// 工具级错误:isError=true,正文在 content 里,不能当搜索结果
|
|
108
|
+
const errText = mcpContentText(result);
|
|
109
|
+
throw new Error(`${label} MCP tool error (isError): ${errText.slice(0, 200) || JSON.stringify(result).slice(0, 200)}`);
|
|
110
|
+
}
|
|
111
|
+
return result;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** 从 CallToolResult.content 里取第一条 text 类型的文本(无则返回空串)。 */
|
|
115
|
+
export function mcpContentText(result) {
|
|
116
|
+
if (!result || !Array.isArray(result.content)) return "";
|
|
117
|
+
const item = result.content.find((c) => c && c.type === "text" && typeof c.text === "string");
|
|
118
|
+
return item ? item.text : "";
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function safeHost(endpoint) {
|
|
122
|
+
try {
|
|
123
|
+
return new URL(endpoint).hostname;
|
|
124
|
+
} catch {
|
|
125
|
+
return "MCP";
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// 真实引擎端点都是 https;http 仅为本地错误路径单测保留(同一套 node 标准库实现)
|
|
130
|
+
function transportFor(endpoint) {
|
|
131
|
+
try {
|
|
132
|
+
return new URL(endpoint).protocol === "http:" ? http : https;
|
|
133
|
+
} catch {
|
|
134
|
+
return https;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function httpsPost(endpoint, body, headers, { timeoutMs, signal, label }) {
|
|
139
|
+
return new Promise((resolve, reject) => {
|
|
140
|
+
let settled = false;
|
|
141
|
+
let timer = null;
|
|
142
|
+
const onAbort = () => {
|
|
143
|
+
req.destroy(new Error(`${label} MCP request aborted`));
|
|
144
|
+
};
|
|
145
|
+
const req = transportFor(endpoint).request(endpoint, {
|
|
146
|
+
method: "POST",
|
|
147
|
+
headers: { ...headers, "content-length": Buffer.byteLength(body) },
|
|
148
|
+
}, (res) => {
|
|
149
|
+
const chunks = [];
|
|
150
|
+
res.on("data", (chunk) => chunks.push(chunk));
|
|
151
|
+
res.on("end", () => {
|
|
152
|
+
const status = res.statusCode ?? 0;
|
|
153
|
+
const text = Buffer.concat(chunks).toString("utf8");
|
|
154
|
+
if (settled) return;
|
|
155
|
+
settled = true;
|
|
156
|
+
cleanup();
|
|
157
|
+
if (status === 401 || status === 403) {
|
|
158
|
+
reject(new Error(`${label} MCP authentication failed (HTTP ${status}) - check the API key`));
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
if (status < 200 || status >= 300) {
|
|
162
|
+
reject(new Error(`${label} MCP HTTP ${status}: ${text.slice(0, 200)}`));
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
resolve(text);
|
|
166
|
+
});
|
|
167
|
+
});
|
|
168
|
+
const cleanup = () => {
|
|
169
|
+
if (timer !== null) clearTimeout(timer);
|
|
170
|
+
signal?.removeEventListener("abort", onAbort);
|
|
171
|
+
};
|
|
172
|
+
req.on("error", (error) => {
|
|
173
|
+
if (settled) return;
|
|
174
|
+
settled = true;
|
|
175
|
+
cleanup();
|
|
176
|
+
// destroy(err) 的 err 带上下文直接透传;网络栈错误补前缀
|
|
177
|
+
reject(error instanceof Error && /MCP/.test(error.message ?? "")
|
|
178
|
+
? error
|
|
179
|
+
: new Error(`${label} MCP request failed: ${error?.message ?? String(error)}`));
|
|
180
|
+
});
|
|
181
|
+
if (timeoutMs > 0) {
|
|
182
|
+
timer = setTimeout(() => {
|
|
183
|
+
req.destroy(new Error(`${label} MCP request timed out after ${timeoutMs}ms (timeout)`));
|
|
184
|
+
}, timeoutMs);
|
|
185
|
+
}
|
|
186
|
+
if (signal?.aborted) {
|
|
187
|
+
req.destroy(new Error(`${label} MCP request aborted`));
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
191
|
+
req.end(body);
|
|
192
|
+
});
|
|
193
|
+
}
|
package/package.json
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-union-search",
|
|
3
|
-
"version": "0.11.2",
|
|
3
|
+
"version": "0.11.3-rc.2",
|
|
4
4
|
"description": "Union web search for DeepSeek Harness (renamed from dsh-free-search): free keyless engines + many professional paid search APIs — 28 engines (Bing/DuckDuckGo/AnySearch/SearXNG multi-instance union/Exa/Tavily/Keenable/Firecrawl/Parallel keyless; Zhihu global/site via MCP and Perplexity/SerpBase/Serply/DeepSeek official/You.com/Baidu/Kimi/Aliyun/Doubao/Zhipu/Bocha/Metaso with key; OpenAI/Gemini/Claude/Grok model built-in search, explicit-only) + auto smart routing + global engine enable/disable & fallback priority + multi mode (parallel top-3 merge) + multi_search cross-source tool + failure-aware fallback + block system built-in search toggle + experimental free advance_fetch (no API key, no billing; host-twin GitHub-Flavored Markdown conversion + CSS selector/fields structured extraction) + time filtering + platform search + web_fetch, with web settings UI.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "lib/index.js",
|
|
7
7
|
"scripts": {
|
|
8
|
-
"test": "node --test test/md.test.mjs test/egress.test.mjs test/credentials.test.mjs test/tool-face.test.mjs test/notes-channel.test.mjs"
|
|
8
|
+
"test": "node --test test/md.test.mjs test/egress.test.mjs test/relevance.test.mjs test/credentials.test.mjs test/tool-face.test.mjs test/notes-channel.test.mjs"
|
|
9
9
|
},
|
|
10
10
|
"exports": {
|
|
11
11
|
".": "./lib/index.js",
|