DeepSeek Harness (DSH) 联网搜索避坑与国内免代理 MCP 打造实战

一、 悬案:为什么我的 DeepSeek API 被频繁扣费? 最近在使用 DSH 进行项目开发时,我们在后台监控到了极其异常的 API 调用波形: 高频消耗:在昨天下午和今天上午,累计产生了近数百次官方 API 请求; 高度重合:消耗的时 …

一、 悬案:为什么我的 DeepSeek API 被频繁扣费?

最近在使用 DSH 进行项目开发时,我们在后台监控到了极其异常的 API 调用波形:

  • 高频消耗:在昨天下午和今天上午,累计产生了近数百次官方 API 请求;
  • 高度重合:消耗的时间窗口与开发者本地活跃敲代码、执行 Agent 任务的时间 100% 严密对齐;
  • 极度异常的缓存命中率:在 DeepSeek 开发者后台,这些调用的 Prompt Cache 命中率竟不足 10%!这意味着绝大多数调用都在以全额原价计费。

起初我们怀疑是:

  1. 模型路由名称配置混淆?(比如某些反代渠道带有 deepseek/ 前缀导致误匹配到官方渠道)
  2. 或者是 API Key 泄露?

但在全量解包分析了 DSH 的本地底层会话日志(多帧 Zstandard 压缩格式)后,排查结果令人大吃一惊:所有常规对话、子代理对话走官方渠道的次数居然是 0 次!

那么,扣费到底从何而来?

二、 破案:揭开内置 web_search 的“Token 刺客”面目

翻阅 DSH 源码中负责网络检索的包 @deepseek-ai/dsh-web-search-deepseek,我们在其核心逻辑中找到了真相:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
/**
 * DeepSeek search through an Anthropic-compatible Messages model call 
 * with the native `web_search_20250305` server tool. 
 * Each search costs a model turn...
 */
const endpoint = "https://api.deepseek.com/anthropic/v1/messages";
const body = {
    model: "deepseek-v4-flash",     // 用的根本不是普通搜索引擎接口,而是直接跑大模型!
    max_tokens: 4096,
    messages: [{
        role: "user",
        content: [{ type: "text", text: `Perform a web search for the query: ${request.query}` }]
    }],
    tools: [{
        type: "web_search_20250305", // 挂载服务端搜索工具
        name: "web_search",
        max_uses: 5
    }]
};

痛点根因:

  1. 它不是专用搜索引擎,而是一次完整的 LLM 推理(Model Turn)
    • 很多开发者以为内置的 web_search 是像 Google Custom Search 或 Bing API 那样按“次”计费(比如几厘钱查一次);
    • 但 DSH 默认捆绑的搜索机制,是启动一个 deepseek-v4-flash 大模型,让模型调用服务端工具抓取网页,再把抓到的海量网页内容塞回给模型阅读并输出摘要
  2. 为什么缓存命中率不足 10%?
    • 官方模型的上下文缓存(Cache Hit)要求有较长且相同的历史前缀(Prefix Cache);
    • 但这个搜索插件每次发出的请求都是冷启动的独立单句(Perform a web search for the query: [全新关键词]),没有任何历史上下文复用;
    • 结果就是:抓回来的网页 Token 全额按原价计费,每次检索都在狠狠燃烧你的官方账户余额!
  3. 静默调用,账本不可见
    • 该插件使用的是私有 HTTP Client 直接读取环境中的 DEEPSEEK_API_KEY,绕过了 DSH 的通用模型计费拦截层,在常规的聊天 Token 统计中根本看不到它。

三、 国内网络环境的第二重困境

既然官方的搜索机制既费钱又隐蔽,那换成社区主流的搜索方案可行吗?

  • Brave Search MCP:DSH 官方推荐,但我们在国内网络环境下实测 api.search.brave.com,直接 10000ms 超时中断,没有全局科学上网几乎不可用;
  • DuckDuckGo / Google:国内直连同样被阻断;
  • 第三方商业搜索 API(如 SerpApi、Tavily):需要绑定海外信用卡、申请 API Key,且存在每月的免费调用限额。

核心诉求:我们能不能做一个国内免代理直连(100~300ms 极速响应)、无需任何 API Key、零额外费用、永不扣大模型 Token 的纯净搜索服务?

答案是:完全可以,利用 DSH 原生一等公民支持的 MCP(Model Context Protocol)协议!

四、 彻底改造实战:两步实现免代理无痛检索

第一步:彻底封印内置大模型搜索(止血)

在 DSH 的全局补丁配置文件 $DSH_HOME/cordis.patch.yml 中,将内置搜索插件显式禁用:

1
2
3
# 禁用 DSH 内置的 DeepSeek 官方联网搜索插件,杜绝后台 web_search 静默消耗 DEEPSEEK_API_KEY
- id: web-search-deepseek
  disabled: true

注:DSH 具备 patchReload: live 特性,保存后热重载机制会立即卸载该插件,不用重启服务,彻底切断扣费源头。

第二步:纯原生 Node.js 实现国内直连双引擎 MCP

