dsh-union-search 0.11.1 → 0.11.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 +35 -12
- 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
|
@@ -354,7 +354,28 @@ function decodeEntities(text) {
|
|
|
354
354
|
.replace(/'/g, "'")
|
|
355
355
|
.replace(/'/g, "'")
|
|
356
356
|
.replace(/ /g, " ")
|
|
357
|
-
.replace(/&#(\d+);/g, (_, n) =>
|
|
357
|
+
.replace(/&#(\d+);/g, (_, n) => fromCodePointSafe(Number(n)));
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
// 码点安全截断(上游 #108 教训):UTF-16 半代理截出孤立代理项后,JSON.stringify 会产出
|
|
361
|
+
// 非法字符串污染会话且不可恢复。凡对外输出/入请求体的文本截断一律走本函数,
|
|
362
|
+
// 纯检测用途(反爬页扫描等)保留原生 slice。limit 落在代理对中间时回退到高代理前。
|
|
363
|
+
function cutSafe(text, limit) {
|
|
364
|
+
const s = String(text ?? "");
|
|
365
|
+
if (s.length <= limit) return s;
|
|
366
|
+
let cut = limit;
|
|
367
|
+
const hi = s.charCodeAt(cut - 1);
|
|
368
|
+
const lo = s.charCodeAt(cut);
|
|
369
|
+
if (hi >= 0xd800 && hi <= 0xdbff && lo >= 0xdc00 && lo <= 0xdfff) cut -= 1;
|
|
370
|
+
return s.slice(0, cut);
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
// 数字实体解码:星平面(>0xFFFF)必须 fromCodePoint;fromCharCode 会直接产出孤立代理。
|
|
374
|
+
// 越界(>0x10FFFF)与孤立代理区(D800-DFFF)一律丢空(与浏览器实体行为一致),不造畸形码点。
|
|
375
|
+
function fromCodePointSafe(n) {
|
|
376
|
+
if (!Number.isInteger(n) || n <= 0 || n > 0x10ffff) return "";
|
|
377
|
+
if (n >= 0xd800 && n <= 0xdfff) return "";
|
|
378
|
+
return String.fromCodePoint(n);
|
|
358
379
|
}
|
|
359
380
|
|
|
360
381
|
//#region 结果缓存(防限流/省额度,LRU 50 条,TTL 可配置 0-5 分钟)
|
|
@@ -376,12 +397,14 @@ const SNIPPET_NOISE =
|
|
|
376
397
|
|
|
377
398
|
function cleanSnippet(text, max = 300) {
|
|
378
399
|
if (!text) return text;
|
|
379
|
-
return
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
400
|
+
return cutSafe(
|
|
401
|
+
String(text)
|
|
402
|
+
.replace(SNIPPET_NOISE, " ")
|
|
403
|
+
.replace(/^\s*(#{1,6}\s*|\[\s*x?\s*\]\s*|-\s*\[\s*x?\s*\]\s*|>\s*)/gm, " ")
|
|
404
|
+
.replace(/\s+/g, " ")
|
|
405
|
+
.trim(),
|
|
406
|
+
max,
|
|
407
|
+
);
|
|
385
408
|
}
|
|
386
409
|
|
|
387
410
|
// 各引擎的摘要展示上限:豆包搜索返回的是千字级 Summary(实测 1300-1800 字),放宽到 2000;
|
|
@@ -1122,10 +1145,7 @@ function normalizeHeadings(md) {
|
|
|
1122
1145
|
function smartTruncate(text, limit) {
|
|
1123
1146
|
const s = String(text ?? "");
|
|
1124
1147
|
if (s.length <= limit) return s;
|
|
1125
|
-
|
|
1126
|
-
const hi = s.charCodeAt(limit - 1);
|
|
1127
|
-
const lo = s.charCodeAt(limit);
|
|
1128
|
-
if (hi >= 0xd800 && hi <= 0xdbff && lo >= 0xdc00 && lo <= 0xdfff) cutLimit = limit - 1;
|
|
1148
|
+
const cutLimit = cutSafe(s, limit).length; // 代理对回退统一走 cutSafe 判则
|
|
1129
1149
|
const window = s.slice(0, cutLimit);
|
|
1130
1150
|
const nl = window.lastIndexOf("\n");
|
|
1131
1151
|
const sp = window.lastIndexOf(" ");
|
|
@@ -1206,7 +1226,7 @@ function extractBySelector(html, { selector, fields, mode, baseUrl } = {}) {
|
|
|
1206
1226
|
}
|
|
1207
1227
|
const value = attr ? hit.attr(attr) ?? "" : hit.text();
|
|
1208
1228
|
const clean = String(value).replace(/\s+/g, " ").trim();
|
|
1209
|
-
extracted.push({ label, value: clean.length > 500 ? `${clean
|
|
1229
|
+
extracted.push({ label, value: clean.length > 500 ? `${cutSafe(clean, 500)}…` : clean });
|
|
1210
1230
|
}
|
|
1211
1231
|
return { extracted, scope, note: note.join("; ") || undefined };
|
|
1212
1232
|
}
|
|
@@ -6029,6 +6049,9 @@ export {
|
|
|
6029
6049
|
normalizeSearxngLang,
|
|
6030
6050
|
htmlToMarkdownGfm,
|
|
6031
6051
|
extractBySelector,
|
|
6052
|
+
cutSafe,
|
|
6053
|
+
cleanSnippet,
|
|
6054
|
+
decodeEntities,
|
|
6032
6055
|
matchCookieEntry,
|
|
6033
6056
|
parseCookieMap,
|
|
6034
6057
|
parseFieldSpecs,
|
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.
|
|
3
|
+
"version": "0.11.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/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/credentials.test.mjs test/tool-face.test.mjs test/notes-channel.test.mjs"
|
|
9
9
|
},
|
|
10
10
|
"exports": {
|
|
11
11
|
".": "./lib/index.js",
|