Compare commits
3
Commits
dbd67ec273
...
cc53c117e8
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cc53c117e8 | ||
|
|
10877c9723 | ||
|
|
509d63a99b |
+6
-2
@@ -190,8 +190,12 @@ IM 用户在实时对话,回合中插话应当“当前这步跑完就插”
|
||||
- 重读去重(engine `run.imgDelivered`)**只拦同一批 tool call 内的重复读**(一次请求里塞两份同样的图
|
||||
没意义);跨批次重读一律放行。不要写成「一回合只投递一次」,也不要靠推测「图还在不在上下文里」——
|
||||
模型说拿不到就得给,而且文件可能已重新生成(路径相同、内容不同);拦掉只会把新像素挡在门外。
|
||||
- 占位裁剪(`agent.trim_write_rounds` / `trim_result_rounds`):距尾 ≥N 个 assistant 轮的
|
||||
`write_file.content`、`fetch`/`read_file` 回执换成单行占位。**只改发给上游的副本**,DB 与 UI 不动。
|
||||
- 占位裁剪(`agent.trim.rules`):距尾 ≥N 个 assistant 轮的指定工具参数(`side: args` + `fields`,
|
||||
仅顶层字符串)或回执正文(`side: result`)换成单行占位。默认规则在 `config.js` 的
|
||||
`DEFAULTS.agent.trim.rules`(`write_file.content` / `fetch` / `read_file` / `web_search`),
|
||||
`config.yml` 写了 `trim.rules` 就整体替换(`[]` = 全关)。
|
||||
**只改发给上游的副本**,DB 与 UI 不动。规则只给「内容可再生或只是当时快照」的工具配:
|
||||
`terminal` 这类一次性输出裁掉后模型就再也看不到(规则写法见 `config.example.yml` 的 `agent.trim`)。
|
||||
- `compressMessages` = `buildMessages` + 末尾一条压缩指令 `user`。**铁律**:压缩请求必须与上一次
|
||||
常规请求字节同构、只在尾部追加;不要为了省 token 在压缩回合抽掉快照或裁剪历史,断前缀缓存等于全价重读。
|
||||
- `titleMessages`:不带 system prompt,只取 user/assistant 纯文本行(白名单 `null`/`summary`/`task_brief`)
|
||||
|
||||
+23
-2
@@ -47,8 +47,29 @@ agent:
|
||||
max_retries: 2 # 上游失败重试次数
|
||||
language: "Simplified Chinese" # 强制回复语言;留空不限
|
||||
auto_compress_tokens: 60000 # In token 超此值弹「自动压缩」提议;0=关
|
||||
trim_write_rounds: 1 # 历史重放裁剪:write_file 参数正文距尾 ≥N 个 assistant 轮换单行占位(0=关;DB/UI 不动,盘上可重读)
|
||||
trim_result_rounds: 2 # fetch/read_file 回执正文距尾 ≥N 个 assistant 轮换单行占位(0=关;占位留 url/path 作恢复指针)
|
||||
# 历史重放占位裁剪(省 token):某条工具调用/回执距对话尾部 ≥rounds 个 assistant 轮后,
|
||||
# 把可再生的重负载换成单行占位再发给上游(DB/UI 不动,盘上可重读/重抓)。rounds=0 或
|
||||
# 不写这条规则 = 不裁;整段 rules: [] = 全关。
|
||||
# 下面是内置默认(与 config.js 的 DEFAULTS.agent.trim.rules 同步);写了本段就整体替换默认。
|
||||
# side=args 裁调用参数(fields 点名顶层字符串参数);side=result 裁整段回执正文。
|
||||
# tool 用模型看到的最终工具名(MCP 重名时含 server__ 前缀)。
|
||||
trim:
|
||||
min_chars: 600 # 短于此长度的正文不裁(占位自身也有成本);单条规则可用 min_chars 覆盖
|
||||
rules:
|
||||
- tool: write_file # 参数正文只是写盘时的快照,后续 edit_file 一次就失真
|
||||
side: args
|
||||
fields: [content]
|
||||
rounds: 1
|
||||
- tool: fetch # 页面可重抓;status_regex 取第一个捕获组写进占位(YAML 用单引号,避免 \d 被当转义)
|
||||
side: result
|
||||
rounds: 2
|
||||
status_regex: '^HTTP (\d{3})'
|
||||
- tool: read_file # 文件在盘上,可重读
|
||||
side: result
|
||||
rounds: 2
|
||||
- tool: web_search # 栈内免费搜索 MCP;可重搜,但结果会随时间变化
|
||||
side: result
|
||||
rounds: 2
|
||||
auto_complete_ms: 1800000 # 保持中(held)超此时长自动收口为已完成;0=关(纯状态动作,历史/模型绑定不动)
|
||||
|
||||
# 长期记忆(日记,memory.js):收口时一条几十字第一人称碎片入当日条目;存储默认永久,旧记忆靠回忆下钻
|
||||
|
||||
+85
-3
@@ -86,9 +86,18 @@ const DEFAULTS = {
|
||||
// auto_compress_tokens:本轮 In token 峰值 ≥ 此值时推送「自动压缩」提议(0=关)。
|
||||
// auto_complete_ms:held(保持中)超过此时长自动收口为 completed(0=关)。key 非独占后 held 不占任何资源,
|
||||
// 收口是纯视觉动作:历史/绑定不动,再发言照常由 completed 分支续跑(见 engine.sweepHeldTimeouts)。
|
||||
// trim_write_rounds / trim_result_rounds:历史重放占位裁剪(llm.buildMessages)——write_file 参数正文 /
|
||||
// fetch、read_file 回执正文距尾 ≥N 个 assistant 轮后换单行占位(DB/UI 不动,内容可再生:盘上重读/重抓);0=关。
|
||||
agent: { temperature: 1.0, max_tool_iterations: 100, max_retries: 2, language: 'Simplified Chinese', auto_compress_tokens: 60000, auto_complete_ms: 1800000, trim_write_rounds: 1, trim_result_rounds: 2 },
|
||||
// 历史重放占位裁剪(llm.buildMessages):trim.rules 逐条声明「哪个工具、参数侧还是回执侧、
|
||||
// 距尾多少个 assistant 轮后换单行占位」;只改发给上游的副本,DB/UI 不动。
|
||||
// 这里是默认策略的唯一来源:config.yml 写了 trim.rules 就整体替换(写 [] = 全关)。
|
||||
agent: { temperature: 1.0, max_tool_iterations: 100, max_retries: 2, language: 'Simplified Chinese', auto_compress_tokens: 60000, auto_complete_ms: 1800000, trim: {
|
||||
min_chars: 600,
|
||||
rules: [
|
||||
{ tool: 'write_file', side: 'args', fields: ['content'], rounds: 1 },
|
||||
{ tool: 'fetch', side: 'result', rounds: 2, status_regex: '^HTTP (\\d{3})' },
|
||||
{ tool: 'read_file', side: 'result', rounds: 2 },
|
||||
{ tool: 'web_search', side: 'result', rounds: 2 },
|
||||
],
|
||||
} },
|
||||
// 大图上传预处理(浏览器端 canvas 压缩,参数经 /api/system/status 下发前端)。
|
||||
// paste_to_file_threshold_chars:粘贴文本超过该字符数时前端转成 .txt 附件,0 = 关闭。
|
||||
upload: { image_compress_threshold_kb: 1536, image_max_dim: 2000, image_quality: 0.85, confirm_size_mb: 10, paste_to_file_threshold_chars: 2000 },
|
||||
@@ -236,10 +245,83 @@ function normalizePlatforms(rawPlatforms, profileNames) {
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---------- 历史重放的重负载占位裁剪(agent.trim) ----------
|
||||
// 语义:某条工具调用/回执距对话尾部 ≥rounds 个 assistant 轮后,把其中「可再生的重负载」
|
||||
// 换成单行占位再发给上游(llm.buildMessages;DB/UI 不动)。
|
||||
// 只该给「内容可再生或只是当时快照」的工具开:read_file/fetch 能重读重抓、write_file 参数
|
||||
// 只是快照;terminal 输出是一次性的,裁掉模型就永久看不到了。
|
||||
const TRIM_RULE_KEYS = new Set(['tool', 'side', 'rounds', 'fields', 'min_chars', 'status_regex']);
|
||||
|
||||
function toNonNegInt(v, d) {
|
||||
const n = Math.floor(Number(v));
|
||||
return Number.isFinite(n) ? Math.max(0, n) : d;
|
||||
}
|
||||
|
||||
// 单条规则校验:未知字段直接报错(拼错静默忽略 = 以为省了 token 其实没省)。
|
||||
function normalizeTrimRule(r, i, defMinChars) {
|
||||
const at = 'agent.trim.rules[' + i + ']';
|
||||
if (!r || typeof r !== 'object' || Array.isArray(r)) throw new Error(at + ' 必须是对象');
|
||||
for (const k of Object.keys(r)) {
|
||||
if (!TRIM_RULE_KEYS.has(k)) {
|
||||
throw new Error(at + ' 含未知字段:' + k + '(可用:' + Array.from(TRIM_RULE_KEYS).join(' / ') + ')');
|
||||
}
|
||||
}
|
||||
const tool = String(r.tool == null ? '' : r.tool).trim();
|
||||
if (!tool) throw new Error(at + ' 缺少 tool(填模型看到的最终工具名,MCP 重名时含 server__ 前缀)');
|
||||
const side = String(r.side == null ? '' : r.side).trim();
|
||||
if (side !== 'args' && side !== 'result') {
|
||||
throw new Error(at + '.side 只能是 args(裁调用参数)/ result(裁回执正文),收到:' + side);
|
||||
}
|
||||
// rounds=0 = 该条规则关闭;直接丢掉,不留空规则。
|
||||
const rounds = toNonNegInt(r.rounds, 0);
|
||||
if (rounds <= 0) return null;
|
||||
const out = { tool, side, rounds, min_chars: toNonNegInt(r.min_chars, defMinChars) };
|
||||
if (side === 'args') {
|
||||
if (!Array.isArray(r.fields) || !r.fields.length) {
|
||||
throw new Error(at + '(args 侧)必须配 fields 数组(要占位的顶层参数名,如 [content])');
|
||||
}
|
||||
out.fields = r.fields.map(x => String(x).trim()).filter(Boolean);
|
||||
if (!out.fields.length) throw new Error(at + '(args 侧)fields 不能为空');
|
||||
} else if (r.fields !== undefined) {
|
||||
throw new Error(at + '.fields 只适用于 args 侧(result 侧整段正文替换,无需点名字段)');
|
||||
}
|
||||
if (r.status_regex !== undefined && r.status_regex !== null && String(r.status_regex).trim()) {
|
||||
if (side !== 'result') throw new Error(at + '.status_regex 只适用于 result 侧');
|
||||
const src = String(r.status_regex);
|
||||
try { new RegExp(src); } catch (_) { throw new Error(at + '.status_regex 不是合法正则:' + src); }
|
||||
out.status_regex = src;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// agent.trim 归一:默认值来自 DEFAULTS.agent.trim.rules(唯一来源),config.yml 写了 rules
|
||||
// 就整体替换([] = 全关)。归一结果直接写回 cfg.agent.trim.rules,不再另造 trim_rules 键。
|
||||
function normalizeAgentTrim(cfg) {
|
||||
// 拷一份再改:无 agent 段时 cfg.agent 与 DEFAULTS.agent 是同一引用,直接写会污染默认值
|
||||
// (配置页反复校验时上一份的 trim 会漏给下一份)。
|
||||
const a = Object.assign({}, cfg.agent || {});
|
||||
cfg.agent = a;
|
||||
const trim = (a.trim && typeof a.trim === 'object' && !Array.isArray(a.trim)) ? a.trim : {};
|
||||
const defMinChars = toNonNegInt(trim.min_chars, DEFAULTS.agent.trim.min_chars);
|
||||
// undefined / null 都是「没配」,回落到 DEFAULTS(deepMerge 通常已把默认数组带进来,
|
||||
// 这里兜住 agent.trim: null 这类显式空值);显式 [] 才是全关。
|
||||
const rawRules = (trim.rules === undefined || trim.rules === null) ? DEFAULTS.agent.trim.rules : trim.rules;
|
||||
if (!Array.isArray(rawRules)) throw new Error('agent.trim.rules 必须是数组');
|
||||
const rules = rawRules.map((r, i) => normalizeTrimRule(r, i, defMinChars)).filter(Boolean);
|
||||
const seen = new Set();
|
||||
for (const r of rules) {
|
||||
const k = r.side + '\u0000' + r.tool;
|
||||
if (seen.has(k)) throw new Error('agent.trim.rules 重复声明同一工具同一侧:' + r.tool + '(' + r.side + ')');
|
||||
seen.add(k);
|
||||
}
|
||||
a.trim = Object.assign({}, trim, { min_chars: defMinChars, rules });
|
||||
}
|
||||
|
||||
// 校验原始配置文本(启动读文件与网页编辑共用)。configPath 仅记录来源,可为空。
|
||||
function parseAndValidate(rawText, configPath) {
|
||||
let raw = YAML.parse(rawText || '') || {};
|
||||
const cfg = deepMerge(DEFAULTS, raw);
|
||||
normalizeAgentTrim(cfg);
|
||||
|
||||
// ---------- 模型配置:platforms 层级(platforms[].models[] + platforms[].keys[])----------
|
||||
// models 提到平台层(与 url/type 同级),多 key 共用同一份 models。
|
||||
|
||||
+68
-33
@@ -199,8 +199,8 @@ function buildMessages(session, language, mintUrl, profile, withProfile, trimOn)
|
||||
for (const k of Array.from(session.blocksCache.keys())) if (!ids.has(k)) session.blocksCache.delete(k);
|
||||
}
|
||||
// 裁剪预扫:① 每行距尾的 assistant 轮数(从尾往头扫);② tool_call id → function
|
||||
// (给 fetch/read_file 占位回填 url/path)。trimOn=false 时整个跳过(压缩回合)。
|
||||
const trimActive = trimOn !== false && (TRIM.writeRounds > 0 || TRIM.resultRounds > 0);
|
||||
// (result 侧规则需要反查工具名)。trimOn=false(压缩回合)或没配规则时整个跳过。
|
||||
const trimActive = trimOn !== false && (TRIM.argsByTool.size > 0 || TRIM.resultByTool.size > 0);
|
||||
const roundsAfter = new Map();
|
||||
const callById = new Map();
|
||||
if (trimActive) {
|
||||
@@ -210,7 +210,7 @@ function buildMessages(session, language, mintUrl, profile, withProfile, trimOn)
|
||||
roundsAfter.set(r.id, n);
|
||||
if (r.role === 'assistant' && r.type !== 'archived' && r.type !== 'errAck') n++;
|
||||
}
|
||||
if (TRIM.resultRounds > 0) {
|
||||
if (TRIM.resultByTool.size > 0) {
|
||||
for (const r of history) {
|
||||
if (r.role !== 'assistant' || !r.tool_calls) continue;
|
||||
try { for (const c of JSON.parse(r.tool_calls) || []) if (c && c.id && c.function) callById.set(c.id, c.function); } catch (_) {}
|
||||
@@ -331,7 +331,7 @@ function buildMessages(session, language, mintUrl, profile, withProfile, trimOn)
|
||||
} else {
|
||||
m.tool_calls = paired;
|
||||
for (const c of paired) emittedCallIds.add(c.id);
|
||||
if (trimActive && TRIM.writeRounds > 0) trimWriteCalls(m.tool_calls, roundsAfter.get(row.id) || 0);
|
||||
if (trimActive && TRIM.argsByTool.size > 0) trimToolCallArgs(m.tool_calls, roundsAfter.get(row.id) || 0);
|
||||
}
|
||||
}
|
||||
if (!m.content) delete m.content;
|
||||
@@ -422,46 +422,81 @@ function buildMessages(session, language, mintUrl, profile, withProfile, trimOn)
|
||||
}
|
||||
|
||||
// ---------- 重负载占位裁剪(历史重放省 token) ----------
|
||||
// fetch/read_file 回执与 write_file 参数正文是重放里最贵的存量,且都可再生:文件在盘上、
|
||||
// 页面可重抓;write 参数只是当时快照(后续 edit_file 一次就失真,本就不该被当现势引用)。
|
||||
// 组装请求时对「距尾 ≥N 个 assistant 轮」的行换单行占位:纯函数、DB 不动(UI 工具卡照旧
|
||||
// 可展全量)、与压缩归档正交(archived 行本来就不进模型)。距离按现存行数 assistant 轮:
|
||||
// 策略只在配置里:默认值来自 config.js 的 DEFAULTS.agent.trim.rules,config.yml 写了
|
||||
// agent.trim.rules 就整体替换([] = 全关)。本模块不含任何工具名或默认阈值;未注入 = 不裁剪。
|
||||
// 语义:某条工具调用/回执距对话尾部 ≥rounds 个 assistant 轮后,把其中「可再生的重负载」
|
||||
// ——args 侧指定参数正文、result 侧整段回执——换成单行占位再发给上游。
|
||||
// 只应给可再生/快照型工具开规则:占位只改发给上游的副本(DB/UI 照旧可看全量),但模型侧
|
||||
// 一旦被裁就再也看不到那段内容(如 terminal 的一次性输出)。
|
||||
// 纯函数、与压缩归档正交(archived 行本来就不进模型)。距离按现存行数 assistant 轮:
|
||||
// 删中间消息可让已占位行短暂复活全文(一次性断前缀缓存,与图片消费 i<lastAck 同一
|
||||
// 语义,接受)。阈值可配(config agent.trim_write_rounds / trim_result_rounds,0=关),
|
||||
// 启动时 setPayloadTrim 注入。
|
||||
let TRIM = { writeRounds: 1, resultRounds: 2 };
|
||||
const TRIM_MIN_CHARS = 600; // 短正文不裁:占位行自身成本接近原文,裁了反而胀
|
||||
function setPayloadTrim(agentCfg) {
|
||||
const a = agentCfg || {};
|
||||
const toN = (v, d) => { const n = Math.floor(Number(v)); return Number.isFinite(n) ? Math.max(0, n) : d; };
|
||||
TRIM = { writeRounds: toN(a.trim_write_rounds, 1), resultRounds: toN(a.trim_result_rounds, 2) };
|
||||
// 语义,接受)。
|
||||
function compileTrimRules(rules) {
|
||||
const argsByTool = new Map();
|
||||
const resultByTool = new Map();
|
||||
for (const r of rules || []) {
|
||||
if (!r || !r.tool) continue;
|
||||
const rounds = Math.floor(Number(r.rounds));
|
||||
if (!(rounds > 0)) continue;
|
||||
const rule = {
|
||||
rounds,
|
||||
minChars: Math.max(0, Math.floor(Number(r.min_chars)) || 0),
|
||||
fields: Array.isArray(r.fields) ? r.fields.map(String) : [],
|
||||
statusRe: null,
|
||||
};
|
||||
if (r.side === 'result' && r.status_regex) {
|
||||
try { rule.statusRe = new RegExp(String(r.status_regex)); } catch (_) { /* config.js 已校验 */ }
|
||||
}
|
||||
if (r.side === 'args') argsByTool.set(String(r.tool), rule);
|
||||
else if (r.side === 'result') resultByTool.set(String(r.tool), rule);
|
||||
}
|
||||
return { argsByTool, resultByTool };
|
||||
}
|
||||
// write_file 参数占位:只洗 content。AI 友好记号风格:键值对、不写整句——path 不必重复,
|
||||
// 本条 arguments 里就还在;改写的是已 parse 副本,DB 行不动,重新 stringify 保持 JSON 合法。
|
||||
function trimWriteCalls(calls, rounds) {
|
||||
if (rounds < TRIM.writeRounds) return;
|
||||
let TRIM = compileTrimRules([]);
|
||||
function setPayloadTrim(agentCfg) {
|
||||
const trim = (agentCfg && agentCfg.trim && typeof agentCfg.trim === 'object' && !Array.isArray(agentCfg.trim))
|
||||
? agentCfg.trim : {};
|
||||
TRIM = compileTrimRules(Array.isArray(trim.rules) ? trim.rules : []);
|
||||
}
|
||||
function omittedMarker(size, extra) {
|
||||
return '[OMITTED' + (extra || '') + ', size=' + size + ']';
|
||||
}
|
||||
// args 侧占位:只洗规则点名的顶层字符串参数,其余参数原样保留(path/url 等恢复指针不动)。
|
||||
// 改写的是已 parse 副本,DB 行不动,重新 stringify 保持 JSON 合法。
|
||||
function trimToolCallArgs(calls, rounds) {
|
||||
for (const c of calls || []) {
|
||||
if (!c || !c.function || c.function.name !== 'write_file') continue;
|
||||
if (!c || !c.function) continue;
|
||||
const rule = TRIM.argsByTool.get(c.function.name);
|
||||
if (!rule || rounds < rule.rounds) continue;
|
||||
let args;
|
||||
try { args = JSON.parse(c.function.arguments || ''); } catch (_) { continue; }
|
||||
if (!args || typeof args.content !== 'string' || args.content.length < TRIM_MIN_CHARS) continue;
|
||||
args.content = '[OMITTED, size=' + args.content.length + ']';
|
||||
c.function.arguments = JSON.stringify(args);
|
||||
if (!args || typeof args !== 'object' || Array.isArray(args)) continue;
|
||||
let changed = false;
|
||||
for (const f of rule.fields) {
|
||||
const v = args[f];
|
||||
if (typeof v !== 'string' || v.length < rule.minChars) continue;
|
||||
args[f] = omittedMarker(v.length);
|
||||
changed = true;
|
||||
}
|
||||
if (changed) c.function.arguments = JSON.stringify(args);
|
||||
}
|
||||
}
|
||||
// fetch/read_file 回执占位:同款键值记号。url/path 不进占位——发起调用的 assistant 行仍载着
|
||||
// 它们,参数本身就是恢复指针。图片回执(blocks 非空)不碰:已有自己的消费省略逻辑。
|
||||
// result 侧占位:整段回执换单行。图片回执(blocks 非空)在上游分支里已还原成文字/图块,
|
||||
// 这里只处理纯文本;status_regex 可把状态码写进占位(如 fetch 的 HTTP 状态)。
|
||||
function trimToolContent(content, row, callById, roundsAfter) {
|
||||
if (TRIM.resultRounds <= 0 || content.length < TRIM_MIN_CHARS) return content;
|
||||
if ((roundsAfter.get(row.id) || 0) < TRIM.resultRounds) return content;
|
||||
if (typeof content !== 'string') return content;
|
||||
const fn = callById.get(row.tool_call_id);
|
||||
const name = row.name || (fn && fn.name) || '';
|
||||
if (name !== 'fetch' && name !== 'read_file') return content;
|
||||
if (name === 'fetch') {
|
||||
const hm = /^HTTP (\d{3})/.exec(content);
|
||||
return '[OMITTED' + (hm ? ', http_status=' + hm[1] : '') + ', size=' + content.length + ']';
|
||||
const rule = TRIM.resultByTool.get(name);
|
||||
if (!rule) return content;
|
||||
if ((roundsAfter.get(row.id) || 0) < rule.rounds) return content;
|
||||
if (content.length < rule.minChars) return content;
|
||||
let extra = '';
|
||||
if (rule.statusRe) {
|
||||
const m = rule.statusRe.exec(content);
|
||||
if (m && m[1]) extra = ', http_status=' + m[1];
|
||||
}
|
||||
return '[OMITTED, size=' + content.length + ']';
|
||||
return omittedMarker(content.length, extra);
|
||||
}
|
||||
|
||||
// 拼压缩回合的 messages(参考 titleMessages 的拼法):默认 system prompt + 正常历史
|
||||
|
||||
+17
-2
@@ -42,10 +42,25 @@
|
||||
{
|
||||
"key": "web_search",
|
||||
"label": "网页搜索",
|
||||
"desc": "栈内搜索服务,无需密钥",
|
||||
"desc": "内置免费搜索,也可接自建 /search",
|
||||
"url": "http://mcp_web_search:3000/",
|
||||
"mode": "advertise",
|
||||
"fields": []
|
||||
"fields": [
|
||||
{
|
||||
"header": "Authorization",
|
||||
"label": "鉴权",
|
||||
"secret": true,
|
||||
"prefix": "Bearer ",
|
||||
"placeholder": "API Key",
|
||||
"hint": "免费后端留空"
|
||||
},
|
||||
{
|
||||
"header": "X-Web-Search-Base-Url",
|
||||
"label": "地址",
|
||||
"placeholder": "https://<host>/v1",
|
||||
"hint": "留空用免费后端"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"key": "image_task",
|
||||
|
||||
@@ -18,7 +18,10 @@ const log = require('./log');
|
||||
|
||||
const cfg = loadConfig(process.env.AGENT_CONFIG);
|
||||
log.setLevel(cfg.log_level); // 分级日志开关(log.js;config.yml log_level,重启生效)
|
||||
llm.setPayloadTrim(cfg.agent); // 历史重放的重负载占位裁剪阈值(llm.buildMessages;config agent.trim_*)
|
||||
llm.setPayloadTrim(cfg.agent); // 历史重放的重负载占位裁剪规则(llm.buildMessages;config agent.trim.rules)
|
||||
// 启动时把生效规则打出来:工具名拼错不会报错(MCP 工具要等发现后才存在),只能靠这行核对。
|
||||
log.info('startup', '历史重放占位裁剪:' + (((cfg.agent && cfg.agent.trim && cfg.agent.trim.rules) || [])
|
||||
.map(r => r.tool + '/' + r.side + '≥' + r.rounds + '轮').join(', ') || '关闭'));
|
||||
const db = initDb(cfg.db_path);
|
||||
const bus = createBus();
|
||||
|
||||
|
||||
@@ -66,6 +66,11 @@ system prompt 不重复 schema 已表达的内容。
|
||||
|
||||
tools 数组每轮请求完整重发。新工具进来时,先问"能不能装进已有工具",再问"要不要新建"。
|
||||
|
||||
回执/参数里可能很大的内容,若**可再生**(文件在盘上可重读、页面可重抓)或只是当时快照,
|
||||
可在 `agent.trim.rules` 登记历史重放占位裁剪:距尾 ≥N 个 assistant 轮后换成单行占位
|
||||
(`app/server/llm.js` 的 `setPayloadTrim`;`side: args` 点名参数、`side: result` 裁整段回执)。
|
||||
一次性输出(`terminal`、外部服务扣额度的生成结果等)不要登记——裁掉后模型无法恢复。
|
||||
|
||||
### 九、回执形态
|
||||
|
||||
- **内容型**工具(`read_file` 的文本、`fetch` 的正文、`db` 的查询结果)回执就是内容本身,不要套 JSON 信封。
|
||||
|
||||
+11
-2
@@ -4,7 +4,7 @@
|
||||
|
||||
| 目录 | 容器名 | 作用 | 容器内端口 | MCP 端点 |
|
||||
|---|---|---|---|---|
|
||||
| `web_search/` | `mcp_web_search` | 免费网页搜索(Parallel / Exa,无需 key) | `3000` | `POST /` |
|
||||
| `web_search/` | `mcp_web_search` | 网页搜索(默认免费 Parallel / Exa,可换成自建 `/search` 上游) | `3000` | `POST /` |
|
||||
| `image_task/` | `mcp_image_task` | 图片生成 / 编辑(文生图走 `/images/generations`,图生图走 `/images/edits`,单工具 op=create/get) | `3000` | `POST /mcp` |
|
||||
| `video_task/` | `mcp_video_task` | 智谱 CogVideo 视频生成(异步,单工具 op=create/get) | `3000` | `POST /mcp` |
|
||||
| `asr/` | `mcp_asr` | 语音转文字(上游 OpenAI 兼容 `/audio/transcriptions`),**额外带一个给输入框用的 `POST /transcribe`** | `3000` | `POST /mcp` |
|
||||
@@ -27,6 +27,10 @@ docker compose up -d --build
|
||||
mcp_servers:
|
||||
- name: web_search
|
||||
url: "http://mcp_web_search:3000/"
|
||||
# 可选:换成自己的搜索接口(不配 = 内置免费后端 Parallel / Exa)
|
||||
# headers:
|
||||
# Authorization: Bearer <key>
|
||||
# X-Web-Search-Base-Url: "https://<host>/v1"
|
||||
- name: image_task
|
||||
url: "http://mcp_image_task:3000/mcp"
|
||||
- name: video_task
|
||||
@@ -51,6 +55,11 @@ mcp_servers:
|
||||
上游地址与模型分别由 `X-Image-Task-Base-Url` / `X-Image-Task-Model` 指定(两者都必填)。
|
||||
所以这两个服务不用配任何密钥。
|
||||
|
||||
`web_search` 同理:默认走内置免费后端(Parallel → Exa,无需 key);想换成自己的搜索接口,
|
||||
就在这段 headers 里写 `X-Web-Search-Base-Url`(容器拼 `/search`)与可选的 `Authorization`。
|
||||
一旦配了地址就以它为准——**失败直接报错,不会静默退回免费后端**(否则 key 过期 / 地址写错
|
||||
只会表现为「结果质量突然变差」)。
|
||||
|
||||
`asr` 同理:上游的 key / base_url / model 全部由调用方随请求 header 带入
|
||||
(`Authorization` / `X-ASR-Base-Url` / `X-ASR-Model`,agent 侧配在 `config.yml` 的
|
||||
`mcp_servers[name=asr].headers`)。输入框那条路(`agent-core` → `POST /transcribe`)不经过 MCP 调用,
|
||||
@@ -85,7 +94,7 @@ AI 把拿到的 URL 当 image_url 交给 video_task:3000/mcp
|
||||
|
||||
| 服务 | 公网暴露 | 说明 |
|
||||
|---|---|---|
|
||||
| `mcp_web_search` | 无 | 服务端无鉴权,**永远不要映射出去**(会被白嫖搜索额度);agent 走内网访问 |
|
||||
| `mcp_web_search` | 无 | 服务端无鉴权,**永远不要映射出去**(会被白嫖搜索额度;配了自定义上游时还会把你的 key 白送出去);agent 走内网访问 |
|
||||
| `mcp_image_task` | 无 | token 由调用方自带,暴露后可被拿去消耗你的上游图片额度 |
|
||||
| `mcp_video_task` | 无 | 它需要的公开临时 URL 由 agent 侧集成的工具提供,自己不占端口 |
|
||||
| `mcp_asr` | 无 | `/mcp` 与 `/transcribe` 都无鉴权,只能由 core 经内网调用;它不存密钥(上游参数随请求带入) |
|
||||
|
||||
@@ -1,15 +1,49 @@
|
||||
# web_search
|
||||
|
||||
免费网页搜索 MCP server 的本地重构版(上游开源实现:[@sheep233_/dsh-web-search-free](https://github.com/sheep-programmer/dsh-web-search-free),MIT)。
|
||||
网页搜索 MCP server 的本地重构版(上游开源实现:[@sheep233_/dsh-web-search-free](https://github.com/sheep-programmer/dsh-web-search-free),MIT)。
|
||||
|
||||
零运行时依赖,只用 Node 内置 `fetch`(Node ≥ 18),**无需 npm install,直接 `node server.js` 启动**。
|
||||
|
||||
## 三路上游
|
||||
|
||||
| 条件 | 走哪 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| 请求带了 `X-Web-Search-Base-Url` | 你的 `POST {base}/search` | key 可选(`Authorization`)。**失败直接报错,不静默退回免费后端** |
|
||||
| 没带 | Parallel(免费匿名) | 失败自动退 Exa |
|
||||
| stdio 模式 | 只能免费 | stdio 没有 HTTP header |
|
||||
|
||||
自定义上游的协议:
|
||||
|
||||
```http
|
||||
POST {base}/search
|
||||
Authorization: Bearer <key>
|
||||
Content-Type: application/json
|
||||
|
||||
{"query":"2027山东省考公告","max_results":5}
|
||||
```
|
||||
|
||||
```json
|
||||
{"query":"...","type":"text2text","results":[{"title":"...","url":"https://...","snippet":"..."}]}
|
||||
```
|
||||
|
||||
响应归一化成 `[{url, title?, snippet?, publishedAt?}]`:`results[]` 里没有 `url` 的条目丢弃,
|
||||
`snippet` 压平空白后**原样返回**(默认不截断);调用方传 `maxSnippetLength: 3000` 才会按该长度截断,
|
||||
`published_at` / `publishedAt` / `publish_date` 任一存在则映射为 `publishedAt`。
|
||||
|
||||
## 工具参数
|
||||
|
||||
| 参数 | 必填 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `query` | 是 | 搜什么 |
|
||||
| `numResults` | 否 | 返回条数,默认 8 |
|
||||
| `maxSnippetLength` | 否 | 每条 `snippet` 的最大字符数;**不传 = 不截断**(上游常给整段正文,长文本请自行控预算) |
|
||||
|
||||
## 结构
|
||||
|
||||
| 文件 | 职责 |
|
||||
| --- | --- |
|
||||
| `core.js` | 搜索后端:Parallel(默认)/ Exa(备用)免费 MCP 端点封装 + 响应解析 |
|
||||
| `mcp.js` | MCP 协议层:`web_search` 工具定义 + JSON-RPC 分发 |
|
||||
| `core.js` | 搜索后端:自定义 `/search` + Parallel / Exa 免费 MCP 端点封装 + 响应解析 |
|
||||
| `mcp.js` | MCP 协议层:`web_search` 工具定义 + JSON-RPC 分发 + 从 header 取上游参数 |
|
||||
| `server.js` | 入口:CLI 参数 + stdio / HTTP/SSE 双传输 |
|
||||
|
||||
## 本地启动
|
||||
@@ -33,6 +67,10 @@ MCP 端点:
|
||||
- `EXA_API_KEY` — 提升 Exa 匿名限额
|
||||
- `SEARCH_TIMEOUT_MS` — 上游搜索超时,默认 30000
|
||||
|
||||
上游地址 / 鉴权**不是**环境变量:由调用方随每个请求用 header 带入(见上面「三路上游」),
|
||||
agent 侧写在 `config.yml` 的 `mcp_servers[name=web_search].headers`。换接口只改 YAML + 重启 core,
|
||||
不碰 `.env`、不重建镜像;容器自身不存任何平台密钥。
|
||||
|
||||
## Docker
|
||||
|
||||
`docker-compose.yml` 中的 `mcp_web_search` 服务直接构建本目录,Dockerfile 已改为拷贝源码启动(不再有 `npm install -g`)。
|
||||
@@ -47,4 +85,4 @@ docker exec mcp_web_search node -e "fetch('http://localhost:3000/health').then(r
|
||||
# {"name":"web_search","version":"...","transport":"http/sse","port":3000}
|
||||
```
|
||||
|
||||
该服务**无服务端鉴权**(上游是免费端点),**永远不要**对外映射端口——会被白嫆搜索额度。
|
||||
该服务**无服务端鉴权**,**永远不要**对外映射端口——会被白嫖搜索额度(自定义上游时还会把你的 key 白送出去)。
|
||||
|
||||
+107
-13
@@ -1,9 +1,13 @@
|
||||
/**
|
||||
* 零依赖搜索核心:Parallel(默认,匿名免 key)与 Exa(备用)两个免费后端的统一封装。
|
||||
* 零依赖搜索核心:三路上游,统一归一化成 `{ url, title?, snippet?, publishedAt? }[]`。
|
||||
*
|
||||
* 只用 Node 内置 fetch,不依赖任何 npm 包。两个后端都是公开的免费 MCP 端点,
|
||||
* 本模块以 JSON-RPC `tools/call` 的方式直接调用它们,并归一化成统一的结果结构:
|
||||
* `{ url, title?, snippet?, publishedAt? }[]`。
|
||||
* - 自定义上游(`X-Web-Search-Base-Url` + `Authorization`):任意 `POST {base}/search`,
|
||||
* 请求体 `{ query, max_results }`、响应 `{ results: [{ title, url, snippet }] }`。
|
||||
* - Parallel(免费匿名 MCP 端点,默认后端)。
|
||||
* - Exa(免费 MCP 端点,Parallel 挂掉时的兜底)。
|
||||
*
|
||||
* 只用 Node 内置 fetch,不依赖任何 npm 包。免费侧两个后端都是公开的 MCP 端点,
|
||||
* 本模块以 JSON-RPC `tools/call` 的方式直接调用它们。
|
||||
*
|
||||
* 上游实现参考:@sheep233_/dsh-web-search-free(github.com/sheep-programmer/dsh-web-search-free)。
|
||||
*/
|
||||
@@ -13,9 +17,22 @@ export const PARALLEL_MCP_URL = 'https://search.parallel.ai/mcp';
|
||||
/** Exa 免费 MCP 端点(匿名可用;EXA_API_KEY 可提升限额)。 */
|
||||
export const EXA_MCP_URL = 'https://mcp.exa.ai/mcp';
|
||||
|
||||
const USER_AGENT = 'web_search/1.0.0';
|
||||
const USER_AGENT = 'web_search/1.1.0';
|
||||
/** 单次上游搜索请求的超时,避免远端挂起拖死 MCP 请求。 */
|
||||
const REQUEST_TIMEOUT_MS = Number(process.env.SEARCH_TIMEOUT_MS ?? 30_000);
|
||||
/**
|
||||
* snippet 一律截断:搜索结果会进历史,之后每一轮都可能被整条重放。
|
||||
* 有些上游(如自建 v1/search)的 snippet 是整段正文,不截等于白烧 token。
|
||||
*/
|
||||
/**
|
||||
* snippet 一律压平空白;是否截断由调用方传 maxSnippetLength 决定,缺省不截断。
|
||||
* 为什么默认不截:上限该由调用方按自己的上下文预算定,写死在服务里会让「换上游 = 悄悄丢内容」。
|
||||
*/
|
||||
export function capSnippet(text, max) {
|
||||
const s = String(text == null ? '' : text).replace(/\s+/g, ' ').trim();
|
||||
if (!Number.isFinite(max) || max <= 0 || s.length <= max) return s;
|
||||
return s.slice(0, max) + '…';
|
||||
}
|
||||
|
||||
/**
|
||||
* 向免费 MCP 端点发一次 `tools/call`,返回工具结果里的 text 载荷。
|
||||
@@ -74,7 +91,7 @@ export function extractToolText(body) {
|
||||
}
|
||||
|
||||
/** Parallel 响应解析:text 是内嵌 JSON `{ results: [...] }`。 */
|
||||
export function mapParallelResponse(text) {
|
||||
export function mapParallelResponse(text, maxSnippetLength) {
|
||||
let payload;
|
||||
try {
|
||||
payload = JSON.parse(text);
|
||||
@@ -84,10 +101,11 @@ export function mapParallelResponse(text) {
|
||||
const sources = [];
|
||||
for (const item of payload.results ?? []) {
|
||||
if (!item.url) continue;
|
||||
const snippet = item.excerpts?.length > 0 ? capSnippet(item.excerpts.join(' '), maxSnippetLength) : '';
|
||||
sources.push({
|
||||
url: item.url,
|
||||
...(item.title ? { title: item.title } : {}),
|
||||
...(item.excerpts?.length > 0 ? { snippet: item.excerpts.join(' ') } : {}),
|
||||
...(snippet ? { snippet } : {}),
|
||||
...(item.publish_date ? { publishedAt: item.publish_date } : {}),
|
||||
});
|
||||
}
|
||||
@@ -105,7 +123,7 @@ export function mapParallelResponse(text) {
|
||||
* <正文摘要>
|
||||
* ```
|
||||
*/
|
||||
export function parseExaText(text) {
|
||||
export function parseExaText(text, maxSnippetLength) {
|
||||
const blocks = text.split(/(?=^Title: )/m).filter((block) => block.trim().length > 0);
|
||||
const sources = [];
|
||||
for (const block of blocks) {
|
||||
@@ -114,28 +132,104 @@ export function parseExaText(text) {
|
||||
const title = block.match(/^Title: (.+)$/m)?.[1]?.trim();
|
||||
const published = block.match(/^Published: (.+)$/m)?.[1]?.trim();
|
||||
const highlights = block.split(/^Highlights:\s*$/m)[1]?.trim();
|
||||
const snippet = capSnippet(highlights, maxSnippetLength);
|
||||
sources.push({
|
||||
url,
|
||||
...(title ? { title } : {}),
|
||||
...(highlights ? { snippet: highlights.slice(0, 500) } : {}),
|
||||
...(snippet ? { snippet } : {}),
|
||||
...(published && published !== 'N/A' ? { publishedAt: published } : {}),
|
||||
});
|
||||
}
|
||||
return sources;
|
||||
}
|
||||
|
||||
/**
|
||||
* 自定义上游:`POST {base}/search`,body `{ query, max_results }`。
|
||||
* 配置了地址就以它为准——失败直接抛错,不静默退回免费后端(否则 key 过期/base 写错
|
||||
* 只会表现为「结果质量突然变差」,永远没人发现)。
|
||||
* @param {{ auth: string, base: string }} up 由 mcp.js 从请求 header 解析(容器不存密钥)
|
||||
* @param {number} [maxSnippetLength] 调用方要求的最大 snippet 长度;缺省不截断
|
||||
*/
|
||||
export async function customSearch(query, maxResults, up, maxSnippetLength) {
|
||||
const url = up.base.replace(/\/+$/, '') + '/search';
|
||||
const headers = {
|
||||
'content-type': 'application/json',
|
||||
'accept': 'application/json',
|
||||
'user-agent': USER_AGENT,
|
||||
};
|
||||
// 免鉴权的自建服务可省;有值才带,避免给上游塞一个空 Authorization 反而被拒
|
||||
if (up.auth) headers.authorization = up.auth;
|
||||
let response;
|
||||
try {
|
||||
response = await fetch(url, {
|
||||
method: 'POST',
|
||||
// 不跟随跳转:Authorization 不能被顺手带到别的地址去
|
||||
redirect: 'error',
|
||||
headers,
|
||||
body: JSON.stringify({ query, max_results: maxResults }),
|
||||
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
||||
});
|
||||
} catch (error) {
|
||||
throw new Error(`搜索上游请求失败(${url}):${String(error && error.message || error)}`);
|
||||
}
|
||||
const raw = await response.text();
|
||||
if (!response.ok) {
|
||||
// 带上游响应片段:401 和 500 的处置完全不同,只说「请求失败」没法排查
|
||||
const detail = capSnippet(raw, 200);
|
||||
throw new Error(`搜索上游 HTTP ${response.status}${detail ? ':' + detail : ''}`);
|
||||
}
|
||||
let payload;
|
||||
try {
|
||||
payload = JSON.parse(raw);
|
||||
} catch (error) {
|
||||
throw new Error(`搜索上游返回了无法解析的响应:${String(error)}`);
|
||||
}
|
||||
const sources = [];
|
||||
for (const item of payload.results ?? []) {
|
||||
if (!item || !item.url) continue;
|
||||
const snippet = capSnippet(item.snippet, maxSnippetLength);
|
||||
const publishedAt = item.published_at ?? item.publishedAt ?? item.publish_date;
|
||||
sources.push({
|
||||
url: String(item.url),
|
||||
...(item.title ? { title: String(item.title) } : {}),
|
||||
...(snippet ? { snippet } : {}),
|
||||
...(publishedAt ? { publishedAt: String(publishedAt) } : {}),
|
||||
});
|
||||
}
|
||||
return maxResults !== undefined ? sources.slice(0, maxResults) : sources;
|
||||
}
|
||||
|
||||
/** Parallel 搜索(默认免费后端)。 */
|
||||
export async function parallelSearch(query, maxResults) {
|
||||
export async function parallelSearch(query, maxResults, maxSnippetLength) {
|
||||
const text = await callMcpTool(PARALLEL_MCP_URL, 'web_search', {
|
||||
objective: query,
|
||||
search_queries: [query],
|
||||
}, AbortSignal.timeout(REQUEST_TIMEOUT_MS));
|
||||
const sources = mapParallelResponse(text);
|
||||
const sources = mapParallelResponse(text, maxSnippetLength);
|
||||
return maxResults !== undefined ? sources.slice(0, maxResults) : sources;
|
||||
}
|
||||
|
||||
/**
|
||||
* 免费侧入口:Parallel 优先,失败自动退 Exa。
|
||||
* 降级放在服务端(而不是让模型显式传 provider)——模型看不到后端,也就不会选错。
|
||||
* @param {string} [exaApiKey] 可选,提升 Exa 匿名限额
|
||||
* @param {number} [maxSnippetLength] 缺省不截断
|
||||
*/
|
||||
export async function freeSearch(query, maxResults, exaApiKey, maxSnippetLength) {
|
||||
try {
|
||||
return await parallelSearch(query, maxResults, maxSnippetLength);
|
||||
} catch (first) {
|
||||
try {
|
||||
return await exaSearch(query, maxResults, exaApiKey, maxSnippetLength);
|
||||
} catch (second) {
|
||||
throw new Error(`免费搜索后端均不可用(parallel: ${String(first && first.message || first)};` +
|
||||
`exa: ${String(second && second.message || second)})`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Exa 搜索(备用免费后端;apiKey 可选,用于提升匿名限额)。 */
|
||||
export async function exaSearch(query, maxResults, apiKey) {
|
||||
export async function exaSearch(query, maxResults, apiKey, maxSnippetLength) {
|
||||
const endpoint = apiKey
|
||||
? `${EXA_MCP_URL}?exaApiKey=${encodeURIComponent(apiKey)}`
|
||||
: EXA_MCP_URL;
|
||||
@@ -145,6 +239,6 @@ export async function exaSearch(query, maxResults, apiKey) {
|
||||
numResults: maxResults ?? 8,
|
||||
livecrawl: 'fallback',
|
||||
}, AbortSignal.timeout(REQUEST_TIMEOUT_MS));
|
||||
const sources = parseExaText(text);
|
||||
const sources = parseExaText(text, maxSnippetLength);
|
||||
return maxResults !== undefined ? sources.slice(0, maxResults) : sources;
|
||||
}
|
||||
|
||||
+59
-16
@@ -2,34 +2,59 @@
|
||||
* MCP(Model Context Protocol)协议层:工具清单 + JSON-RPC 分发。
|
||||
*
|
||||
* 与传输无关(stdio / HTTP 都在 server.js 里),只负责把一条 JSON-RPC
|
||||
* 消息变成 JSON-RPC 响应。支持的 method 与上游 dsh-web-search-free 一致:
|
||||
* initialize / tools/list / tools/call / ping。
|
||||
* 消息变成 JSON-RPC 响应。支持的 method:initialize / tools/list / tools/call / ping。
|
||||
*
|
||||
* 上游参数逐请求从 HTTP header 取(与 mcp/asr、mcp/image_task 同构):
|
||||
* X-Web-Search-Base-Url: https://<host>/v1 → 打 {base}/search(配了就用它,不降级)
|
||||
* Authorization: Bearer <key> → 可选,裸 key 自动补 Bearer
|
||||
* 两者都不配 = 内置免费后端(Parallel → Exa)。stdio 模式没有 header,因此只有免费后端。
|
||||
*/
|
||||
import { parallelSearch, exaSearch } from './core.js';
|
||||
import { customSearch, freeSearch } from './core.js';
|
||||
|
||||
export const SERVER_NAME = 'web_search';
|
||||
export const VERSION = '1.0.0';
|
||||
export const VERSION = '1.1.0';
|
||||
const DEFAULT_PROTOCOL = '2025-03-26';
|
||||
const HDR_AUTH = 'authorization';
|
||||
const HDR_BASE = 'x-web-search-base-url';
|
||||
|
||||
/** 暴露给 MCP 客户端的工具清单。 */
|
||||
const TOOLS = [
|
||||
{
|
||||
name: 'web_search',
|
||||
description: 'Free web search tool. Uses Parallel by default or Exa as fallback. Returns an array of results with title, url, snippet, and publishedAt.',
|
||||
description: 'Search the web. Returns results with title, url, snippet and (when available) publishedAt.',
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
query: { type: 'string', description: 'Search query text' },
|
||||
provider: { type: 'string', enum: ['parallel', 'exa'], description: "Backend provider: 'parallel' (default) or 'exa' (fallback)" },
|
||||
numResults: { type: 'integer', minimum: 1, default: 8, description: 'Maximum number of results to return (default 8)' },
|
||||
maxSnippetLength: { type: 'integer', minimum: 1, description: 'Truncate each snippet to this many characters (default: keep full text)' },
|
||||
},
|
||||
required: ['query'],
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
/** 执行一次 tools/call;失败时抛 { code, message } 表示工具级错误。 */
|
||||
async function callTool(name, args) {
|
||||
/** 从请求 header 取上游两要素;Authorization 允许写裸 key(自动补 Bearer)。 */
|
||||
function upstreamOf(headers) {
|
||||
const h = headers || {};
|
||||
const raw = String(h[HDR_AUTH] || '').trim();
|
||||
return {
|
||||
auth: raw ? (/^bearer\s/i.test(raw) ? raw : 'Bearer ' + raw) : '',
|
||||
base: String(h[HDR_BASE] || '').trim().replace(/\/+$/, ''),
|
||||
};
|
||||
}
|
||||
|
||||
/** 配了地址就必须是完整 http(s):不能是相对路径,也不能把 key 发到别的协议上。 */
|
||||
function assertBase(base) {
|
||||
let u = null;
|
||||
try { u = new URL(base); } catch (_) { u = null; }
|
||||
if (!u || (u.protocol !== 'http:' && u.protocol !== 'https:')) {
|
||||
throw new Error('X-Web-Search-Base-Url 必须是完整的 http(s) 地址,如 https://<host>/v1');
|
||||
}
|
||||
}
|
||||
|
||||
/** 执行一次 tools/call;失败时抛 { code, message } 表示协议级错误。 */
|
||||
async function callTool(name, args, headers) {
|
||||
if (name !== 'web_search') throw { code: -32602, message: `unknown tool: ${name}` };
|
||||
|
||||
const params = args ?? {};
|
||||
@@ -38,20 +63,36 @@ async function callTool(name, args) {
|
||||
: null;
|
||||
if (query === null) throw { code: -32602, message: 'query is required' };
|
||||
|
||||
const provider = params.provider === 'exa' ? 'exa' : 'parallel';
|
||||
const numResults = typeof params.numResults === 'number' && Number.isFinite(params.numResults)
|
||||
? Math.max(1, Math.floor(params.numResults))
|
||||
: 8;
|
||||
// 截断是调用方的选择:不传就原样返回整段 snippet(上游可能给整篇正文,由调用方自己控上下文)
|
||||
const rawMaxLen = Number(params.maxSnippetLength);
|
||||
const maxSnippetLength = Number.isFinite(rawMaxLen) && rawMaxLen >= 1 ? Math.floor(rawMaxLen) : undefined;
|
||||
|
||||
const sources = provider === 'exa'
|
||||
? await exaSearch(query, numResults, process.env.EXA_API_KEY)
|
||||
: await parallelSearch(query, numResults);
|
||||
const up = upstreamOf(headers);
|
||||
let sources;
|
||||
try {
|
||||
if (up.base) {
|
||||
assertBase(up.base);
|
||||
sources = await customSearch(query, numResults, up, maxSnippetLength);
|
||||
} else {
|
||||
sources = await freeSearch(query, numResults, process.env.EXA_API_KEY, maxSnippetLength);
|
||||
}
|
||||
} catch (error) {
|
||||
// 工具级错误回文本、协议层仍成功:模型能读懂并换查询/换工具,
|
||||
// 回 JSON-RPC error 只会被 core 拼成「调用失败」,模型反而不好自纠。
|
||||
return {
|
||||
isError: true,
|
||||
content: [{ type: 'text', text: 'Error: ' + String(error && error.message || error) }],
|
||||
};
|
||||
}
|
||||
|
||||
return { content: [{ type: 'text', text: JSON.stringify(sources, null, 2) }] };
|
||||
}
|
||||
|
||||
/** 处理一条请求消息,返回 result;失败时抛 { code, message }。 */
|
||||
async function handleRequest(message) {
|
||||
async function handleRequest(message, headers) {
|
||||
switch (message.method) {
|
||||
case 'initialize':
|
||||
return {
|
||||
@@ -62,7 +103,7 @@ async function handleRequest(message) {
|
||||
case 'tools/list':
|
||||
return { tools: TOOLS };
|
||||
case 'tools/call':
|
||||
return callTool(message.params?.name, message.params?.arguments);
|
||||
return callTool(message.params?.name, message.params?.arguments, headers);
|
||||
case 'ping':
|
||||
return {};
|
||||
default:
|
||||
@@ -72,9 +113,11 @@ async function handleRequest(message) {
|
||||
|
||||
/**
|
||||
* 解析并执行一条 JSON 消息。
|
||||
* @param {string} raw JSON-RPC 文本
|
||||
* @param {object} [headers] 本次 HTTP 请求的 header(stdio 模式没有,上游参数就走免费后端)
|
||||
* @returns 响应信封对象;notification(无 id)返回 null;非法 JSON 返回 undefined。
|
||||
*/
|
||||
export async function dispatch(raw) {
|
||||
export async function dispatch(raw, headers) {
|
||||
let message;
|
||||
try {
|
||||
message = JSON.parse(raw);
|
||||
@@ -83,7 +126,7 @@ export async function dispatch(raw) {
|
||||
}
|
||||
if (message.id === undefined) return null; // 通知不响应
|
||||
try {
|
||||
return { jsonrpc: '2.0', id: message.id, result: await handleRequest(message) };
|
||||
return { jsonrpc: '2.0', id: message.id, result: await handleRequest(message, headers) };
|
||||
} catch (error) {
|
||||
const e = error;
|
||||
return {
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
{
|
||||
"name": "web_search",
|
||||
"version": "1.0.0",
|
||||
"version": "1.1.0",
|
||||
"private": true,
|
||||
"description": "Free web search tool. Uses Parallel by default or Exa as fallback.",
|
||||
"description": "Web search tool. Uses a caller-provided /search endpoint when configured, otherwise free Parallel / Exa backends.",
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
"main": "server.js",
|
||||
|
||||
@@ -1,16 +1,22 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* MCP server 入口 —— 免费网页搜索(Parallel 默认 / Exa 备用,匿名免 key)。
|
||||
* MCP server 入口 —— 网页搜索(自定义 /search 上游,或内置免费 Parallel / Exa)。
|
||||
*
|
||||
* 本地重构版(上游:@sheep233_/dsh-web-search-free),零运行时依赖,直接 node 启动。
|
||||
*
|
||||
* ## 双传输
|
||||
* - **stdio**(默认):`node server.js`
|
||||
* - `claude mcp add web_search -- node <路径>/server.js`
|
||||
* - 没有 HTTP header,因此只能用内置免费后端
|
||||
* - **HTTP/SSE**(监听端口):`node server.js --http --port 3000 --host 0.0.0.0`
|
||||
* - 兼容 Streamable HTTP(`POST /`)与老式 SSE(`GET /sse` + `POST /messages`)
|
||||
* - `GET /` 或 `GET /health` 返回服务信息,可做健康检查
|
||||
*
|
||||
* 上游参数逐请求从 HTTP header 取(与 mcp/asr、mcp/image_task 同构,容器不存密钥):
|
||||
* X-Web-Search-Base-Url: https://<host>/v1 → 打 {base}/search
|
||||
* Authorization: Bearer <key> → 可选,裸 key 自动补 Bearer
|
||||
* 两者都不配 = 免费后端。
|
||||
*
|
||||
* 环境变量:EXA_API_KEY(可选,提升 Exa 匿名限额);SEARCH_TIMEOUT_MS(可选,上游超时)。
|
||||
*/
|
||||
import { createInterface } from 'node:readline';
|
||||
@@ -88,7 +94,8 @@ function runHttp(host, port) {
|
||||
let body = '';
|
||||
req.on('data', (chunk) => { body += chunk.toString(); });
|
||||
req.on('end', () => {
|
||||
void dispatch(body).then((response) => {
|
||||
// header 必须随消息带进协议层:上游地址 / 鉴权都是逐请求带入的(容器不存密钥)
|
||||
void dispatch(body, req.headers).then((response) => {
|
||||
if (response === null) { // 通知
|
||||
res.writeHead(202).end();
|
||||
return;
|
||||
|
||||
Reference in New Issue
Block a user