为了避免 Windows 权限沙盒下的 npm 缓存锁定问题(EPERM: operation not permitted),我们不引入任何外部第三方 npm 依赖,仅使用 Node.js 原生的 httpsreadline 模块,编写一个极度轻量、毫秒级响应的标准 MCP 服务端。

它整合了微软必应中国(cn.bing.com,实测延迟 300ms)百度搜索(www.baidu.com,实测延迟 170ms),具备自动双引擎故障回退。

新建文件 $DSH_HOME/scripts/mcp-cn-search.js

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
#!/usr/bin/env node
/**
 * MCP Server: CN Direct Search (免代理国内直连搜索引擎 MCP)
 * 纯原生 Node.js 实现,零外部依赖,安全稳定。
 */

const https = require("https");
const http = require("http");
const readline = require("readline");
const { URL } = require("url");

function decodeHtml(html) {
  if (!html) return "";
  return html
    .replace(/&/g, "&")
    .replace(/&lt;/g, "<")
    .replace(/&gt;/g, ">")
    .replace(/&quot;/g, '"')
    .replace(/&#039;/g, "'")
    .replace(/&#x27;/g, "'")
    .replace(/&ensp;/g, " ")
    .replace(/&emsp;/g, " ")
    .replace(/&nbsp;/g, " ")
    .replace(/&#0183;/g, "·")
    .replace(/<[^>]+>/g, " ")
    .replace(/\s+/g, " ")
    .trim();
}

function fetchHttp(targetUrl, timeoutMs = 8000) {
  return new Promise((resolve, reject) => {
    const parsed = new URL(targetUrl);
    const client = parsed.protocol === "http:" ? http : https;
    const req = client.get(
      targetUrl,
      {
        headers: {
          "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/122.0.0.0 Safari/537.36",
          "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
          Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
        },
        timeout: timeoutMs,
      },
      (res) => {
        if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
          const nextUrl = new URL(res.headers.location, targetUrl).toString();
          return fetchHttp(nextUrl, timeoutMs).then(resolve, reject);
        }
        let data = "";
        res.on("data", (chunk) => (data += chunk));
        res.on("end", () => resolve({ statusCode: res.statusCode, body: data }));
      }
    );
    req.on("error", reject);
    req.on("timeout", () => {
      req.destroy();
      reject(new Error(`Request timeout after ${timeoutMs}ms`));
    });
  });
}

// 必应中国解析
async function searchBing(query, count = 8) {
  const url = `https://cn.bing.com/search?q=${encodeURIComponent(query)}&setlang=zh-Hans`;
  const res = await fetchHttp(url);
  const blocks = res.body.split(/<li class="b_algo"/);
  const results = [];

  for (let i = 1; i < blocks.length && results.length < count; i++) {
    const b = blocks[i];
    const h2Match = b.match(/<h2[^>]*><a[^>]+href="([^"]+)"[^>]*>([\s\S]*?)<\/a><\/h2>/);
    if (!h2Match) continue;
    const link = h2Match[1];
    const title = decodeHtml(h2Match[2]);
    const pMatch = b.match(/<p[^>]*>([\s\S]*?)<\/p>/);
    const snippet = pMatch ? decodeHtml(pMatch[1]) : "";
    if (title && link) {
      results.push({ title, url: link, snippet, engine: "bing" });
    }
  }
  return results;
}

// 百度搜索解析
async function searchBaidu(query, count = 8) {
  const url = `https://www.baidu.com/s?wd=${encodeURIComponent(query)}&ie=utf-8`;
  const res = await fetchHttp(url);
  const blocks = res.body.split(/<div class="[a-z0-9-_ ]*c-container/);
  const results = [];

  for (let i = 1; i < blocks.length && results.length < count; i++) {
    const b = blocks[i];
    const h3Match = b.match(/<h3[^>]*>[\s\S]*?<a[^>]+href="([^"]+)"[^>]*>([\s\S]*?)<\/a>[\s\S]*?<\/h3>/);
    if (!h3Match) continue;
    const link = h3Match[1];
    const title = decodeHtml(h3Match[2]);
    let snippet = "";
    const spanMatch = b.match(/<span class="[a-z0-9-_ ]*content-right_[\s\S]*?>([\s\S]*?)<\/span>/) ||
                      b.match(/<div class="[a-z0-9-_ ]*c-abstract[^"]*">([\s\S]*?)<\/div>/);
    if (spanMatch) snippet = decodeHtml(spanMatch[1]);
    if (title && link) {
      results.push({ title, url: link, snippet, engine: "baidu" });
    }
  }
  return results;
}

// 自动选优与回退
async function doSearch(query, count = 8, engine = "auto") {
  if (engine === "bing") return await searchBing(query, count);
  if (engine === "baidu") return await searchBaidu(query, count);
  try {
    const r = await searchBing(query, count);
    if (r && r.length > 0) return r;
  } catch (e) {}
  try {
    return await searchBaidu(query, count);
  } catch (e) {
    return [];
  }
}

// 网页正文提取
async function fetchPage(url) {
  const res = await fetchHttp(url, 10000);
  const html = res.body;
  const titleMatch = html.match(/<title[^>]*>([\s\S]*?)<\/title>/i);
  const title = titleMatch ? decodeHtml(titleMatch[1]) : "";
  const clean = html
    .replace(/<script[\s\S]*?<\/script>/gi, "")
    .replace(/<style[\s\S]*?<\/style>/gi, "")
    .replace(/<nav[\s\S]*?<\/nav>/gi, "")
    .replace(/<footer[\s\S]*?<\/footer>/gi, "");
  return { title, url, content: decodeHtml(clean).slice(0, 10000) };
}

// MCP 标准工具清单
const TOOLS = [
  {
    name: "cn_web_search",
    description: "国内免代理搜索引擎(必应中国+百度)。无需 API Key,免翻墙,响应极速。",
    inputSchema: {
      type: "object",
      properties: {
        query: { type: "string", description: "搜索关键词" },
        count: { type: "number", description: "返回数量(默认 8 条)" },
        engine: { type: "string", enum: ["auto", "bing", "baidu"], description: "指定引擎" }
      },
      required: ["query"]
    }
  },
  {
    name: "cn_fetch_url",
    description: "抓取并解析网页纯文本正文内容。",
    inputSchema: {
      type: "object",
      properties: {
        url: { type: "string", description: "网页 URL" }
      },
      required: ["url"]
    }
  }
];

// MCP JSON-RPC 2.0 通信处理
const rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: false });
function send(msg) { process.stdout.write(JSON.stringify(msg) + "\n"); }

rl.on("line", async (line) => {
  if (!line.trim()) return;
  let req;
  try { req = JSON.parse(line); } catch (e) { return; }
  const { id, method, params } = req;

  if (method === "initialize") {
    return send({
      jsonrpc: "2.0",
      id,
      result: {
        protocolVersion: "2024-11-05",
        capabilities: { tools: {} },
        serverInfo: { name: "mcp-cn-search", version: "1.0.0" }
      }
    });
  }
  if (method === "notifications/initialized" || method === "ping") {
    if (id !== undefined) send({ jsonrpc: "2.0", id, result: {} });
    return;
  }
  if (method === "tools/list") {
    return send({ jsonrpc: "2.0", id, result: { tools: TOOLS } });
  }
  if (method === "tools/call") {
    try {
      if (params.name === "cn_web_search") {
        const res = await doSearch(params.arguments?.query, params.arguments?.count || 8, params.arguments?.engine || "auto");
        return send({ jsonrpc: "2.0", id, result: { content: [{ type: "text", text: JSON.stringify(res, null, 2) }] } });
      }
      if (params.name === "cn_fetch_url") {
        const res = await fetchPage(params.arguments?.url);
        return send({ jsonrpc: "2.0", id, result: { content: [{ type: "text", text: JSON.stringify(res, null, 2) }] } });
      }
    } catch (err) {
      return send({ jsonrpc: "2.0", id, result: { isError: true, content: [{ type: "text", text: err.message }] } });
    }
  }
});

第三步:在 DSH 中挂载该 MCP

编辑 $DSH_HOME/cordis.patch.yml,在 insert 列表中加入该服务:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
- insert:
    # CN Direct Search: 国内免代理直连中文搜索引擎
    - id: mcp-cn-search
      name: '@deepseek-ai/dsh-mcp-client'
      config:
        serverName: cn-search
        transport: stdio
        command: node
        args:
          - !!js dshHomePath('scripts', 'mcp-cn-search.js')
        reconnect:
          enabled: true

注意:在 YAML 中传递动态路径参数时,使用标准的缩进多行列表(如上所示),避免由于行内方括号解析导致语法报错。

五、 实操效果检验

配置完成后,在终端中使用命令校验 DSH 组合层:

1
dsh --profile web --dump-config

你可以看到 mcp-cn-search 已正常装载,而 web-search-deepseek 已明确处于 disabled: true 状态。

在日常与 Agent 对话时:

  • Agent 获得专属工具:mcp__cn-search__cn_web_searchmcp__cn-search__cn_fetch_url
  • 输入搜索请求,平均 200ms 内即刻返回结构化网页列表(含标题、原文链接和摘要);
  • Token 消耗归零,从此彻底告别月底 API 账单的“意外惊喜”!

六、 总结与结语

AI Agent 框架目前百花齐放,但在底层实现上,不同的搜索与检索机制往往存在着成本与网络陷阱。DeepSeek Harness 原生的设计初衷是让模型借助服务端大模型去理解网页,但在实际工程与国内网络环境下,往往会演变成“既花钱又连不上海外引擎”的双重尴尬。

通过禁用官方高消耗搜索 + 挂载本地原生直连 MCP,我们在保证开发体验顺畅的同时,兼顾了极致的成本控制与直连稳定性。希望这篇实战记录能为同样在折腾 DSH 的开发者们提供清晰的排查思路与落地参考!

2026-09-16 07:51